diff --git a/.gitignore b/.gitignore index 1dd3b77523..3b7223108b 100644 --- a/.gitignore +++ b/.gitignore @@ -26,3 +26,4 @@ cms/static/sass/*.css lms/lib/comment_client/python nosetests.xml cover_html/ +.idea/ diff --git a/brew-formulas.txt b/brew-formulas.txt index 0aed9645d0..b5b555e2a0 100644 --- a/brew-formulas.txt +++ b/brew-formulas.txt @@ -7,3 +7,4 @@ python yuicompressor node graphviz +mysql diff --git a/cms/.coveragerc b/cms/.coveragerc new file mode 100644 index 0000000000..42638feb8f --- /dev/null +++ b/cms/.coveragerc @@ -0,0 +1,13 @@ +# .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 diff --git a/cms/envs/test.py b/cms/envs/test.py index 7dcd32caab..d55c309827 100644 --- a/cms/envs/test.py +++ b/cms/envs/test.py @@ -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') diff --git a/common/djangoapps/pipeline_mako/templates/static_content.html b/common/djangoapps/pipeline_mako/templates/static_content.html index c153da22fe..302d4d7aa5 100644 --- a/common/djangoapps/pipeline_mako/templates/static_content.html +++ b/common/djangoapps/pipeline_mako/templates/static_content.html @@ -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: diff --git a/common/djangoapps/student/management/commands/pearson_export_cdd.py b/common/djangoapps/student/management/commands/pearson_export_cdd.py new file mode 100644 index 0000000000..b10e92d92d --- /dev/null +++ b/common/djangoapps/student/management/commands/pearson_export_cdd.py @@ -0,0 +1,156 @@ +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 = '' + 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 diff --git a/common/djangoapps/student/management/commands/pearson_export_ead.py b/common/djangoapps/student/management/commands/pearson_export_ead.py new file mode 100644 index 0000000000..415f0812ae --- /dev/null +++ b/common/djangoapps/student/management/commands/pearson_export_ead.py @@ -0,0 +1,150 @@ +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 = '' + 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 diff --git a/common/djangoapps/student/management/commands/pearson_make_tc_user.py b/common/djangoapps/student/management/commands/pearson_make_tc_user.py new file mode 100644 index 0000000000..d974c25b6b --- /dev/null +++ b/common/djangoapps/student/management/commands/pearson_make_tc_user.py @@ -0,0 +1,85 @@ +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 = "" + 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() diff --git a/common/djangoapps/student/migrations/0020_add_test_center_user.py b/common/djangoapps/student/migrations/0020_add_test_center_user.py new file mode 100644 index 0000000000..e308e2d7e0 --- /dev/null +++ b/common/djangoapps/student/migrations/0020_add_test_center_user.py @@ -0,0 +1,188 @@ +# -*- coding: utf-8 -*- +import datetime +from south.db import db +from south.v2 import SchemaMigration +from django.db import models + + +class Migration(SchemaMigration): + + def forwards(self, orm): + # Adding model 'TestCenterUser' + db.create_table('student_testcenteruser', ( + ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), + ('user', self.gf('django.db.models.fields.related.ForeignKey')(default=None, to=orm['auth.User'], unique=True)), + ('created_at', self.gf('django.db.models.fields.DateTimeField')(auto_now_add=True, db_index=True, blank=True)), + ('updated_at', self.gf('django.db.models.fields.DateTimeField')(auto_now=True, db_index=True, blank=True)), + ('user_updated_at', self.gf('django.db.models.fields.DateTimeField')(db_index=True)), + ('candidate_id', self.gf('django.db.models.fields.IntegerField')(null=True, db_index=True)), + ('client_candidate_id', self.gf('django.db.models.fields.CharField')(max_length=50, db_index=True)), + ('first_name', self.gf('django.db.models.fields.CharField')(max_length=30, db_index=True)), + ('last_name', self.gf('django.db.models.fields.CharField')(max_length=50, db_index=True)), + ('middle_name', self.gf('django.db.models.fields.CharField')(max_length=30, blank=True)), + ('suffix', self.gf('django.db.models.fields.CharField')(max_length=255, blank=True)), + ('salutation', self.gf('django.db.models.fields.CharField')(max_length=50, blank=True)), + ('address_1', self.gf('django.db.models.fields.CharField')(max_length=40)), + ('address_2', self.gf('django.db.models.fields.CharField')(max_length=40, blank=True)), + ('address_3', self.gf('django.db.models.fields.CharField')(max_length=40, blank=True)), + ('city', self.gf('django.db.models.fields.CharField')(max_length=32, db_index=True)), + ('state', self.gf('django.db.models.fields.CharField')(db_index=True, max_length=20, blank=True)), + ('postal_code', self.gf('django.db.models.fields.CharField')(db_index=True, max_length=16, blank=True)), + ('country', self.gf('django.db.models.fields.CharField')(max_length=3, db_index=True)), + ('phone', self.gf('django.db.models.fields.CharField')(max_length=35)), + ('extension', self.gf('django.db.models.fields.CharField')(db_index=True, max_length=8, blank=True)), + ('phone_country_code', self.gf('django.db.models.fields.CharField')(max_length=3, db_index=True)), + ('fax', self.gf('django.db.models.fields.CharField')(max_length=35, blank=True)), + ('fax_country_code', self.gf('django.db.models.fields.CharField')(max_length=3, blank=True)), + ('company_name', self.gf('django.db.models.fields.CharField')(max_length=50, blank=True)), + )) + db.send_create_signal('student', ['TestCenterUser']) + + + def backwards(self, orm): + # Deleting model 'TestCenterUser' + db.delete_table('student_testcenteruser') + + + models = { + 'auth.group': { + 'Meta': {'object_name': 'Group'}, + 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), + 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), + 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) + }, + 'auth.permission': { + 'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'}, + 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), + 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}), + 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), + 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) + }, + 'auth.user': { + 'Meta': {'object_name': 'User'}, + 'about': ('django.db.models.fields.TextField', [], {'blank': 'True'}), + 'avatar_type': ('django.db.models.fields.CharField', [], {'default': "'n'", 'max_length': '1'}), + 'bronze': ('django.db.models.fields.SmallIntegerField', [], {'default': '0'}), + 'consecutive_days_visit_count': ('django.db.models.fields.IntegerField', [], {'default': '0'}), + 'country': ('django_countries.fields.CountryField', [], {'max_length': '2', 'blank': 'True'}), + 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), + 'date_of_birth': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}), + 'display_tag_filter_strategy': ('django.db.models.fields.SmallIntegerField', [], {'default': '0'}), + 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), + 'email_isvalid': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), + 'email_key': ('django.db.models.fields.CharField', [], {'max_length': '32', 'null': 'True'}), + 'email_tag_filter_strategy': ('django.db.models.fields.SmallIntegerField', [], {'default': '1'}), + 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), + 'gold': ('django.db.models.fields.SmallIntegerField', [], {'default': '0'}), + 'gravatar': ('django.db.models.fields.CharField', [], {'max_length': '32'}), + 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}), + 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), + 'ignored_tags': ('django.db.models.fields.TextField', [], {'blank': 'True'}), + 'interesting_tags': ('django.db.models.fields.TextField', [], {'blank': 'True'}), + 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), + 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), + 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), + 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), + 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), + 'last_seen': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), + 'location': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}), + 'new_response_count': ('django.db.models.fields.IntegerField', [], {'default': '0'}), + 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), + 'questions_per_page': ('django.db.models.fields.SmallIntegerField', [], {'default': '10'}), + 'real_name': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}), + 'reputation': ('django.db.models.fields.PositiveIntegerField', [], {'default': '1'}), + 'seen_response_count': ('django.db.models.fields.IntegerField', [], {'default': '0'}), + 'show_country': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), + 'silver': ('django.db.models.fields.SmallIntegerField', [], {'default': '0'}), + 'status': ('django.db.models.fields.CharField', [], {'default': "'w'", 'max_length': '2'}), + 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), + 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}), + 'website': ('django.db.models.fields.URLField', [], {'max_length': '200', 'blank': 'True'}) + }, + 'contenttypes.contenttype': { + 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, + 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), + 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), + 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), + 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) + }, + 'student.courseenrollment': { + 'Meta': {'unique_together': "(('user', 'course_id'),)", 'object_name': 'CourseEnrollment'}, + 'course_id': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_index': 'True'}), + 'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'null': 'True', 'db_index': 'True', 'blank': 'True'}), + 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), + 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}) + }, + 'student.pendingemailchange': { + 'Meta': {'object_name': 'PendingEmailChange'}, + 'activation_key': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '32', 'db_index': 'True'}), + 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), + 'new_email': ('django.db.models.fields.CharField', [], {'db_index': 'True', 'max_length': '255', 'blank': 'True'}), + 'user': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['auth.User']", 'unique': 'True'}) + }, + 'student.pendingnamechange': { + 'Meta': {'object_name': 'PendingNameChange'}, + 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), + 'new_name': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}), + 'rationale': ('django.db.models.fields.CharField', [], {'max_length': '1024', 'blank': 'True'}), + 'user': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['auth.User']", 'unique': 'True'}) + }, + 'student.registration': { + 'Meta': {'object_name': 'Registration', 'db_table': "'auth_registration'"}, + 'activation_key': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '32', 'db_index': 'True'}), + 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), + 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'unique': 'True'}) + }, + 'student.testcenteruser': { + 'Meta': {'object_name': 'TestCenterUser'}, + 'address_1': ('django.db.models.fields.CharField', [], {'max_length': '40'}), + 'address_2': ('django.db.models.fields.CharField', [], {'max_length': '40', 'blank': 'True'}), + 'address_3': ('django.db.models.fields.CharField', [], {'max_length': '40', 'blank': 'True'}), + 'candidate_id': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'db_index': 'True'}), + 'city': ('django.db.models.fields.CharField', [], {'max_length': '32', 'db_index': 'True'}), + 'client_candidate_id': ('django.db.models.fields.CharField', [], {'max_length': '50', 'db_index': 'True'}), + 'company_name': ('django.db.models.fields.CharField', [], {'max_length': '50', 'blank': 'True'}), + 'country': ('django.db.models.fields.CharField', [], {'max_length': '3', 'db_index': 'True'}), + 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'db_index': 'True', 'blank': 'True'}), + 'extension': ('django.db.models.fields.CharField', [], {'db_index': 'True', 'max_length': '8', 'blank': 'True'}), + 'fax': ('django.db.models.fields.CharField', [], {'max_length': '35', 'blank': 'True'}), + 'fax_country_code': ('django.db.models.fields.CharField', [], {'max_length': '3', 'blank': 'True'}), + 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'db_index': 'True'}), + 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), + 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '50', 'db_index': 'True'}), + 'middle_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), + 'phone': ('django.db.models.fields.CharField', [], {'max_length': '35'}), + 'phone_country_code': ('django.db.models.fields.CharField', [], {'max_length': '3', 'db_index': 'True'}), + 'postal_code': ('django.db.models.fields.CharField', [], {'db_index': 'True', 'max_length': '16', 'blank': 'True'}), + 'salutation': ('django.db.models.fields.CharField', [], {'max_length': '50', 'blank': 'True'}), + 'state': ('django.db.models.fields.CharField', [], {'db_index': 'True', 'max_length': '20', 'blank': 'True'}), + 'suffix': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}), + 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'db_index': 'True', 'blank': 'True'}), + 'user': ('django.db.models.fields.related.ForeignKey', [], {'default': 'None', 'to': "orm['auth.User']", 'unique': 'True'}), + 'user_updated_at': ('django.db.models.fields.DateTimeField', [], {'db_index': 'True'}) + }, + 'student.userprofile': { + 'Meta': {'object_name': 'UserProfile', 'db_table': "'auth_userprofile'"}, + 'courseware': ('django.db.models.fields.CharField', [], {'default': "'course.xml'", 'max_length': '255', 'blank': 'True'}), + 'gender': ('django.db.models.fields.CharField', [], {'db_index': 'True', 'max_length': '6', 'null': 'True', 'blank': 'True'}), + 'goals': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), + 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), + 'language': ('django.db.models.fields.CharField', [], {'db_index': 'True', 'max_length': '255', 'blank': 'True'}), + 'level_of_education': ('django.db.models.fields.CharField', [], {'db_index': 'True', 'max_length': '6', 'null': 'True', 'blank': 'True'}), + 'location': ('django.db.models.fields.CharField', [], {'db_index': 'True', 'max_length': '255', 'blank': 'True'}), + 'mailing_address': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), + 'meta': ('django.db.models.fields.TextField', [], {'blank': 'True'}), + 'name': ('django.db.models.fields.CharField', [], {'db_index': 'True', 'max_length': '255', 'blank': 'True'}), + 'user': ('django.db.models.fields.related.OneToOneField', [], {'related_name': "'profile'", 'unique': 'True', 'to': "orm['auth.User']"}), + 'year_of_birth': ('django.db.models.fields.IntegerField', [], {'db_index': 'True', 'null': 'True', 'blank': 'True'}) + }, + 'student.usertestgroup': { + 'Meta': {'object_name': 'UserTestGroup'}, + 'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}), + 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), + 'name': ('django.db.models.fields.CharField', [], {'max_length': '32', 'db_index': 'True'}), + 'users': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.User']", 'db_index': 'True', 'symmetrical': 'False'}) + } + } + + complete_apps = ['student'] \ No newline at end of file diff --git a/common/djangoapps/student/models.py b/common/djangoapps/student/models.py index 82b3acbbf3..0eded21df1 100644 --- a/common/djangoapps/student/models.py +++ b/common/djangoapps/student/models.py @@ -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 diff --git a/common/djangoapps/student/views.py b/common/djangoapps/student/views.py index 2b940fe982..e7562f83d0 100644 --- a/common/djangoapps/student/views.py +++ b/common/djangoapps/student/views.py @@ -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() diff --git a/common/lib/capa/.coveragerc b/common/lib/capa/.coveragerc new file mode 100644 index 0000000000..6af3218f75 --- /dev/null +++ b/common/lib/capa/.coveragerc @@ -0,0 +1,13 @@ +# .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 diff --git a/common/lib/capa/capa/capa_problem.py b/common/lib/capa/capa/capa_problem.py index 1c31725e4b..451891d067 100644 --- a/common/lib/capa/capa/capa_problem.py +++ b/common/lib/capa/capa/capa_problem.py @@ -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 ... 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) diff --git a/common/lib/capa/capa/chem/chemtools.py b/common/lib/capa/capa/chem/chemtools.py index e5a8e1a6f6..ad6633fc00 100644 --- a/common/lib/capa/capa/chem/chemtools.py +++ b/common/lib/capa/capa/chem/chemtools.py @@ -1,63 +1,143 @@ -from collections import OrderedDict +"""This module originally includes functions for grading Vsepr problems. + +Also, may be this module is the place for other chemistry-related grade functions. TODO: discuss it. +""" + import json import unittest +import itertools def vsepr_parse_user_answer(user_input): - d = OrderedDict(json.loads(user_input)) - d['atoms'] = OrderedDict(sorted(d['atoms'].items())) - return d + """ + user_input is json generated by vsepr.js from dictionary. + There are must be only two keys in original user_input dictionary: "geometry" and "atoms". + Format: u'{"geometry": "AX3E0","atoms":{"c0": "B","p0": "F","p1": "B","p2": "F"}}' + Order of elements inside "atoms" subdict does not matters. + Return dict from parsed json. + + "Atoms" subdict stores positions of atoms in molecule. + General types of positions: + c0 - central atom + p0..pN - peripheral atoms + a0..aN - axial atoms + e0..eN - equatorial atoms + + Each position is dictionary key, i.e. user_input["atoms"]["c0"] is central atom, user_input["atoms"]["a0"] is one of axial atoms. + + Special position only for AX6 (Octahedral) geometry: + e10, e12 - atom pairs opposite the central atom, + e20, e22 - atom pairs opposite the central atom, + e1 and e2 pairs lying crosswise in equatorial plane. + + In user_input["atoms"] may be only 3 set of keys: + (c0,p0..pN), + (c0, a0..aN, e0..eN), + (c0, a0, a1, e10,e11,e20,e21) - if geometry is AX6. + """ + return json.loads(user_input) def vsepr_build_correct_answer(geometry, atoms): - correct_answer = OrderedDict() - correct_answer['geometry'] = geometry - correct_answer['atoms'] = OrderedDict(sorted(atoms.items())) - return correct_answer - - -def vsepr_grade(user_input, correct_answer, ignore_p_order=False, ignore_a_order=False, ignore_e_order=False): - """ Flags ignore_(a,p,e)_order are for checking order in axial, perepherial or equatorial positions. - Allowed cases: - c0, a, e - c0, p - Not implemented and not tested cases when p with a or e (no need for now) """ - # print user_input, type(user_input) - # print correct_answer, type(correct_answer) + geometry is string. + atoms is dict of atoms with proper positions. + Example: + + correct_answer = vsepr_build_correct_answer(geometry="AX4E0", atoms={"c0": "N", "p0": "H", "p1": "(ep)", "p2": "H", "p3": "H"}) + + returns a dictionary composed from input values: + {'geometry': geometry, 'atoms': atoms} + """ + return {'geometry': geometry, 'atoms': atoms} + + +def vsepr_grade(user_input, correct_answer, convert_to_peripheral=False): + """ + This function does comparison between user_input and correct_answer. + + Comparison is successful if all steps are successful: + + 1) geometries are equal + 2) central atoms (index in dictionary 'c0') are equal + 3): + In next steps there is comparing of corresponding subsets of atom positions: equatorial (e0..eN), axial (a0..aN) or peripheral (p0..pN) + + If convert_to_peripheral is True, then axial and equatorial positions are converted to peripheral. + This means that user_input from: + "atoms":{"c0": "Br","a0": "test","a1": "(ep)","e10": "H","e11": "(ep)","e20": "H","e21": "(ep)"}}' after parsing to json + is converted to: + {"c0": "Br", "p0": "(ep)", "p1": "test", "p2": "H", "p3": "H", "p4": "(ep)", "p6": "(ep)"} + i.e. aX and eX -> pX + + So if converted, p subsets are compared, + if not a and e subsets are compared + If all subsets are equal, grade succeeds. + + There is also one special case for AX6 geometry. + In this case user_input["atoms"] contains special 3 symbol keys: e10, e12, e20, and e21. + Correct answer for this geometry can be of 3 types: + 1) c0 and peripheral + 2) c0 and axial and equatorial + 3) c0 and axial and equatorial-subset-1 (e1X) and equatorial-subset-2 (e2X) + + If correct answer is type 1 or 2, then user_input is converted from type 3 to type 2 (or to type 1 if convert_to_peripheral is True) + + If correct_answer is type 3, then we done special case comparison. We have 3 sets of atoms positions both in user_input and correct_answer: axial, eq-1 and eq-2. + Answer will be correct if these sets are equals for one of permutations. For example, if : + user_axial = correct_eq-1 + user_eq-1 = correct-axial + user_eq-2 = correct-eq-2 + + """ if user_input['geometry'] != correct_answer['geometry']: return False if user_input['atoms']['c0'] != correct_answer['atoms']['c0']: return False - # not order-aware comparisons - for ignore in [(ignore_p_order, 'p'), (ignore_e_order, 'e'), (ignore_a_order, 'a')]: - if ignore[0]: + if convert_to_peripheral: + # convert user_input from (a,e,e1,e2) to (p) + # correct_answer must be set in (p) using this flag + c0 = user_input['atoms'].pop('c0') + user_input['atoms'] = {'p' + str(i): v for i, v in enumerate(user_input['atoms'].values())} + user_input['atoms']['c0'] = c0 + + # special case for AX6 + if 'e10' in correct_answer['atoms']: # need check e1x, e2x symmetry for AX6.. + a_user = {} + a_correct = {} + for ea_position in ['a', 'e1', 'e2']: # collecting positions: + a_user[ea_position] = [v for k, v in user_input['atoms'].items() if k.startswith(ea_position)] + a_correct[ea_position] = [v for k, v in correct_answer['atoms'].items() if k.startswith(ea_position)] + + correct = [sorted(a_correct['a'])] + [sorted(a_correct['e1'])] + [sorted(a_correct['e2'])] + for permutation in itertools.permutations(['a', 'e1', 'e2']): + if correct == [sorted(a_user[permutation[0]])] + [sorted(a_user[permutation[1]])] + [sorted(a_user[permutation[2]])]: + return True + return False + + else: # no need to check e1x,e2x symmetry - convert them to ex + if 'e10' in user_input['atoms']: # e1x exists, it is AX6.. case + e_index = 0 + for k, v in user_input['atoms'].items(): + if len(k) == 3: # e1x + del user_input['atoms'][k] + user_input['atoms']['e' + str(e_index)] = v + e_index += 1 + + # common case + for ea_position in ['p', 'a', 'e']: # collecting atoms: - a_user = [v for k, v in user_input['atoms'].items() if k.startswith(ignore[1])] - a_correct = [v for k, v in correct_answer['atoms'].items() if k.startswith(ignore[1])] - # print ignore[0], ignore[1], a_user, a_correct + a_user = [v for k, v in user_input['atoms'].items() if k.startswith(ea_position)] + a_correct = [v for k, v in correct_answer['atoms'].items() if k.startswith(ea_position)] + # print a_user, a_correct if len(a_user) != len(a_correct): return False if sorted(a_user) != sorted(a_correct): return False - # order-aware comparisons - for ignore in [(ignore_p_order, 'p'), (ignore_e_order, 'e'), (ignore_a_order, 'a')]: - if not ignore[0]: - # collecting atoms: - a_user = [v for k, v in user_input['atoms'].items() if k.startswith(ignore[1])] - a_correct = [v for k, v in correct_answer['atoms'].items() if k.startswith(ignore[1])] - # print '2nd', ignore[0], ignore[1], a_user, a_correct - if len(a_user) != len(a_correct): - return False - if len(a_correct) == 0: - continue - if a_user != a_correct: - return False - - return True + return True class Test_Grade(unittest.TestCase): @@ -65,63 +145,53 @@ class Test_Grade(unittest.TestCase): def test_incorrect_geometry(self): correct_answer = vsepr_build_correct_answer(geometry="AX4E0", atoms={"c0": "N", "p0": "H", "p1": "(ep)", "p2": "H", "p3": "H"}) - user_answer = vsepr_parse_user_answer(u'{"geometry":"AX3E0","atoms":{"c0":"B","p0":"F","p1":"B","p2":"F"}}') + user_answer = vsepr_parse_user_answer(u'{"geometry": "AX3E0","atoms":{"c0": "B","p0": "F","p1": "B","p2": "F"}}') self.assertFalse(vsepr_grade(user_answer, correct_answer)) - def test_incorrect_positions(self): + def test_correct_answer_p(self): correct_answer = vsepr_build_correct_answer(geometry="AX4E0", atoms={"c0": "N", "p0": "H", "p1": "(ep)", "p2": "H", "p3": "H"}) - user_answer = vsepr_parse_user_answer(u'{"geometry":"AX4E0","atoms":{"c0":"B","p0":"F","p1":"B","p2":"F"}}') - self.assertFalse(vsepr_grade(user_answer, correct_answer)) - - def test_correct_answer(self): - correct_answer = vsepr_build_correct_answer(geometry="AX4E0", atoms={"c0": "N", "p0": "H", "p1": "(ep)", "p2": "H", "p3": "H"}) - user_answer = vsepr_parse_user_answer(u'{"geometry":"AX4E0","atoms":{"c0":"N","p0":"H","p1":"(ep)","p2":"H", "p3":"H"}}') + user_answer = vsepr_parse_user_answer(u'{"geometry": "AX4E0","atoms":{"c0": "N","p0": "H","p1": "(ep)","p2": "H", "p3": "H"}}') self.assertTrue(vsepr_grade(user_answer, correct_answer)) - def test_incorrect_position_order_p(self): - correct_answer = vsepr_build_correct_answer(geometry="AX4E0", atoms={"c0": "N", "p0": "H", "p1": "(ep)", "p2": "H", "p3": "H"}) - user_answer = vsepr_parse_user_answer(u'{"geometry":"AX4E0","atoms":{"c0":"N","p0":"H","p1":"H","p2":"(ep)", "p3":"H"}}') - self.assertFalse(vsepr_grade(user_answer, correct_answer)) - - def test_correct_position_order_with_ignore_p_order(self): - correct_answer = vsepr_build_correct_answer(geometry="AX4E0", atoms={"c0": "N", "p0": "H", "p1": "(ep)", "p2": "H", "p3": "H"}) - user_answer = vsepr_parse_user_answer(u'{"geometry":"AX4E0","atoms":{"c0":"N","p0":"H","p1":"H","p2":"(ep)", "p3":"H"}}') - self.assertTrue(vsepr_grade(user_answer, correct_answer, ignore_p_order=True)) - - def test_incorrect_position_order_ae(self): + def test_correct_answer_ae(self): correct_answer = vsepr_build_correct_answer(geometry="AX6E0", atoms={"c0": "Br", "a0": "test", "a1": "(ep)", "e0": "H", "e1": "H", "e2": "(ep)", "e3": "(ep)"}) - user_answer = vsepr_parse_user_answer(u'{"geometry":"AX6E0","atoms":{"c0":"Br","a0":"test","a1":"(ep)","e0":"H","e1":"(ep)","e2":"(ep)","e3":"(ep)"}}') - self.assertFalse(vsepr_grade(user_answer, correct_answer)) + user_answer = vsepr_parse_user_answer(u'{"geometry": "AX6E0","atoms":{"c0": "Br","a0": "test","a1": "(ep)","e10": "H","e11": "H","e20": "(ep)","e21": "(ep)"}}') + self.assertTrue(vsepr_grade(user_answer, correct_answer)) - def test_correct_position_order_with_ignore_a_order_not_e(self): + def test_correct_answer_ae_convert_to_p_but_input_not_in_p(self): correct_answer = vsepr_build_correct_answer(geometry="AX6E0", atoms={"c0": "Br", "a0": "(ep)", "a1": "test", "e0": "H", "e1": "H", "e2": "(ep)", "e3": "(ep)"}) - user_answer = vsepr_parse_user_answer(u'{"geometry":"AX6E0","atoms":{"c0":"Br","a0":"test","a1":"(ep)","e0":"H","e1":"H","e2":"(ep)","e3":"(ep)"}}') - self.assertTrue(vsepr_grade(user_answer, correct_answer, ignore_a_order=True)) + user_answer = vsepr_parse_user_answer(u'{"geometry": "AX6E0","atoms":{"c0": "Br","a0": "test","a1": "(ep)","e10": "H","e11": "(ep)","e20": "H","e21": "(ep)"}}') + self.assertFalse(vsepr_grade(user_answer, correct_answer, convert_to_peripheral=True)) - def test_incorrect_position_order_with_ignore_a_order_not_e(self): - correct_answer = vsepr_build_correct_answer(geometry="AX6E0", atoms={"c0": "Br", "a0": "(ep)", "a1": "test", "e0": "H", "e1": "H", "e2": "H", "e3": "(ep)"}) - user_answer = vsepr_parse_user_answer(u'{"geometry":"AX6E0","atoms":{"c0":"Br","a0":"test","a1":"(ep)","e0":"H","e1":"H","e2":"(ep)","e3":"H"}}') - self.assertFalse(vsepr_grade(user_answer, correct_answer, ignore_a_order=True)) + def test_correct_answer_ae_convert_to_p(self): + correct_answer = vsepr_build_correct_answer(geometry="AX6E0", atoms={"c0": "Br", "p0": "(ep)", "p1": "test", "p2": "H", "p3": "H", "p4": "(ep)", "p6": "(ep)"}) + user_answer = vsepr_parse_user_answer(u'{"geometry": "AX6E0","atoms":{"c0": "Br","a0": "test","a1": "(ep)","e10": "H","e11": "(ep)","e20": "H","e21": "(ep)"}}') + self.assertTrue(vsepr_grade(user_answer, correct_answer, convert_to_peripheral=True)) - def test_correct_position_order_with_ignore_e_order_not_a(self): - correct_answer = vsepr_build_correct_answer(geometry="AX6E0", atoms={"c0": "Br", "a0": "(ep)", "a1": "test", "e0": "H", "e1": "H", "e2": "H", "e3": "(ep)"}) - user_answer = vsepr_parse_user_answer(u'{"geometry":"AX6E0","atoms":{"c0":"Br","a0":"(ep)","a1":"test","e0":"H","e1":"H","e2":"(ep)","e3":"H"}}') - self.assertTrue(vsepr_grade(user_answer, correct_answer, ignore_e_order=True)) + def test_correct_answer_e1e2_in_a(self): + correct_answer = vsepr_build_correct_answer(geometry="AX6E0", atoms={"c0": "Br", "a0": "(ep)", "a1": "(ep)", "e10": "H", "e11": "H", "e20": "H", "e21": "H"}) + user_answer = vsepr_parse_user_answer(u'{"geometry": "AX6E0","atoms":{"c0": "Br","a0": "(ep)","a1": "(ep)","e10": "H","e11": "H","e20": "H","e21": "H"}}') + self.assertTrue(vsepr_grade(user_answer, correct_answer)) - def test_incorrect_position_order_with_ignore_e_order__not_a(self): - correct_answer = vsepr_build_correct_answer(geometry="AX6E0", atoms={"c0": "Br", "a0": "(ep)", "a1": "test", "e0": "H", "e1": "H", "e2": "H", "e3": "(ep)"}) - user_answer = vsepr_parse_user_answer(u'{"geometry":"AX6E0","atoms":{"c0":"Br","a0":"test","a1":"(ep)","e0":"H","e1":"H","e2":"(ep)","e3":"H"}}') - self.assertFalse(vsepr_grade(user_answer, correct_answer, ignore_e_order=True)) + def test_correct_answer_e1e2_in_e1(self): + correct_answer = vsepr_build_correct_answer(geometry="AX6E0", atoms={"c0": "Br", "a0": "(ep)", "a1": "(ep)", "e10": "H", "e11": "H", "e20": "H", "e21": "H"}) + user_answer = vsepr_parse_user_answer(u'{"geometry": "AX6E0","atoms":{"c0": "Br","a0": "H","a1": "H","e10": "(ep)","e11": "(ep)","e20": "H","e21": "H"}}') + self.assertTrue(vsepr_grade(user_answer, correct_answer)) - def test_correct_position_order_with_ignore_ae_order(self): - correct_answer = vsepr_build_correct_answer(geometry="AX6E0", atoms={"c0": "Br", "a0": "(ep)", "a1": "test", "e0": "H", "e1": "H", "e2": "H", "e3": "(ep)"}) - user_answer = vsepr_parse_user_answer(u'{"geometry":"AX6E0","atoms":{"c0":"Br","a0":"test","a1":"(ep)","e0":"H","e1":"H","e2":"(ep)","e3":"H"}}') - self.assertTrue(vsepr_grade(user_answer, correct_answer, ignore_e_order=True, ignore_a_order=True)) + def test_correct_answer_e1e2_in_e2(self): + correct_answer = vsepr_build_correct_answer(geometry="AX6E0", atoms={"c0": "Br", "a0": "(ep)", "a1": "(ep)", "e10": "H", "e11": "H", "e20": "H", "e21": "H"}) + user_answer = vsepr_parse_user_answer(u'{"geometry": "AX6E0","atoms":{"c0": "Br","a0": "H","a1": "H","e10": "H","e11": "H","e20": "(ep)","e21": "(ep)"}}') + self.assertTrue(vsepr_grade(user_answer, correct_answer)) + + def test_incorrect_answer_e1e2(self): + correct_answer = vsepr_build_correct_answer(geometry="AX6E0", atoms={"c0": "Br", "a0": "(ep)", "a1": "(ep)", "e10": "H", "e11": "H", "e20": "H", "e21": "H"}) + user_answer = vsepr_parse_user_answer(u'{"geometry": "AX6E0","atoms":{"c0": "Br","a0": "H","a1": "H","e10": "(ep)","e11": "H","e20": "H","e21": "(ep)"}}') + self.assertFalse(vsepr_grade(user_answer, correct_answer)) def test_incorrect_c0(self): correct_answer = vsepr_build_correct_answer(geometry="AX6E0", atoms={"c0": "Br", "a0": "(ep)", "a1": "test", "e0": "H", "e1": "H", "e2": "H", "e3": "(ep)"}) - user_answer = vsepr_parse_user_answer(u'{"geometry":"AX6E0","atoms":{"c0":"H","a0":"test","a1":"(ep)","e0":"H","e1":"H","e2":"(ep)","e3":"H"}}') - self.assertFalse(vsepr_grade(user_answer, correct_answer, ignore_e_order=True, ignore_a_order=True)) + user_answer = vsepr_parse_user_answer(u'{"geometry": "AX6E0","atoms":{"c0": "H","a0": "test","a1": "(ep)","e0": "H","e1": "H","e2": "(ep)","e3": "H"}}') + self.assertFalse(vsepr_grade(user_answer, correct_answer)) def suite(): diff --git a/common/lib/capa/capa/correctmap.py b/common/lib/capa/capa/correctmap.py index 3c4f43a1d6..c7386219b1 100644 --- a/common/lib/capa/capa/correctmap.py +++ b/common/lib/capa/capa/correctmap.py @@ -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 diff --git a/common/lib/capa/capa/customrender.py b/common/lib/capa/capa/customrender.py new file mode 100644 index 0000000000..ef1044e8b1 --- /dev/null +++ b/common/lib/capa/capa/customrender.py @@ -0,0 +1,100 @@ +""" +This has custom renderers: classes that know how to render certain problem tags (e.g. and +) 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: + + $\displaystyle U(r)=4 U_0 $ + $r_0$ + + 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 = '%s%s' % ( + self.mathstr, saxutils.escape(self.xml.tail)) + try: + xhtml = etree.XML(html) + except Exception as err: + if self.system.DEBUG: + msg = '

Error %s

' % ( + str(err).replace('<', '<')) + msg += ('

Failed to construct math expression from

%s

' % + html.replace('<', '<')) + msg += "
" + log.error(msg) + return etree.XML(msg) + else: + raise + return xhtml + + +registry.register(MathRenderer) + +#----------------------------------------------------------------------------- + +class SolutionRenderer(object): + ''' + A solution is just a ... 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) + diff --git a/common/lib/capa/capa/inputtypes.py b/common/lib/capa/capa/inputtypes.py index 57cb7ee90f..0b2250f98d 100644 --- a/common/lib/capa/capa/inputtypes.py +++ b/common/lib/capa/capa/inputtypes.py @@ -6,11 +6,9 @@ Module containing the problem elements which render into input objects - textline -- textbox (change this to textarea?) -- schemmatic -- choicegroup -- radiogroup -- checkboxgroup +- textbox (aka codeinput) +- schematic +- choicegroup (aka radiogroup, checkboxgroup) - javascriptinput - imageinput (for clickable image) - optioninput (for option list) @@ -23,63 +21,88 @@ Each input type takes the xml tree as 'element', the previous answer as 'value', graded status as'status' """ -# TODO: rename "state" to "status" for all below. status is currently the answer for the -# problem ID for the input element, but it will turn into a dict containing both the -# answer and any associated message for the problem ID for the input element. +# TODO: make hints do something +# TODO: make all inputtypes actually render msg + +# TODO: remove unused fields (e.g. 'hidden' in a few places) + +# TODO: add validators so that content folks get better error messages. + + +# Possible todo: make inline the default for textlines and other "one-line" inputs. It probably +# makes sense, but a bunch of problems have markup that assumes block. Bigger TODO: figure out a +# general css and layout strategy for capa, document it, then implement it. + +from collections import namedtuple +import json import logging +from lxml import etree import re import shlex # for splitting quoted strings -import json +import sys -from lxml import etree -import xml.sax.saxutils as saxutils +from registry import TagRegistry log = logging.getLogger('mitx.' + __name__) ######################################################################### -_TAGS_TO_CLASSES = {} +registry = TagRegistry() -def register_input_class(cls): +class Attribute(object): """ - Register cls as a supported input type. It is expected to have the same constructor as - InputTypeBase, and to define cls.tags as a list of tags that it implements. - - If an already-registered input type has claimed one of those tags, will raise ValueError. - - If there are no tags in cls.tags, will also raise ValueError. + Allows specifying required and optional attributes for input types. """ - # Do all checks and complain before changing any state. - if len(cls.tags) == 0: - raise ValueError("No supported tags for class {0}".format(cls.__name__)) + # want to allow default to be None, but also allow required objects + _sentinel = object() - for t in cls.tags: - if t in _TAGS_TO_CLASSES: - other_cls = _TAGS_TO_CLASSES[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__)) + def __init__(self, name, default=_sentinel, transform=None, validate=None, render=True): + """ + Define an attribute - # Ok, should be good to change state now. - for t in cls.tags: - _TAGS_TO_CLASSES[t] = cls + name (str): then name of the attribute--should be alphanumeric (valid for an XML attribute) -def registered_input_tags(): - """ - Get a list of all the xml tags that map to known input types. - """ - return _TAGS_TO_CLASSES.keys() + default (any type): If not specified, this attribute is required. If specified, use this as the default value + if the attribute is not specified. Note that this value will not be transformed or validated. + transform (function str -> any type): If not None, will be called to transform the parsed value into an internal + representation. -def get_class_for_tag(tag): - """ - For any tag in registered_input_tags(), return the corresponding class. Otherwise, will raise KeyError. - """ - return _TAGS_TO_CLASSES[tag] + validate (function str-or-return-type-of-tranform -> unit or exception): If not None, called to validate the + (possibly transformed) value of the attribute. Should raise ValueError with a helpful message if + the value is invalid. + + render (bool): if False, don't include this attribute in the template context. + """ + self.name = name + self.default = default + self.validate = validate + self.transform = transform + self.render = render + + def parse_from_xml(self, element): + """ + Given an etree xml element that should have this attribute, do the obvious thing: + - look for it. raise ValueError if not found and required. + - transform and validate. pass through any exceptions from transform or validate. + """ + val = element.get(self.name) + if self.default == self._sentinel and val is None: + raise ValueError('Missing required attribute {0}.'.format(self.name)) + + if val is None: + # not required, so return default + return self.default + + if self.transform is not None: + val = self.transform(val) + + if self.validate is not None: + self.validate(val) + + return val class InputTypeBase(object): @@ -93,16 +116,18 @@ class InputTypeBase(object): """ Instantiate an InputType class. Arguments: - - system : ModuleSystem instance which provides OS, rendering, and user context. Specifically, must - have a render_template function. + - system : ModuleSystem instance which provides OS, rendering, and user context. + Specifically, must have a render_template function. - xml : Element tree of this Input element - state : a dictionary with optional keys: - * 'value' - * 'id' + * 'value' -- the current value of this input + (what the student entered last time) + * 'id' -- the id of this input, typically + "{problem-location}_{response-num}_{input-num}" * 'status' (answered, unanswered, unsubmitted) * 'feedback' (dictionary containing keys for hints, errors, or other - feedback from previous attempt. Specifically 'message', 'hint', 'hintmode'. If 'hintmode' - is 'always', the hint is always displayed.) + feedback from previous attempt. Specifically 'message', 'hint', + 'hintmode'. If 'hintmode' is 'always', the hint is always displayed.) """ self.xml = xml @@ -132,54 +157,104 @@ class InputTypeBase(object): self.status = state.get('status', 'unanswered') + try: + # Pre-parse and propcess all the declared requirements. + self.process_requirements() + + # Call subclass "constructor" -- means they don't have to worry about calling + # super().__init__, and are isolated from changes to the input constructor interface. + self.setup() + except Exception as err: + # Something went wrong: add xml to message, but keep the traceback + msg = "Error in xml '{x}': {err} ".format(x=etree.tostring(xml), err=str(err)) + raise Exception, msg, sys.exc_info()[2] + + + @classmethod + def get_attributes(cls): + """ + Should return a list of Attribute objects (see docstring there for details). Subclasses should override. e.g. + + return [Attribute('unicorn', True), Attribute('num_dragons', 12, transform=int), ...] + """ + return [] + + + def process_requirements(self): + """ + Subclasses can declare lists of required and optional attributes. This + function parses the input xml and pulls out those attributes. This + isolates most simple input types from needing to deal with xml parsing at all. + + Processes attributes, putting the results in the self.loaded_attributes dictionary. Also creates a set + self.to_render, containing the names of attributes that should be included in the context by default. + """ + # Use local dicts and sets so that if there are exceptions, we don't end up in a partially-initialized state. + loaded = {} + to_render = set() + for a in self.get_attributes(): + loaded[a.name] = a.parse_from_xml(self.xml) + if a.render: + to_render.add(a.name) + + self.loaded_attributes = loaded + self.to_render = to_render + + def setup(self): + """ + InputTypes should override this to do any needed initialization. It is called after the + constructor, so all base attributes will be set. + + If this method raises an exception, it will be wrapped with a message that includes the + problem xml. + """ + pass + + def _get_render_context(self): """ - Abstract method. Subclasses should implement to return the dictionary - of keys needed to render their template. + Should return a dictionary of keys needed to render the template for the input type. (Separate from get_html to faciliate testing of logic separately from the rendering) + + The default implementation gets the following rendering context: basic things like value, id, status, and msg, + as well as everything in self.loaded_attributes, and everything returned by self._extra_context(). + + This means that input types that only parse attributes and pass them to the template get everything they need, + and don't need to override this method. """ - raise NotImplementedError + context = { + 'id': self.id, + 'value': self.value, + 'status': self.status, + 'msg': self.msg, + } + context.update((a, v) for (a, v) in self.loaded_attributes.iteritems() if a in self.to_render) + context.update(self._extra_context()) + return context + + def _extra_context(self): + """ + Subclasses can override this to return extra context that should be passed to their templates for rendering. + + This is useful when the input type requires computing new template variables from the parsed attributes. + """ + return {} def get_html(self): """ Return the html for this input, as an etree element. """ if self.template is None: - raise NotImplementedError("no rendering template specified for class {0}".format(self.__class__)) + raise NotImplementedError("no rendering template specified for class {0}" + .format(self.__class__)) - html = self.system.render_template(self.template, self._get_render_context()) + context = self._get_render_context() + + html = self.system.render_template(self.template, context) return etree.XML(html) -## TODO: Remove once refactor is complete -def make_class_for_render_function(fn): - """ - Take an old-style render function, return a new-style input class. - """ - - class Impl(InputTypeBase): - """ - Inherit all the constructor logic from InputTypeBase... - """ - tags = [fn.__name__] - def get_html(self): - """...delegate to the render function to do the work""" - return fn(self.xml, self.value, self.status, self.system.render_template, self.msg) - - # don't want all the classes to be called Impl (confuses register_input_class). - Impl.__name__ = fn.__name__.capitalize() - return Impl - - -def _reg(fn): - """ - Register an old-style inputtype render function as a new-style subclass of InputTypeBase. - This will go away once converting all input types to the new format is complete. (TODO) - """ - register_input_class(make_class_for_render_function(fn)) - - #----------------------------------------------------------------------------- @@ -190,487 +265,353 @@ class OptionInput(InputTypeBase): Example: The location of the sky + + # TODO: allow ordering to be randomized """ template = "optioninput.html" tags = ['optioninput'] - def _get_render_context(self): - return _optioninput(self.xml, self.value, self.status, self.system.render_template, self.msg) + @staticmethod + def parse_options(options): + """ + Given options string, convert it into an ordered list of (option_id, option_description) tuples, where + id==description for now. TODO: make it possible to specify different id and descriptions. + """ + # parse the set of possible options + lexer = shlex.shlex(options[1:-1]) + lexer.quotes = "'" + # Allow options to be separated by whitespace as well as commas + lexer.whitespace = ", " + + # remove quotes + tokens = [x[1:-1] for x in list(lexer)] + + # make list of (option_id, option_description), with description=id + return [(t, t) for t in tokens] + + @classmethod + def get_attributes(cls): + """ + Convert options to a convenient format. + """ + return [Attribute('options', transform=cls.parse_options), + Attribute('inline', '')] + +registry.register(OptionInput) + +#----------------------------------------------------------------------------- -def optioninput(element, value, status, render_template, msg=''): - context = _optioninput(element, value, status, render_template, msg) - html = render_template("optioninput.html", context) - return etree.XML(html) +# TODO: consolidate choicegroup, radiogroup, checkboxgroup after discussion of +# desired semantics. -def _optioninput(element, value, status, render_template, msg=''): +class ChoiceGroup(InputTypeBase): """ - Select option input type. + Radio button or checkbox inputs: multiple choice or true/false + + TODO: allow order of choices to be randomized, following lon-capa spec. Use + "location" attribute, ie random, top, bottom. Example: - The location of the sky + + + This is foil One. + + + This is foil Two. + + + This is foil Three. + + """ - eid = element.get('id') - options = element.get('options') - if not options: - raise Exception( - "[courseware.capa.inputtypes.optioninput] Missing options specification in " - + etree.tostring(element)) + template = "choicegroup.html" + tags = ['choicegroup', 'radiogroup', 'checkboxgroup'] - # parse the set of possible options - oset = shlex.shlex(options[1:-1]) - oset.quotes = "'" - oset.whitespace = "," - oset = [x[1:-1] for x in list(oset)] + def setup(self): + # suffix is '' or [] to change the way the input is handled in --as a scalar or vector + # value. (VS: would be nice to make this less hackish). + if self.tag == 'choicegroup': + self.suffix = '' + self.html_input_type = "radio" + elif self.tag == 'radiogroup': + self.html_input_type = "radio" + self.suffix = '[]' + elif self.tag == 'checkboxgroup': + self.html_input_type = "checkbox" + self.suffix = '[]' + else: + raise Exception("ChoiceGroup: unexpected tag {0}".format(self.tag)) - # make ordered list with (key, value) same - osetdict = [(oset[x], oset[x]) for x in range(len(oset))] - # TODO: allow ordering to be randomized + self.choices = self.extract_choices(self.xml) - context = {'id': eid, - 'value': value, - 'state': status, - 'msg': msg, - 'options': osetdict, - 'inline': element.get('inline',''), - } - return context + def _extra_context(self): + return {'input_type': self.html_input_type, + 'choices': self.choices, + 'name_array_suffix': self.suffix} + + @staticmethod + def extract_choices(element): + ''' + Extracts choices for a few input types, such as ChoiceGroup, RadioGroup and + CheckboxGroup. + + returns list of (choice_name, choice_text) tuples + + TODO: allow order of choices to be randomized, following lon-capa spec. Use + "location" attribute, ie random, top, bottom. + ''' + + choices = [] + + for choice in element: + if choice.tag != 'choice': + raise Exception( + "[capa.inputtypes.extract_choices] Expected a tag; got %s instead" + % choice.tag) + choice_text = ''.join([etree.tostring(x) for x in choice]) + if choice.text is not None: + # TODO: fix order? + choice_text += choice.text + + choices.append((choice.get("name"), choice_text)) + + return choices + + +registry.register(ChoiceGroup) -register_input_class(OptionInput) #----------------------------------------------------------------------------- -# TODO: consolidate choicegroup, radiogroup, checkboxgroup after discussion of -# desired semantics. -# @register_render_function -def choicegroup(element, value, status, render_template, msg=''): - ''' - Radio button inputs: multiple choice or true/false - - TODO: allow order of choices to be randomized, following lon-capa spec. Use - "location" attribute, ie random, top, bottom. - ''' - eid = element.get('id') - if element.get('type') == "MultipleChoice": - element_type = "radio" - elif element.get('type') == "TrueFalse": - element_type = "checkbox" - else: - element_type = "radio" - choices = [] - for choice in element: - if not choice.tag == 'choice': - raise Exception("[courseware.capa.inputtypes.choicegroup] " - "Error: only tags should be immediate children " - "of a , found %s instead" % choice.tag) - ctext = "" - # TODO: what if choice[0] has math tags in it? - ctext += ''.join([etree.tostring(x) for x in choice]) - if choice.text is not None: - # TODO: fix order? - ctext += choice.text - choices.append((choice.get("name"), ctext)) - context = {'id': eid, - 'value': value, - 'state': status, - 'input_type': element_type, - 'choices': choices, - 'name_array_suffix': ''} - html = render_template("choicegroup.html", context) - return etree.XML(html) - -_reg(choicegroup) - -#----------------------------------------------------------------------------- -def extract_choices(element): - ''' - Extracts choices for a few input types, such as radiogroup and - checkboxgroup. - - TODO: allow order of choices to be randomized, following lon-capa spec. Use - "location" attribute, ie random, top, bottom. - ''' - - choices = [] - - for choice in element: - if not choice.tag == 'choice': - raise Exception("[courseware.capa.inputtypes.extract_choices] \ - Expected a tag; got %s instead" - % choice.tag) - choice_text = ''.join([etree.tostring(x) for x in choice]) - - choices.append((choice.get("name"), choice_text)) - - return choices - - -# TODO: consolidate choicegroup, radiogroup, checkboxgroup after discussion of -# desired semantics. -def radiogroup(element, value, status, render_template, msg=''): - ''' - Radio button inputs: (multiple choice) - ''' - - eid = element.get('id') - - choices = extract_choices(element) - - context = {'id': eid, - 'value': value, - 'state': status, - 'input_type': 'radio', - 'choices': choices, - 'name_array_suffix': '[]'} - - html = render_template("choicegroup.html", context) - return etree.XML(html) - - -_reg(radiogroup) - -# TODO: consolidate choicegroup, radiogroup, checkboxgroup after discussion of -# desired semantics. -def checkboxgroup(element, value, status, render_template, msg=''): - ''' - Checkbox inputs: (select one or more choices) - ''' - - eid = element.get('id') - - choices = extract_choices(element) - - context = {'id': eid, - 'value': value, - 'state': status, - 'input_type': 'checkbox', - 'choices': choices, - 'name_array_suffix': '[]'} - - html = render_template("choicegroup.html", context) - return etree.XML(html) - -_reg(checkboxgroup) - -def javascriptinput(element, value, status, render_template, msg='null'): - ''' +class JavascriptInput(InputTypeBase): + """ Hidden field for javascript to communicate via; also loads the required scripts for rendering the problem and passes data to the problem. - ''' - eid = element.get('id') - params = element.get('params') - problem_state = element.get('problem_state') - display_class = element.get('display_class') - display_file = element.get('display_file') - # Need to provide a value that JSON can parse if there is no - # student-supplied value yet. - if value == "": - value = 'null' + TODO (arjun?): document this in detail. Initial notes: + - display_class is a subclass of XProblemClassDisplay (see + xmodule/xmodule/js/src/capa/display.coffee), + - display_file is the js script to be in /static/js/ where display_class is defined. + """ - escapedict = {'"': '"'} - value = saxutils.escape(value, escapedict) - msg = saxutils.escape(msg, escapedict) - context = {'id': eid, - 'params': params, - 'display_file': display_file, - 'display_class': display_class, - 'problem_state': problem_state, - 'value': value, - 'evaluation': msg, - } - html = render_template("javascriptinput.html", context) - return etree.XML(html) + template = "javascriptinput.html" + tags = ['javascriptinput'] -_reg(javascriptinput) + @classmethod + def get_attributes(cls): + """ + Register the attributes. + """ + return [Attribute('params', None), + Attribute('problem_state', None), + Attribute('display_class', None), + Attribute('display_file', None),] -def textline(element, value, status, render_template, msg=""): - ''' - Simple text line input, with optional size specification. - ''' - # TODO: 'dojs' flag is temporary, for backwards compatibility with 8.02x - if element.get('math') or element.get('dojs'): - return textline_dynamath(element, value, status, render_template, msg) - eid = element.get('id') - if eid is None: - msg = 'textline has no id: it probably appears outside of a known response type' - msg += "\nSee problem XML source line %s" % getattr(element, 'sourceline', '') - raise Exception(msg) + def setup(self): + # Need to provide a value that JSON can parse if there is no + # student-supplied value yet. + if self.value == "": + self.value = 'null' - count = int(eid.split('_')[-2]) - 1 # HACK - size = element.get('size') - # if specified, then textline is hidden and id is stored in div of name given by hidden - hidden = element.get('hidden', '') - - # Escape answers with quotes, so they don't crash the system! - escapedict = {'"': '"'} - value = saxutils.escape(value, escapedict) - - context = {'id': eid, - 'value': value, - 'state': status, - 'count': count, - 'size': size, - 'msg': msg, - 'hidden': hidden, - 'inline': element.get('inline',''), - } - - html = render_template("textinput.html", context) - try: - xhtml = etree.XML(html) - except Exception as err: - # TODO: needs to be self.system.DEBUG - but can't access system - if True: - log.debug('[inputtypes.textline] failed to parse XML for:\n%s' % html) - raise - return xhtml - -_reg(textline) - -#----------------------------------------------------------------------------- - - -def textline_dynamath(element, value, status, render_template, msg=''): - ''' - Text line input with dynamic math display (equation rendered on client in real time - during input). - ''' - # TODO: Make a wrapper for - # TODO: Make an AJAX loop to confirm equation is okay in real-time as user types - ''' - textline is used for simple one-line inputs, like formularesponse and symbolicresponse. - uses a `{::}` - and a hidden textarea with id=input_eid_fromjs for the mathjax rendering and return. - ''' - eid = element.get('id') - count = int(eid.split('_')[-2]) - 1 # HACK - size = element.get('size') - # if specified, then textline is hidden and id is stored in div of name given by hidden - hidden = element.get('hidden', '') - - # Preprocessor to insert between raw input and Mathjax - preprocessor = {'class_name': element.get('preprocessorClassName',''), - 'script_src': element.get('preprocessorSrc','')} - if '' in preprocessor.values(): - preprocessor = None - - # Escape characters in student input for safe XML parsing - escapedict = {'"': '"'} - value = saxutils.escape(value, escapedict) - - context = {'id': eid, - 'value': value, - 'state': status, - 'count': count, - 'size': size, - 'msg': msg, - 'hidden': hidden, - 'preprocessor': preprocessor,} - html = render_template("textinput_dynamath.html", context) - return etree.XML(html) +registry.register(JavascriptInput) #----------------------------------------------------------------------------- -def filesubmission(element, value, status, render_template, msg=''): - ''' - Upload a single file (e.g. for programming assignments) - ''' - eid = element.get('id') - escapedict = {'"': '"'} - allowed_files = json.dumps(element.get('allowed_files', '').split()) - allowed_files = saxutils.escape(allowed_files, escapedict) - required_files = json.dumps(element.get('required_files', '').split()) - required_files = saxutils.escape(required_files, escapedict) - # Check if problem has been queued - queue_len = 0 - # Flag indicating that the problem has been queued, 'msg' is length of queue - if status == 'incomplete': - status = 'queued' - queue_len = msg - msg = "Your file(s) have been submitted; as soon as your submission is graded, this message will be replaced with the grader's feedback." +class TextLine(InputTypeBase): + """ + A text line input. Can do math preview if "math"="1" is specified. - context = { 'id': eid, - 'state': status, - 'msg': msg, - 'value': value, - 'queue_len': queue_len, - 'allowed_files': allowed_files, - 'required_files': required_files,} - html = render_template("filesubmission.html", context) - return etree.XML(html) + If the hidden attribute is specified, the textline is hidden and the input id is stored in a div with name equal + to the value of the hidden attribute. This is used e.g. for embedding simulations turned into questions. + """ -_reg(filesubmission) + template = "textline.html" + tags = ['textline'] -#----------------------------------------------------------------------------- -## TODO: Make a wrapper for -def textbox(element, value, status, render_template, msg=''): - ''' - The textbox is used for code input. The message is the return HTML string from - evaluating the code, eg error messages, and output from the code tests. - - ''' - eid = element.get('id') - count = int(eid.split('_')[-2]) - 1 # HACK - size = element.get('size') - rows = element.get('rows') or '30' - cols = element.get('cols') or '80' - # if specified, then textline is hidden and id is stored in div of name given by hidden - hidden = element.get('hidden', '') - - # if no student input yet, then use the default input given by the problem - if not value: - value = element.text - - # Check if problem has been queued - queue_len = 0 - # Flag indicating that the problem has been queued, 'msg' is length of queue - if status == 'incomplete': - status = 'queued' - queue_len = msg - msg = 'Submitted to grader.' - - # For CodeMirror - mode = element.get('mode','python') - linenumbers = element.get('linenumbers','true') - tabsize = element.get('tabsize','4') - tabsize = int(tabsize) - - context = {'id': eid, - 'value': value, - 'state': status, - 'count': count, - 'size': size, - 'msg': msg, - 'mode': mode, - 'linenumbers': linenumbers, - 'rows': rows, - 'cols': cols, - 'hidden': hidden, - 'tabsize': tabsize, - 'queue_len': queue_len, - } - html = render_template("textbox.html", context) - try: - xhtml = etree.XML(html) - except Exception as err: - newmsg = 'error %s in rendering message' % (str(err).replace('<', '<')) - newmsg += '
Original message: %s' % msg.replace('<', '<') - context['msg'] = newmsg - html = render_template("textbox.html", context) - xhtml = etree.XML(html) - return xhtml + @classmethod + def get_attributes(cls): + """ + Register the attributes. + """ + return [ + Attribute('size', None), -_reg(textbox) + Attribute('hidden', False), + Attribute('inline', False), -#----------------------------------------------------------------------------- -def schematic(element, value, status, render_template, msg=''): - eid = element.get('id') - height = element.get('height') - width = element.get('width') - parts = element.get('parts') - analyses = element.get('analyses') - initial_value = element.get('initial_value') - submit_analyses = element.get('submit_analyses') - context = { - 'id': eid, - 'value': value, - 'initial_value': initial_value, - 'state': status, - 'width': width, - 'height': height, - 'parts': parts, - 'analyses': analyses, - 'submit_analyses': submit_analyses, - } - html = render_template("schematicinput.html", context) - return etree.XML(html) + # Attributes below used in setup(), not rendered directly. + Attribute('math', None, render=False), + # TODO: 'dojs' flag is temporary, for backwards compatibility with 8.02x + Attribute('dojs', None, render=False), + Attribute('preprocessorClassName', None, render=False), + Attribute('preprocessorSrc', None, render=False), + ] -_reg(schematic) -#----------------------------------------------------------------------------- -### TODO: Move out of inputtypes -def math(element, value, status, render_template, msg=''): - ''' - This is not really an input type. It is a convention from Lon-CAPA, used for - displaying a math equation. + def setup(self): + self.do_math = bool(self.loaded_attributes['math'] or + self.loaded_attributes['dojs']) - Examples: + # TODO: do math checking using ajax instead of using js, so + # that we only have one math parser. + self.preprocessor = None + if self.do_math: + # Preprocessor to insert between raw input and Mathjax + self.preprocessor = {'class_name': self.loaded_attributes['preprocessorClassName'], + 'script_src': self.loaded_attributes['preprocessorSrc']} + if None in self.preprocessor.values(): + self.preprocessor = None - $\displaystyle U(r)=4 U_0 - $r_0$ - We convert these to [mathjax]...[/mathjax] and [mathjaxinline]...[/mathjaxinline] + def _extra_context(self): + return {'do_math': self.do_math, + 'preprocessor': self.preprocessor,} - TODO: use shorter tags (but this will require converting problem XML files!) - ''' - mathstr = re.sub('\$(.*)\$', '[mathjaxinline]\\1[/mathjaxinline]', element.text) - mtag = 'mathjax' - if not '\\displaystyle' in mathstr: mtag += 'inline' - else: mathstr = mathstr.replace('\\displaystyle', '') - mathstr = mathstr.replace('mathjaxinline]', '%s]' % mtag) - - #if '\\displaystyle' in mathstr: - # isinline = False - # mathstr = mathstr.replace('\\displaystyle','') - #else: - # isinline = True - # html = render_template("mathstring.html", {'mathstr':mathstr, - # 'isinline':isinline,'tail':element.tail}) - - html = '%s%s' % (mathstr, saxutils.escape(element.tail)) - try: - xhtml = etree.XML(html) - except Exception as err: - if False: # TODO needs to be self.system.DEBUG - but can't access system - msg = '

Error %s

' % str(err).replace('<', '<') - msg += ('

Failed to construct math expression from

%s

' % - html.replace('<', '<')) - msg += "
" - log.error(msg) - return etree.XML(msg) - else: - raise - # xhtml.tail = element.tail # don't forget to include the tail! - return xhtml - -_reg(math) +registry.register(TextLine) #----------------------------------------------------------------------------- +class FileSubmission(InputTypeBase): + """ + Upload some files (e.g. for programming assignments) + """ -def solution(element, value, status, render_template, msg=''): - ''' - This is not really an input type. It is just a ... 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 sent with the HTML. It is obtained - by an ajax call. - ''' - eid = element.get('id') - size = element.get('size') - context = {'id': eid, - 'value': value, - 'state': status, - 'size': size, - 'msg': msg, - } - html = render_template("solutionspan.html", context) - return etree.XML(html) + template = "filesubmission.html" + tags = ['filesubmission'] + + # pulled out for testing + submitted_msg = ("Your file(s) have been submitted; as soon as your submission is" + " graded, this message will be replaced with the grader's feedback.") + + @staticmethod + def parse_files(files): + """ + Given a string like 'a.py b.py c.out', split on whitespace and return as a json list. + """ + return json.dumps(files.split()) + + @classmethod + def get_attributes(cls): + """ + Convert the list of allowed files to a convenient format. + """ + return [Attribute('allowed_files', '[]', transform=cls.parse_files), + Attribute('required_files', '[]', transform=cls.parse_files),] + + def setup(self): + """ + Do some magic to handle queueing status (render as "queued" instead of "incomplete"), + pull queue_len from the msg field. (TODO: get rid of the queue_len hack). + """ + # Check if problem has been queued + self.queue_len = 0 + # Flag indicating that the problem has been queued, 'msg' is length of queue + if self.status == 'incomplete': + self.status = 'queued' + self.queue_len = self.msg + self.msg = FileSubmission.submitted_msg + + def _extra_context(self): + return {'queue_len': self.queue_len,} + return context + +registry.register(FileSubmission) -_reg(solution) #----------------------------------------------------------------------------- +class CodeInput(InputTypeBase): + """ + A text area input for code--uses codemirror, does syntax highlighting, special tab handling, + etc. + """ -def imageinput(element, value, status, render_template, msg=''): - ''' + template = "codeinput.html" + tags = ['codeinput', + 'textbox', # Another (older) name--at some point we may want to make it use a + # non-codemirror editor. + ] + + # pulled out for testing + submitted_msg = ("Submitted. As soon as your submission is" + " graded, this message will be replaced with the grader's feedback.") + + @classmethod + def get_attributes(cls): + """ + Convert options to a convenient format. + """ + return [Attribute('rows', '30'), + Attribute('cols', '80'), + Attribute('hidden', ''), + + # For CodeMirror + Attribute('mode', 'python'), + Attribute('linenumbers', 'true'), + # Template expects tabsize to be an int it can do math with + Attribute('tabsize', 4, transform=int), + ] + + def setup(self): + """ + Implement special logic: handle queueing state, and default input. + """ + # if no student input yet, then use the default input given by the problem + if not self.value: + self.value = self.xml.text + + # Check if problem has been queued + self.queue_len = 0 + # Flag indicating that the problem has been queued, 'msg' is length of queue + if self.status == 'incomplete': + self.status = 'queued' + self.queue_len = self.msg + self.msg = self.submitted_msg + + def _extra_context(self): + """Defined queue_len, add it """ + return {'queue_len': self.queue_len,} + +registry.register(CodeInput) + + +#----------------------------------------------------------------------------- +class Schematic(InputTypeBase): + """ + """ + + template = "schematicinput.html" + tags = ['schematic'] + + @classmethod + def get_attributes(cls): + """ + Convert options to a convenient format. + """ + return [ + Attribute('height', None), + Attribute('width', None), + Attribute('parts', None), + Attribute('analyses', None), + Attribute('initial_value', None), + Attribute('submit_analyses', None),] + + return context + +registry.register(Schematic) + +#----------------------------------------------------------------------------- + +class ImageInput(InputTypeBase): + """ Clickable image as an input field. Element should specify the image source, height, and width, e.g. @@ -678,130 +619,91 @@ def imageinput(element, value, status, render_template, msg=''): TODO: showanswer for imageimput does not work yet - need javascript to put rectangle over acceptable area of image. - ''' - eid = element.get('id') - src = element.get('src') - height = element.get('height') - width = element.get('width') + """ - # if value is of the form [x,y] then parse it and send along coordinates of previous answer - m = re.match('\[([0-9]+),([0-9]+)]', value.strip().replace(' ', '')) - if m: - (gx, gy) = [int(x) - 15 for x in m.groups()] - else: - (gx, gy) = (0, 0) + template = "imageinput.html" + tags = ['imageinput'] - context = { - 'id': eid, - 'value': value, - 'height': height, - 'width': width, - 'src': src, - 'gx': gx, - 'gy': gy, - 'state': status, # to change - 'msg': msg, # to change - } - html = render_template("imageinput.html", context) - return etree.XML(html) - -_reg(imageinput) + @classmethod + def get_attributes(cls): + """ + Note: src, height, and width are all required. + """ + return [Attribute('src'), + Attribute('height'), + Attribute('width'),] -def crystallography(element, value, status, render_template, msg=''): - eid = element.get('id') - if eid is None: - msg = 'cryst has no id: it probably appears outside of a known response type' - msg += "\nSee problem XML source line %s" % getattr(element, 'sourceline', '') - raise Exception(msg) - height = element.get('height') - width = element.get('width') - display_file = element.get('display_file') - - count = int(eid.split('_')[-2]) - 1 # HACK - size = element.get('size') - # if specified, then textline is hidden and id is stored in div of name given by hidden - hidden = element.get('hidden', '') - # Escape answers with quotes, so they don't crash the system! - escapedict = {'"': '"'} - value = saxutils.escape(value, escapedict) - - context = {'id': eid, - 'value': value, - 'state': status, - 'count': count, - 'size': size, - 'msg': msg, - 'hidden': hidden, - 'inline': element.get('inline', ''), - 'width': width, - 'height': height, - 'display_file': display_file, - } - - html = render_template("crystallography.html", context) - - try: - xhtml = etree.XML(html) - except Exception as err: - # TODO: needs to be self.system.DEBUG - but can't access system - if True: - log.debug('[inputtypes.crystallography] failed to parse XML for:\n%s' % html) - raise - return xhtml - -_reg(crystallography) + def setup(self): + """ + if value is of the form [x,y] then parse it and send along coordinates of previous answer + """ + m = re.match('\[([0-9]+),([0-9]+)]', self.value.strip().replace(' ', '')) + if m: + # Note: we subtract 15 to compensate for the size of the dot on the screen. + # (is a 30x30 image--lms/static/green-pointer.png). + (self.gx, self.gy) = [int(x) - 15 for x in m.groups()] + else: + (self.gx, self.gy) = (0, 0) -def vsepr_input(element, value, status, render_template, msg=''): - eid = element.get('id') - if eid is None: - msg = 'cryst has no id: it probably appears outside of a known response type' - msg += "\nSee problem XML source line %s" % getattr(element, 'sourceline', '') - raise Exception(msg) - height = element.get('height') - width = element.get('width') - display_file = element.get('display_file') + def _extra_context(self): - count = int(eid.split('_')[-2]) - 1 # HACK - size = element.get('size') - # if specified, then textline is hidden and id is stored in div of name given by hidden - hidden = element.get('hidden', '') - # Escape answers with quotes, so they don't crash the system! - escapedict = {'"': '"'} - value = saxutils.escape(value, escapedict) + return {'gx': self.gx, + 'gy': self.gy} - molecules = element.get('molecules') - geometries = element.get('geometries') +registry.register(ImageInput) - context = {'id': eid, - 'value': value, - 'state': status, - 'count': count, - 'size': size, - 'msg': msg, - 'hidden': hidden, - 'inline': element.get('inline', ''), - 'width': width, - 'height': height, - 'display_file': display_file, - 'molecules': molecules, - 'geometries': geometries, - } +#----------------------------------------------------------------------------- - html = render_template("vsepr_input.html", context) +class Crystallography(InputTypeBase): + """ + An input for crystallography -- user selects 3 points on the axes, and we get a plane. - try: - xhtml = etree.XML(html) - except Exception as err: - # TODO: needs to be self.system.DEBUG - but can't access system - if True: - log.debug('[inputtypes.vsepr_input] failed to parse XML for:\n%s' % html) - raise - return xhtml + TODO: what's the actual value format? + """ -_reg(vsepr_input) + template = "crystallography.html" + tags = ['crystallography'] + @classmethod + def get_attributes(cls): + """ + Note: height, width are required. + """ + return [Attribute('size', None), + Attribute('height'), + Attribute('width'), + + # can probably be removed (textline should prob be always-hidden) + Attribute('hidden', ''), + ] + +registry.register(Crystallography) + +# ------------------------------------------------------------------------- + +class VseprInput(InputTypeBase): + """ + Input for molecular geometry--show possible structures, let student + pick structure and label positions with atoms or electron pairs. + """ + + template = 'vsepr_input.html' + tags = ['vsepr_input'] + + @classmethod + def get_attributes(cls): + """ + Note: height, width are required. + """ + return [Attribute('height'), + Attribute('width'), + Attribute('molecules'), + Attribute('geometries'), + ] + +registry.register(VseprInput) #-------------------------------------------------------------------------------- @@ -820,15 +722,17 @@ class ChemicalEquationInput(InputTypeBase): template = "chemicalequationinput.html" tags = ['chemicalequationinput'] - def _get_render_context(self): - size = self.xml.get('size', '20') - context = { - 'id': self.id, - 'value': self.value, - 'status': self.status, - 'size': size, - 'previewer': '/static/js/capa/chemical_equation_preview.js', - } - return context + @classmethod + def get_attributes(cls): + """ + Can set size of text field. + """ + return [Attribute('size', '20'),] -register_input_class(ChemicalEquationInput) + def _extra_context(self): + """ + TODO (vshnayder): Get rid of this once we have a standard way of requiring js to be loaded. + """ + return {'previewer': '/static/js/capa/chemical_equation_preview.js',} + +registry.register(ChemicalEquationInput) diff --git a/common/lib/capa/capa/registry.py b/common/lib/capa/capa/registry.py new file mode 100644 index 0000000000..94a2853dec --- /dev/null +++ b/common/lib/capa/capa/registry.py @@ -0,0 +1,49 @@ +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] diff --git a/common/lib/capa/capa/responsetypes.py b/common/lib/capa/capa/responsetypes.py index 648fc9e861..b990c489b3 100644 --- a/common/lib/capa/capa/responsetypes.py +++ b/common/lib/capa/capa/responsetypes.py @@ -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 diff --git a/common/lib/capa/capa/templates/choicegroup.html b/common/lib/capa/capa/templates/choicegroup.html index ce1b6d9476..457d9e7817 100644 --- a/common/lib/capa/capa/templates/choicegroup.html +++ b/common/lib/capa/capa/templates/choicegroup.html @@ -1,12 +1,12 @@
- % if state == 'unsubmitted': + % if status == 'unsubmitted': - % elif state == 'correct': + % elif status == 'correct': - % elif state == 'incorrect': + % elif status == 'incorrect': - % elif state == 'incomplete': + % elif status == 'incomplete': % endif
diff --git a/common/lib/capa/capa/templates/textbox.html b/common/lib/capa/capa/templates/codeinput.html similarity index 90% rename from common/lib/capa/capa/templates/textbox.html rename to common/lib/capa/capa/templates/codeinput.html index 6e44712d9f..5c2ff2aca5 100644 --- a/common/lib/capa/capa/templates/textbox.html +++ b/common/lib/capa/capa/templates/codeinput.html @@ -6,13 +6,13 @@ >${value|h}
- % if state == 'unsubmitted': + % if status == 'unsubmitted': Unanswered - % elif state == 'correct': + % elif status == 'correct': Correct - % elif state == 'incorrect': + % elif status == 'incorrect': Incorrect - % elif state == 'queued': + % elif status == 'queued': Queued % endif @@ -21,7 +21,7 @@
% endif -

${state}

+

${status}

diff --git a/common/lib/capa/capa/templates/crystallography.html b/common/lib/capa/capa/templates/crystallography.html index 1fc638b356..2370f59dd2 100644 --- a/common/lib/capa/capa/templates/crystallography.html +++ b/common/lib/capa/capa/templates/crystallography.html @@ -1,25 +1,25 @@ -<% doinline = "inline" if inline else "" %> - -
+
-
+
+
+
- % if state == 'unsubmitted': -
- % elif state == 'correct': -
- % elif state == 'incorrect': -
- % elif state == 'incomplete': -
+ % if status == 'unsubmitted': +
+ % elif status == 'correct': +
+ % elif status == 'incorrect': +
+ % elif status == 'incomplete': +
% endif % if hidden:
% endif -

- % 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

@@ -45,7 +45,7 @@ % if msg: ${msg|n} % endif -% if state in ['unsubmitted', 'correct', 'incorrect', 'incomplete'] or hidden: +% if status in ['unsubmitted', 'correct', 'incorrect', 'incomplete']:
% endif
diff --git a/common/lib/capa/capa/templates/filesubmission.html b/common/lib/capa/capa/templates/filesubmission.html index 630a3222dc..930469dc0d 100644 --- a/common/lib/capa/capa/templates/filesubmission.html +++ b/common/lib/capa/capa/templates/filesubmission.html @@ -1,18 +1,18 @@
- % if state == 'unsubmitted': + % if status == 'unsubmitted': Unanswered - % elif state == 'correct': + % elif status == 'correct': Correct - % elif state == 'incorrect': + % elif status == 'incorrect': Incorrect - % elif state == 'queued': + % elif status == 'queued': Queued % endif -

${state}

+

${status}

- +
${msg|n}
diff --git a/common/lib/capa/capa/templates/imageinput.html b/common/lib/capa/capa/templates/imageinput.html index ceda98ee8f..97279c1b8c 100644 --- a/common/lib/capa/capa/templates/imageinput.html +++ b/common/lib/capa/capa/templates/imageinput.html @@ -4,13 +4,13 @@
- % if state == 'unsubmitted': + % if status == 'unsubmitted': - % elif state == 'correct': + % elif status == 'correct': - % elif state == 'incorrect': + % elif status == 'incorrect': - % elif state == 'incomplete': + % elif status == 'incomplete': % endif diff --git a/common/lib/capa/capa/templates/javascriptinput.html b/common/lib/capa/capa/templates/javascriptinput.html index 8b4c8f7115..b4d007e4d8 100644 --- a/common/lib/capa/capa/templates/javascriptinput.html +++ b/common/lib/capa/capa/templates/javascriptinput.html @@ -2,7 +2,7 @@
+ data-submission="${value|h}" data-evaluation="${msg|h}">
diff --git a/common/lib/capa/capa/templates/jstextline.html b/common/lib/capa/capa/templates/jstextline.html index 045f329ad4..7e5fd94a4b 100644 --- a/common/lib/capa/capa/templates/jstextline.html +++ b/common/lib/capa/capa/templates/jstextline.html @@ -18,13 +18,13 @@ % endif - % if state == 'unsubmitted': + % if status == 'unsubmitted': - % elif state == 'correct': + % elif status == 'correct': - % elif state == 'incorrect': + % elif status == 'incorrect': - % elif state == 'incomplete': + % elif status == 'incomplete': % endif % if msg: diff --git a/common/lib/capa/capa/templates/optioninput.html b/common/lib/capa/capa/templates/optioninput.html index 06c7ed1257..ac62c0c9cb 100644 --- a/common/lib/capa/capa/templates/optioninput.html +++ b/common/lib/capa/capa/templates/optioninput.html @@ -12,13 +12,13 @@ - % if state == 'unsubmitted': + % if status == 'unsubmitted': - % elif state == 'correct': + % elif status == 'correct': - % elif state == 'incorrect': + % elif status == 'incorrect': - % elif state == 'incomplete': + % elif status == 'incomplete': % endif
diff --git a/common/lib/capa/capa/templates/schematicinput.html b/common/lib/capa/capa/templates/schematicinput.html index f79dc66d24..ff8cc64073 100644 --- a/common/lib/capa/capa/templates/schematicinput.html +++ b/common/lib/capa/capa/templates/schematicinput.html @@ -12,13 +12,13 @@ - % if state == 'unsubmitted': + % if status == 'unsubmitted': - % elif state == 'correct': + % elif status == 'correct': - % elif state == 'incorrect': + % elif status == 'incorrect': - % elif state == 'incomplete': + % elif status == 'incomplete': % endif diff --git a/common/lib/capa/capa/templates/textinput.html b/common/lib/capa/capa/templates/textinput.html deleted file mode 100644 index 9b66654117..0000000000 --- a/common/lib/capa/capa/templates/textinput.html +++ /dev/null @@ -1,46 +0,0 @@ -<% doinline = "inline" if inline else "" %> - -
- % if state == 'unsubmitted': -
- % elif state == 'correct': -
- % elif state == 'incorrect': -
- % elif state == 'incomplete': -
- % endif - % if hidden: -
- % endif - - - -

- % if state == 'unsubmitted': - unanswered - % elif state == 'correct': - correct - % elif state == 'incorrect': - incorrect - % elif state == 'incomplete': - incomplete - % endif -

- -

- - % if msg: - ${msg|n} - % endif -% if state in ['unsubmitted', 'correct', 'incorrect', 'incomplete'] or hidden: -
-% endif -
diff --git a/common/lib/capa/capa/templates/textinput_dynamath.html b/common/lib/capa/capa/templates/textinput_dynamath.html deleted file mode 100644 index d1de22ef27..0000000000 --- a/common/lib/capa/capa/templates/textinput_dynamath.html +++ /dev/null @@ -1,50 +0,0 @@ -### -### version of textline.html which does dynamic math -### -
- - % if preprocessor is not None: -
-
- % endif - - % if state == 'unsubmitted': -
- % elif state == 'correct': -
- % elif state == 'incorrect': -
- % elif state == 'incomplete': -
- % endif - % if hidden: -
- % endif - - -

- % if state == 'unsubmitted': - unanswered - % elif state == 'correct': - correct - % elif state == 'incorrect': - incorrect - % elif state == 'incomplete': - incomplete - % endif -

- -

- -
`{::}`
- -
- - % if msg: - ${msg|n} - % endif -
diff --git a/common/lib/capa/capa/templates/textline.html b/common/lib/capa/capa/templates/textline.html new file mode 100644 index 0000000000..fbb5467b67 --- /dev/null +++ b/common/lib/capa/capa/templates/textline.html @@ -0,0 +1,64 @@ +<% doinline = "inline" if inline else "" %> + +
+ + % if preprocessor is not None: +
+
+ % endif + + % if status == 'unsubmitted': +
+ % elif status == 'correct': +
+ % elif status == 'incorrect': +
+ % elif status == 'incomplete': +
+ % endif + % if hidden: +
+ % endif + + + +

+ % if status == 'unsubmitted': + unanswered + % elif status == 'correct': + correct + % elif status == 'incorrect': + incorrect + % elif status == 'incomplete': + incomplete + % endif +

+ +

+ + % if do_math: +
`{::}`
+ + + % endif + +% if status in ['unsubmitted', 'correct', 'incorrect', 'incomplete']: +
+% endif + + % if msg: + ${msg|n} + % endif + +
diff --git a/common/lib/capa/capa/templates/vsepr_input.html b/common/lib/capa/capa/templates/vsepr_input.html index 588e53c914..1bac2fd6e2 100644 --- a/common/lib/capa/capa/templates/vsepr_input.html +++ b/common/lib/capa/capa/templates/vsepr_input.html @@ -1,6 +1,4 @@ -<% doinline = "inline" if inline else "" %> - -
+
@@ -13,36 +11,28 @@
- % if state == 'unsubmitted': -
- % elif state == 'correct': -
- % elif state == 'incorrect': -
- % elif state == 'incomplete': -
- % endif - % if hidden: -
+ % if status == 'unsubmitted': +
+ % elif status == 'correct': +
+ % elif status == 'incorrect': +
+ % elif status == 'incomplete': +
% endif -

- % 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

@@ -52,7 +42,7 @@ % if msg: ${msg|n} % endif -% if state in ['unsubmitted', 'correct', 'incorrect', 'incomplete'] or hidden: +% if status in ['unsubmitted', 'correct', 'incorrect', 'incomplete']:
% endif diff --git a/common/lib/capa/capa/tests/__init__.py b/common/lib/capa/capa/tests/__init__.py index c72d2a1538..b06975f6ce 100644 --- a/common/lib/capa/capa/tests/__init__.py +++ b/common/lib/capa/capa/tests/__init__.py @@ -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
+ """ + return '
{0}
'.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")), diff --git a/common/lib/capa/capa/tests/test_customrender.py b/common/lib/capa/capa/tests/test_customrender.py new file mode 100644 index 0000000000..7208ab2941 --- /dev/null +++ b/common/lib/capa/capa/tests/test_customrender.py @@ -0,0 +1,76 @@ +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 = """{s}""".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 = """{tex}""".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. + diff --git a/common/lib/capa/capa/tests/test_inputtypes.py b/common/lib/capa/capa/tests/test_inputtypes.py index 9ef642d468..826d304717 100644 --- a/common/lib/capa/capa/tests/test_inputtypes.py +++ b/common/lib/capa/capa/tests/test_inputtypes.py @@ -1,50 +1,39 @@ """ -Tests of input types (and actually responsetypes too) +Tests of input types. + +TODO: +- refactor: so much repetive code (have factory methods that build xml elements directly, etc) + +- test error cases + +- check rendering -- e.g. msg should appear in the rendered output. If possible, test that + templates are escaping things properly. + + +- test unicode in values, parameters, etc. +- test various html escapes +- test funny xml chars -- should never get xml parse error if things are escaped properly. + """ -from datetime import datetime -import json -from mock import Mock -from nose.plugins.skip import SkipTest -import os +from lxml import etree import unittest +import xml.sax.saxutils as saxutils from . import test_system from capa import inputtypes -from lxml import etree - -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. - """ - return repr(context) +# just a handy shortcut +lookup_tag = inputtypes.registry.get_class_for_tag -system = Mock(render_template=tst_render_template) +def quote_attr(s): + return saxutils.quoteattr(s)[1:-1] # don't want the outer quotes class OptionInputTest(unittest.TestCase): ''' Make sure option inputs work ''' - def test_rendering_new(self): - xml = """""" - element = etree.fromstring(xml) - - value = 'Down' - status = 'answered' - context = inputtypes._optioninput(element, value, status, test_system.render_template) - print 'context: ', context - - expected = {'value': 'Down', - 'options': [('Up', 'Up'), ('Down', 'Down')], - 'state': 'answered', - 'msg': '', - 'inline': '', - 'id': 'sky_input'} - - self.assertEqual(context, expected) - def test_rendering(self): xml_str = """""" @@ -53,16 +42,466 @@ class OptionInputTest(unittest.TestCase): state = {'value': 'Down', 'id': 'sky_input', 'status': 'answered'} - option_input = inputtypes.OptionInput(system, element, state) + option_input = lookup_tag('optioninput')(test_system, element, state) context = option_input._get_render_context() expected = {'value': 'Down', 'options': [('Up', 'Up'), ('Down', 'Down')], - 'state': 'answered', + 'status': 'answered', 'msg': '', 'inline': '', 'id': 'sky_input'} self.assertEqual(context, expected) + def test_option_parsing(self): + f = inputtypes.OptionInput.parse_options + def check(input, options): + """Take list of options, confirm that output is in the silly doubled format""" + expected = [(o, o) for o in options] + self.assertEqual(f(input), expected) + + check("('a','b')", ['a', 'b']) + check("('a', 'b')", ['a', 'b']) + check("('a b','b')", ['a b', 'b']) + check("('My \"quoted\"place','b')", ['My \"quoted\"place', 'b']) + + +class ChoiceGroupTest(unittest.TestCase): + ''' + Test choice groups, radio groups, and checkbox groups + ''' + + def check_group(self, tag, expected_input_type, expected_suffix): + xml_str = """ + <{tag}> + This is foil One. + This is foil Two. + This is foil Three. + + """.format(tag=tag) + + element = etree.fromstring(xml_str) + + state = {'value': 'foil3', + 'id': 'sky_input', + 'status': 'answered'} + + the_input = lookup_tag(tag)(test_system, element, state) + + context = the_input._get_render_context() + + expected = {'id': 'sky_input', + 'value': 'foil3', + 'status': 'answered', + 'msg': '', + 'input_type': expected_input_type, + 'choices': [('foil1', 'This is foil One.'), + ('foil2', 'This is foil Two.'), + ('foil3', 'This is foil Three.'),], + 'name_array_suffix': expected_suffix, # what is this for?? + } + + self.assertEqual(context, expected) + + def test_choicegroup(self): + self.check_group('choicegroup', 'radio', '') + + def test_radiogroup(self): + self.check_group('radiogroup', 'radio', '[]') + + def test_checkboxgroup(self): + self.check_group('checkboxgroup', 'checkbox', '[]') + + + +class JavascriptInputTest(unittest.TestCase): + ''' + The javascript input is a pretty straightforward pass-thru, but test it anyway + ''' + + def test_rendering(self): + params = "(1,2,3)" + + problem_state = "abc12',12&hi" + display_class = "a_class" + display_file = "my_files/hi.js" + + xml_str = """""".format( + params=params, + ps=quote_attr(problem_state), + dc=display_class, df=display_file) + + element = etree.fromstring(xml_str) + + state = {'value': '3',} + the_input = lookup_tag('javascriptinput')(test_system, element, state) + + context = the_input._get_render_context() + + expected = {'id': 'prob_1_2', + 'status': 'unanswered', + 'msg': '', + 'value': '3', + 'params': params, + 'display_file': display_file, + 'display_class': display_class, + 'problem_state': problem_state,} + + self.assertEqual(context, expected) + + +class TextLineTest(unittest.TestCase): + ''' + Check that textline inputs work, with and without math. + ''' + + def test_rendering(self): + size = "42" + xml_str = """""".format(size=size) + + element = etree.fromstring(xml_str) + + state = {'value': 'BumbleBee',} + the_input = lookup_tag('textline')(test_system, element, state) + + context = the_input._get_render_context() + + expected = {'id': 'prob_1_2', + 'value': 'BumbleBee', + 'status': 'unanswered', + 'size': size, + 'msg': '', + 'hidden': False, + 'inline': False, + 'do_math': False, + 'preprocessor': None} + self.assertEqual(context, expected) + + + def test_math_rendering(self): + size = "42" + preprocessorClass = "preParty" + script = "foo/party.js" + + xml_str = """""".format(size=size, pp=preprocessorClass, sc=script) + + element = etree.fromstring(xml_str) + + state = {'value': 'BumbleBee',} + the_input = lookup_tag('textline')(test_system, element, state) + + context = the_input._get_render_context() + + expected = {'id': 'prob_1_2', + 'value': 'BumbleBee', + 'status': 'unanswered', + 'size': size, + 'msg': '', + 'hidden': False, + 'inline': False, + 'do_math': True, + 'preprocessor': {'class_name': preprocessorClass, + 'script_src': script}} + self.assertEqual(context, expected) + + +class FileSubmissionTest(unittest.TestCase): + ''' + Check that file submission inputs work + ''' + + def test_rendering(self): + allowed_files = "runme.py nooooo.rb ohai.java" + required_files = "cookies.py" + + xml_str = """""".format(af=allowed_files, + rf=required_files,) + + + element = etree.fromstring(xml_str) + + state = {'value': 'BumbleBee.py', + 'status': 'incomplete', + 'feedback' : {'message': '3'}, } + input_class = lookup_tag('filesubmission') + the_input = input_class(test_system, element, state) + + context = the_input._get_render_context() + + expected = {'id': 'prob_1_2', + 'status': 'queued', + 'msg': input_class.submitted_msg, + 'value': 'BumbleBee.py', + 'queue_len': '3', + 'allowed_files': '["runme.py", "nooooo.rb", "ohai.java"]', + 'required_files': '["cookies.py"]'} + + self.assertEqual(context, expected) + + +class CodeInputTest(unittest.TestCase): + ''' + Check that codeinput inputs work + ''' + + def test_rendering(self): + mode = "parrot" + linenumbers = 'false' + rows = '37' + cols = '11' + tabsize = '7' + + xml_str = """""".format(m=mode, c=cols, r=rows, ln=linenumbers, ts=tabsize) + + element = etree.fromstring(xml_str) + + escapedict = {'"': '"'} + esc = lambda s: saxutils.escape(s, escapedict) + + state = {'value': 'print "good evening"', + 'status': 'incomplete', + 'feedback' : {'message': '3'}, } + + input_class = lookup_tag('codeinput') + the_input = input_class(test_system, element, state) + + context = the_input._get_render_context() + + expected = {'id': 'prob_1_2', + 'value': 'print "good evening"', + 'status': 'queued', + 'msg': input_class.submitted_msg, + 'mode': mode, + 'linenumbers': linenumbers, + 'rows': rows, + 'cols': cols, + 'hidden': '', + 'tabsize': int(tabsize), + 'queue_len': '3', + } + + self.assertEqual(context, expected) + + +class SchematicTest(unittest.TestCase): + ''' + Check that schematic inputs work + ''' + + def test_rendering(self): + height = '12' + width = '33' + parts = 'resistors, capacitors, and flowers' + analyses = 'fast, slow, and pink' + initial_value = 'two large batteries' + submit_analyses = 'maybe' + + + xml_str = """""".format(h=height, w=width, p=parts, a=analyses, + iv=initial_value, sa=submit_analyses) + + element = etree.fromstring(xml_str) + + value = 'three resistors and an oscilating pendulum' + state = {'value': value, + 'status': 'unsubmitted'} + + the_input = lookup_tag('schematic')(test_system, element, state) + + context = the_input._get_render_context() + + expected = {'id': 'prob_1_2', + 'value': value, + 'status': 'unsubmitted', + 'msg': '', + 'initial_value': initial_value, + 'width': width, + 'height': height, + 'parts': parts, + 'analyses': analyses, + 'submit_analyses': submit_analyses, + } + + self.assertEqual(context, expected) + + +class ImageInputTest(unittest.TestCase): + ''' + Check that image inputs work + ''' + + def check(self, value, egx, egy): + height = '78' + width = '427' + src = 'http://www.edx.org/cowclicker.jpg' + + xml_str = """""".format(s=src, h=height, w=width) + + element = etree.fromstring(xml_str) + + state = {'value': value, + 'status': 'unsubmitted'} + + the_input = lookup_tag('imageinput')(test_system, element, state) + + context = the_input._get_render_context() + + expected = {'id': 'prob_1_2', + 'value': value, + 'status': 'unsubmitted', + 'width': width, + 'height': height, + 'src': src, + 'gx': egx, + 'gy': egy, + 'msg': ''} + + self.assertEqual(context, expected) + + def test_with_value(self): + # Check that compensating for the dot size works properly. + self.check('[50,40]', 35, 25) + + def test_without_value(self): + self.check('', 0, 0) + + def test_corrupt_values(self): + self.check('[12', 0, 0) + self.check('[12, a]', 0, 0) + self.check('[12 10]', 0, 0) + self.check('[12]', 0, 0) + self.check('[12 13 14]', 0, 0) + + + +class CrystallographyTest(unittest.TestCase): + ''' + Check that crystallography inputs work + ''' + + def test_rendering(self): + height = '12' + width = '33' + size = '10' + + xml_str = """""".format(h=height, w=width, s=size) + + element = etree.fromstring(xml_str) + + value = 'abc' + state = {'value': value, + 'status': 'unsubmitted'} + + the_input = lookup_tag('crystallography')(test_system, element, state) + + context = the_input._get_render_context() + + expected = {'id': 'prob_1_2', + 'value': value, + 'status': 'unsubmitted', + 'size': size, + 'msg': '', + 'hidden': '', + 'width': width, + 'height': height, + } + + self.assertEqual(context, expected) + + +class VseprTest(unittest.TestCase): + ''' + Check that vsepr inputs work + ''' + + def test_rendering(self): + height = '12' + width = '33' + molecules = "H2O, C2O" + geometries = "AX12,TK421" + + xml_str = """""".format(h=height, w=width, m=molecules, g=geometries) + + element = etree.fromstring(xml_str) + + value = 'abc' + state = {'value': value, + 'status': 'unsubmitted'} + + the_input = lookup_tag('vsepr_input')(test_system, element, state) + + context = the_input._get_render_context() + + expected = {'id': 'prob_1_2', + 'value': value, + 'status': 'unsubmitted', + 'msg': '', + 'width': width, + 'height': height, + 'molecules': molecules, + 'geometries': geometries, + } + + self.assertEqual(context, expected) + + + +class ChemicalEquationTest(unittest.TestCase): + ''' + Check that chemical equation inputs work. + ''' + + def test_rendering(self): + size = "42" + xml_str = """""".format(size=size) + + element = etree.fromstring(xml_str) + + state = {'value': 'H2OYeah',} + the_input = lookup_tag('chemicalequationinput')(test_system, element, state) + + context = the_input._get_render_context() + + expected = {'id': 'prob_1_2', + 'value': 'H2OYeah', + 'status': 'unanswered', + 'msg': '', + 'size': size, + 'previewer': '/static/js/capa/chemical_equation_preview.js', + } + self.assertEqual(context, expected) + diff --git a/common/lib/xmodule/.coveragerc b/common/lib/xmodule/.coveragerc new file mode 100644 index 0000000000..310c8e778b --- /dev/null +++ b/common/lib/xmodule/.coveragerc @@ -0,0 +1,13 @@ +# .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 diff --git a/common/lib/xmodule/setup.py b/common/lib/xmodule/setup.py index 0441357427..d3889bc388 100644 --- a/common/lib/xmodule/setup.py +++ b/common/lib/xmodule/setup.py @@ -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", diff --git a/common/lib/xmodule/xmodule/capa_module.py b/common/lib/xmodule/xmodule/capa_module.py index 151c726f66..47d5d5c423 100644 --- a/common/lib/xmodule/xmodule/capa_module.py +++ b/common/lib/xmodule/xmodule/capa_module.py @@ -30,15 +30,17 @@ TIMEDELTA_REGEX = re.compile(r'^((?P\d+?) day(?:s?))?(\s)?((?P\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) diff --git a/common/lib/xmodule/xmodule/course_module.py b/common/lib/xmodule/xmodule/course_module.py index 0a5108590f..2b6232d366 100644 --- a/common/lib/xmodule/xmodule/course_module.py +++ b/common/lib/xmodule/xmodule/course_module.py @@ -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 @@ -275,6 +280,21 @@ class CourseDescriptor(SequenceDescriptor): more sensible framework later.""" 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 @@ -282,6 +302,16 @@ class CourseDescriptor(SequenceDescriptor): # Explicit comparison to True because we always want to return a bool. 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 diff --git a/common/lib/xmodule/xmodule/css/video/display.scss b/common/lib/xmodule/xmodule/css/video/display.scss index e8aba4d671..43b024ec32 100644 --- a/common/lib/xmodule/xmodule/css/video/display.scss +++ b/common/lib/xmodule/xmodule/css/video/display.scss @@ -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; diff --git a/common/lib/xmodule/xmodule/js/src/capa/schematic.js b/common/lib/xmodule/xmodule/js/src/capa/schematic.js index b01f6e12e8..b033dbaf46 100644 --- a/common/lib/xmodule/xmodule/js/src/capa/schematic.js +++ b/common/lib/xmodule/xmodule/js/src/capa/schematic.js @@ -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) { diff --git a/common/lib/xmodule/xmodule/js/src/selfassessment/display.coffee b/common/lib/xmodule/xmodule/js/src/selfassessment/display.coffee new file mode 100644 index 0000000000..951eb42fce --- /dev/null +++ b/common/lib/xmodule/xmodule/js/src/selfassessment/display.coffee @@ -0,0 +1,133 @@ +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.') diff --git a/common/lib/xmodule/xmodule/js/src/video/display/video_caption.coffee b/common/lib/xmodule/xmodule/js/src/video/display/video_caption.coffee index b1e41afc3c..cdd74c5d07 100644 --- a/common/lib/xmodule/xmodule/js/src/video/display/video_caption.coffee +++ b/common/lib/xmodule/xmodule/js/src/video/display/video_caption.coffee @@ -22,7 +22,7 @@ class @VideoCaption extends Subview """ @$('.video-controls .secondary-controls').append """ Captions - """ + """#" @$('.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() diff --git a/common/lib/xmodule/xmodule/js/src/video/display/video_control.coffee b/common/lib/xmodule/xmodule/js/src/video/display/video_control.coffee index 5053f1dcb1..856549c3e2 100644 --- a/common/lib/xmodule/xmodule/js/src/video/display/video_control.coffee +++ b/common/lib/xmodule/xmodule/js/src/video/display/video_control.coffee @@ -16,7 +16,7 @@ class @VideoControl extends Subview Fill Browser
- """ + """#" unless onTouchBasedDevice() @$('.video_control').addClass('play').html('Play') diff --git a/common/lib/xmodule/xmodule/js/src/video/display/video_player.coffee b/common/lib/xmodule/xmodule/js/src/video/display/video_player.coffee index bb89def63d..8829e25dac 100644 --- a/common/lib/xmodule/xmodule/js/src/video/display/video_player.coffee +++ b/common/lib/xmodule/xmodule/js/src/video/display/video_player.coffee @@ -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() diff --git a/common/lib/xmodule/xmodule/js/src/video/display/video_quality_control.coffee b/common/lib/xmodule/xmodule/js/src/video/display/video_quality_control.coffee new file mode 100644 index 0000000000..f8f6167075 --- /dev/null +++ b/common/lib/xmodule/xmodule/js/src/video/display/video_quality_control.coffee @@ -0,0 +1,26 @@ +class @VideoQualityControl extends Subview + initialize: -> + @quality = null; + + bind: -> + @$('.quality_control').click @toggleQuality + + render: -> + @el.append """ + HD + """#" + + 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 diff --git a/common/lib/xmodule/xmodule/js/src/video/display/video_volume_control.coffee b/common/lib/xmodule/xmodule/js/src/video/display/video_volume_control.coffee index 10d3f6b044..096b50042d 100644 --- a/common/lib/xmodule/xmodule/js/src/video/display/video_volume_control.coffee +++ b/common/lib/xmodule/xmodule/js/src/video/display/video_volume_control.coffee @@ -17,7 +17,7 @@ class @VideoVolumeControl extends Subview
- """ + """#" @slider = @$('.volume-slider').slider orientation: "vertical" range: "min" diff --git a/common/lib/xmodule/xmodule/self_assessment_module.py b/common/lib/xmodule/xmodule/self_assessment_module.py new file mode 100644 index 0000000000..2edf5467b2 --- /dev/null +++ b/common/lib/xmodule/xmodule/self_assessment_module.py @@ -0,0 +1,476 @@ +""" +A Self Assessment module that allows students to write open-ended responses, +submit, then see a rubric and rate themselves. Persists student supplied +hints, answers, and assessment judgment (currently only correct/incorrect). +Parses xml definition file--see below for exact format. +""" + +import copy +from fs.errors import ResourceNotFoundError +import logging +import os +import sys +from lxml import etree +from lxml.html import rewrite_links +from path import path +import json +from progress import Progress + +from pkg_resources import resource_string + +from .capa_module import only_one, ComplexEncoder +from .editing_module import EditingDescriptor +from .html_checker import check_html +from .stringify import stringify_children +from .x_module import XModule +from .xml_module import XmlDescriptor +from xmodule.modulestore import Location + +log = logging.getLogger("mitx.courseware") + +# Set the default number of max attempts. Should be 1 for production +# Set higher for debugging/testing +# attempts specified in xml definition overrides this. +MAX_ATTEMPTS = 1 + +# Set maximum available number of points. +# Overriden by max_score specified in xml. +MAX_SCORE = 1 + +class SelfAssessmentModule(XModule): + """ + States: + + initial (prompt, textbox shown) + | + assessing (read-only textbox, rubric + assessment input shown) + | + request_hint (read-only textbox, read-only rubric and assessment, hint input box shown) + | + done (submitted msg, green checkmark, everything else read-only. If attempts < max, shows + a reset button that goes back to initial state. Saves previous + submissions too.) + """ + + # states + INITIAL = 'initial' + ASSESSING = 'assessing' + REQUEST_HINT = 'request_hint' + DONE = 'done' + + js = {'coffee': [resource_string(__name__, 'js/src/selfassessment/display.coffee')]} + js_module_name = "SelfAssessment" + + def __init__(self, system, location, definition, descriptor, + instance_state=None, shared_state=None, **kwargs): + XModule.__init__(self, system, location, definition, descriptor, + instance_state, shared_state, **kwargs) + + """ + Definition file should have 4 blocks -- prompt, rubric, submitmessage, hintprompt, + and two optional attributes: + attempts, which should be an integer that defaults to 1. + If it's > 1, the student will be able to re-submit after they see + the rubric. + max_score, which should be an integer that defaults to 1. + It defines the maximum number of points a student can get. Assumed to be integer scale + from 0 to max_score, with an interval of 1. + + Note: all the submissions are stored. + + Sample file: + + + + Insert prompt text here. (arbitrary html) + + + Insert grading rubric here. (arbitrary html) + + + Please enter a hint below: (arbitrary html) + + + Thanks for submitting! (arbitrary html) + + + """ + + # Load instance state + if instance_state is not None: + instance_state = json.loads(instance_state) + else: + instance_state = {} + + # Note: score responses are on scale from 0 to max_score + self.student_answers = instance_state.get('student_answers', []) + self.scores = instance_state.get('scores', []) + self.hints = instance_state.get('hints', []) + + self.state = instance_state.get('state', 'initial') + + # Used for progress / grading. Currently get credit just for + # completion (doesn't matter if you self-assessed correct/incorrect). + + self._max_score = int(self.metadata.get('max_score', MAX_SCORE)) + + self.attempts = instance_state.get('attempts', 0) + + self.max_attempts = int(self.metadata.get('attempts', MAX_ATTEMPTS)) + + self.rubric = definition['rubric'] + self.prompt = definition['prompt'] + self.submit_message = definition['submitmessage'] + self.hint_prompt = definition['hintprompt'] + + def _allow_reset(self): + """Can the module be reset?""" + return self.state == self.DONE and self.attempts < self.max_attempts + + def get_html(self): + #set context variables and render template + if self.state != self.INITIAL and self.student_answers: + previous_answer = self.student_answers[-1] + else: + previous_answer = '' + + context = { + 'prompt': self.prompt, + 'previous_answer': previous_answer, + 'ajax_url': self.system.ajax_url, + 'initial_rubric': self.get_rubric_html(), + 'initial_hint': self.get_hint_html(), + 'initial_message': self.get_message_html(), + 'state': self.state, + 'allow_reset': self._allow_reset(), + } + html = self.system.render_template('self_assessment_prompt.html', context) + + # cdodge: perform link substitutions for any references to course static content (e.g. images) + return rewrite_links(html, self.rewrite_content_links) + + def get_score(self): + """ + Returns dict with 'score' key + """ + return {'score': self.get_last_score()} + + def max_score(self): + """ + Return max_score + """ + return self._max_score + + def get_last_score(self): + """ + Returns the last score in the list + """ + last_score=0 + if(len(self.scores)>0): + last_score=self.scores[len(self.scores)-1] + return last_score + + def get_progress(self): + ''' + For now, just return last score / max_score + ''' + if self._max_score > 0: + try: + return Progress(self.get_last_score(), self._max_score) + except Exception as err: + log.exception("Got bad progress") + return None + return None + + + def handle_ajax(self, dispatch, get): + """ + This is called by courseware.module_render, to handle an AJAX call. + "get" is request.POST. + + Returns a json dictionary: + { 'progress_changed' : True/False, + 'progress': 'none'/'in_progress'/'done', + } + """ + + handlers = { + 'save_answer': self.save_answer, + 'save_assessment': self.save_assessment, + 'save_hint': self.save_hint, + 'reset': self.reset, + } + + if dispatch not in handlers: + return 'Error' + + before = self.get_progress() + d = handlers[dispatch](get) + after = self.get_progress() + d.update({ + 'progress_changed': after != before, + 'progress_status': Progress.to_js_status_str(after), + }) + return json.dumps(d, cls=ComplexEncoder) + + def out_of_sync_error(self, get, msg=''): + """ + return dict out-of-sync error message, and also log. + """ + log.warning("Assessment module state out sync. state: %r, get: %r. %s", + self.state, get, msg) + return {'success': False, + 'error': 'The problem state got out-of-sync'} + + def get_rubric_html(self): + """ + Return the appropriate version of the rubric, based on the state. + """ + if self.state == self.INITIAL: + return '' + + # we'll render it + context = {'rubric': self.rubric, + 'max_score' : self._max_score, + } + + if self.state == self.ASSESSING: + context['read_only'] = False + elif self.state in (self.REQUEST_HINT, self.DONE): + context['read_only'] = True + else: + raise ValueError("Illegal state '%r'" % self.state) + + return self.system.render_template('self_assessment_rubric.html', context) + + def get_hint_html(self): + """ + Return the appropriate version of the hint view, based on state. + """ + if self.state in (self.INITIAL, self.ASSESSING): + return '' + + if self.state == self.DONE and len(self.hints) > 0: + # display the previous hint + hint = self.hints[-1] + else: + hint = '' + + context = {'hint_prompt': self.hint_prompt, + 'hint': hint} + + if self.state == self.REQUEST_HINT: + context['read_only'] = False + elif self.state == self.DONE: + context['read_only'] = True + else: + raise ValueError("Illegal state '%r'" % self.state) + + return self.system.render_template('self_assessment_hint.html', context) + + def get_message_html(self): + """ + Return the appropriate version of the message view, based on state. + """ + if self.state != self.DONE: + return "" + + return """
{0}
""".format(self.submit_message) + + + def save_answer(self, get): + """ + After the answer is submitted, show the rubric. + """ + # Check to see if attempts are less than max + if self.attempts > self.max_attempts: + # If too many attempts, prevent student from saving answer and + # seeing rubric. In normal use, students shouldn't see this because + # they won't see the reset button once they're out of attempts. + return { + 'success': False, + 'error': 'Too many attempts.' + } + + if self.state != self.INITIAL: + return self.out_of_sync_error(get) + + self.student_answers.append(get['student_answer']) + self.state = self.ASSESSING + + return { + 'success': True, + 'rubric_html': self.get_rubric_html() + } + + def save_assessment(self, get): + """ + Save the assessment. If the student said they're right, don't ask for a + hint, and go straight to the done state. Otherwise, do ask for a hint. + + Returns a dict { 'success': bool, 'state': state, + + 'hint_html': hint_html OR 'message_html': html and 'allow_reset', + + 'error': error-msg}, + + with 'error' only present if 'success' is False, and 'hint_html' or + 'message_html' only if success is true + """ + + n_answers = len(self.student_answers) + n_scores = len(self.scores) + if (self.state != self.ASSESSING or n_answers != n_scores + 1): + msg = "%d answers, %d scores" % (n_answers, n_scores) + return self.out_of_sync_error(get, msg) + + try: + score = int(get['assessment']) + except: + return {'success': False, 'error': "Non-integer score value"} + + self.scores.append(score) + + d = {'success': True,} + + if score == self.max_score(): + self.state = self.DONE + d['message_html'] = self.get_message_html() + d['allow_reset'] = self._allow_reset() + else: + self.state = self.REQUEST_HINT + d['hint_html'] = self.get_hint_html() + + d['state'] = self.state + return d + + + def save_hint(self, get): + ''' + Save the hint. + Returns a dict { 'success': bool, + 'message_html': message_html, + 'error': error-msg, + 'allow_reset': bool}, + with the error key only present if success is False and message_html + only if True. + ''' + if self.state != self.REQUEST_HINT: + # Note: because we only ask for hints on wrong answers, may not have + # the same number of hints and answers. + return self.out_of_sync_error(get) + + self.hints.append(get['hint'].lower()) + self.state = self.DONE + + # increment attempts + self.attempts = self.attempts + 1 + + # To the tracking logs! + event_info = { + 'selfassessment_id': self.location.url(), + 'state': { + 'student_answers': self.student_answers, + 'score': self.scores, + 'hints': self.hints, + } + } + self.system.track_function('save_hint', event_info) + + return {'success': True, + 'message_html': self.get_message_html(), + 'allow_reset': self._allow_reset()} + + + def reset(self, get): + """ + If resetting is allowed, reset the state. + + Returns {'success': bool, 'error': msg} + (error only present if not success) + """ + if self.state != self.DONE: + return self.out_of_sync_error(get) + + if self.attempts > self.max_attempts: + return { + 'success': False, + 'error': 'Too many attempts.' + } + self.state = self.INITIAL + return {'success': True} + + + def get_instance_state(self): + """ + Get the current score and state + """ + + state = { + 'student_answers': self.student_answers, + 'hints': self.hints, + 'state': self.state, + 'scores': self.scores, + 'max_score': self._max_score, + 'attempts': self.attempts + } + return json.dumps(state) + + +class SelfAssessmentDescriptor(XmlDescriptor, EditingDescriptor): + """ + Module for adding self assessment questions to courses + """ + mako_template = "widgets/html-edit.html" + module_class = SelfAssessmentModule + filename_extension = "xml" + + stores_state = True + has_score = True + template_dir_name = "selfassessment" + + js = {'coffee': [resource_string(__name__, 'js/src/html/edit.coffee')]} + js_module_name = "HTMLEditingDescriptor" + + @classmethod + def definition_from_xml(cls, xml_object, system): + """ + Pull out the rubric, prompt, and submitmessage into a dictionary. + + Returns: + { + 'rubric': 'some-html', + 'prompt': 'some-html', + 'submitmessage': 'some-html' + 'hintprompt': 'some-html' + } + """ + expected_children = ['rubric', 'prompt', 'submitmessage', 'hintprompt'] + for child in expected_children: + if len(xml_object.xpath(child)) != 1: + raise ValueError("Self assessment definition must include exactly one '{0}' tag".format(child)) + + def parse(k): + """Assumes that xml_object has child k""" + return stringify_children(xml_object.xpath(k)[0]) + + return {'rubric': parse('rubric'), + 'prompt': parse('prompt'), + 'submitmessage': parse('submitmessage'), + 'hintprompt': parse('hintprompt'), + } + + + def definition_to_xml(self, resource_fs): + '''Return an xml element representing this definition.''' + elt = etree.Element('selfassessment') + + def add_child(k): + child_str = '<{tag}>{body}'.format(tag=k, body=self.definition[k]) + child_node = etree.fromstring(child_str) + elt.append(child_node) + + for child in ['rubric', 'prompt', 'submitmessage', 'hintprompt']: + add_child(child) + + return elt diff --git a/common/lib/xmodule/xmodule/tests/test_export.py b/common/lib/xmodule/xmodule/tests/test_export.py index 826e6c9d5a..aeebc6da6b 100644 --- a/common/lib/xmodule/xmodule/tests/test_export.py +++ b/common/lib/xmodule/xmodule/tests/test_export.py @@ -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") diff --git a/common/lib/xmodule/xmodule/tests/test_import.py b/common/lib/xmodule/xmodule/tests/test_import.py index 21dd8968f6..77532959d7 100644 --- a/common/lib/xmodule/xmodule/tests/test_import.py +++ b/common/lib/xmodule/xmodule/tests/test_import.py @@ -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 = ["""""", + """""", + """ """, + """""", + """"""] + + no = ["""""", + """some text""", + """tree""", + """ + 3 + + """] + + 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') diff --git a/common/lib/xmodule/xmodule/video_module.py b/common/lib/xmodule/xmodule/video_module.py index 11c90f45ef..9a22950ca8 100644 --- a/common/lib/xmodule/xmodule/video_module.py +++ b/common/lib/xmodule/xmodule/video_module.py @@ -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'], diff --git a/common/lib/xmodule/xmodule/xml_module.py b/common/lib/xmodule/xmodule/xml_module.py index a5b3460f17..ec755af4ef 100644 --- a/common/lib/xmodule/xmodule/xml_module.py +++ b/common/lib/xmodule/xmodule/xml_module.py @@ -25,7 +25,7 @@ def name_to_pathname(name): def is_pointer_tag(xml_obj): """ Check if xml_obj is a pointer tag: . - No children, one attribute named url_name. + No children, one attribute named url_name, no text. Special case for course roots: the pointer is @@ -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') diff --git a/common/static/images/hd.png b/common/static/images/hd.png new file mode 100644 index 0000000000..d6b8c1b7d1 Binary files /dev/null and b/common/static/images/hd.png differ diff --git a/common/test/data/full/problem/choiceresponse_demo.xml b/common/test/data/full/problem/choiceresponse_demo.xml new file mode 100644 index 0000000000..f7d1fcf16c --- /dev/null +++ b/common/test/data/full/problem/choiceresponse_demo.xml @@ -0,0 +1,37 @@ + + + +

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.

+
+ +

a. The magnitude of the force experienced by the electron is proportional the product of which of the following? (Select all that apply.)

+ + + +Magnetic field strength +Electric field strength +Electric charge of the electron +Radius of the electron +Mass of the electron +Velocity of the electron + + + + + +

b. The direction of the force experienced by the electron is _______.

+ + + +up, in the plane of the screen. +down, in the plane of the screen. +into the plane of the screen. +out of the plane of the screen. +towards the right, in the plane of the screen. +towards the left, in the plane of the screen. + + + + + +
diff --git a/common/test/data/full/problem/codeinput_demo.xml b/common/test/data/full/problem/codeinput_demo.xml new file mode 100644 index 0000000000..03d8fd8c31 --- /dev/null +++ b/common/test/data/full/problem/codeinput_demo.xml @@ -0,0 +1,205 @@ + + + +

+ Part 1: Function Types +

+

+For each of the following functions, specify the type of its output. You can assume each function is called with an appropriate argument, as specified by its docstring.

+

+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.

+

+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.

+

+

+
+
+ What are those lines under the function definitions? +
+
+

+In this and future problems, you'll see function definitions that look like this:

+
+def a(x):
+   '''
+   x: int or float.
+   '''
+   return x + 1
+
+

+What are those three lines between def a(x): and return x + 1? These lines are called the docstring 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.

+

+In Python, docstrings appear immediately after the def 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:

+
+def myFunction(argument):
+   """
+   Docstring goes here. Explain what type argument(s) should have, and what your function
+   is going to return.
+   """
+   < Code for your function (the body of the function) goes here >
+
+

+As you begin coding your own functions, we strongly encourage you to document all your functions by using properly-formatted docstrings!

+
+
+
+

+
    +
  1. +
    +def a(x):
    +   '''
    +   x: int or float.
    +   '''
    +   return x + 1
    + 
    +

    + Indicate the type of the output that the function a will yield.

    +
  2. +
  3. +
    +def b(x):
    +   '''
    +   x: int or float.
    +   '''
    +   return x + 1.0
    + 
    +

    + Indicate the type of the output that the function b will yield.

    +
  4. +
  5. +
    +def c(x, y):
    +   '''
    +   x: int or float. 
    +   y: int or float.
    +   '''
    +   return x + y
    + 
    +

    + Indicate the type of the output that the function c will yield.

    +
  6. +
  7. +
    +def d(x, y):
    +   '''
    +   x: Can be of any type.
    +   y: Can be of any type.
    +   '''
    +   return x > y
    + 
    +

    + Indicate the type of the output that the function d will yield.

    +
  8. +
  9. +
    +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 >= y and x <= z
    + 
    +

    + Indicate the type of the output that the function e will yield.

    +
  10. +
  11. +
    +def f(x, y):
    +   '''
    +   x: int or float.
    +   y: int or float
    +   '''
    +   x + y - 2
    + 
    +

    + Indicate the type of the output that the function f will yield.

    +
  12. +
+

+ Part 2: Transcript +

+

+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.

+
    +
  1. +

    + a(6) + + + + + + +

    +
  2. +
  3. +

    + a(-5.3) + + + + + + +

    +
  4. +
  5. +

    + a(a(a(6))) + + + + + + +

    +
  6. +
  7. +

    + c(a(1), b(1)) + + + + + + +

    +
  8. +
  9. +

    + d('apple', 11.1) + + + + + + +

    +
  10. +
  11. +

    + e(a(3), b(4), c(3, 4)) + + + + + + +

    +
  12. +
  13. +

    + f + + + + + + +

    +
  14. +
+
+
diff --git a/common/test/data/full/problem/multiplechoicelresponse_demo.xml b/common/test/data/full/problem/multiplechoicelresponse_demo.xml new file mode 100644 index 0000000000..b3e89a39e3 --- /dev/null +++ b/common/test/data/full/problem/multiplechoicelresponse_demo.xml @@ -0,0 +1,17 @@ + + +

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?

+ + + + + + The ion would deflect identically as both species have the same charge. + 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. + The deflection will be in the same direction but smaller in magnitude due to the larger mass of the ion. + 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. + + + + +
\ No newline at end of file diff --git a/common/test/data/full/problem/numericalresponse_demo.xml b/common/test/data/full/problem/numericalresponse_demo.xml new file mode 100644 index 0000000000..629b56edfd --- /dev/null +++ b/common/test/data/full/problem/numericalresponse_demo.xml @@ -0,0 +1,31 @@ + + + +

Gaseous hydrogen can be reacted with gaseous oxygen in the presence of a flame to produce water vapor according to the following reaction:

+ [mathjax] \text{ a } \text{H}_{2 } + \text{ b }\text{O}_{2 } = \text{ c }\text{H}_{2 }\text{O }[/mathjax] +

Balance the equation i.e., specify the values of a, b, and c. Use the lowest whole number coefficients.

+ +

a =

+ + + + + + +

b = + + + +

+ +

c = + + + +

+ + +
+
+ + diff --git a/common/test/data/full/problem/test_files/chemicalformularesponse.xml b/common/test/data/full/problem/test_files/chemicalformularesponse.xml new file mode 100644 index 0000000000..28591013f5 --- /dev/null +++ b/common/test/data/full/problem/test_files/chemicalformularesponse.xml @@ -0,0 +1,64 @@ + + +

Metallothermic production of zirconium (Zr) would involve the reaction of sodium (Na) with zirconium tetrachloride (ZrCl4).

+ +

(a) Write a balanced chemical equation.

+ + + + + + + +if chemcalc.chemical_equations_equal(submission[0], 'ZrCl4 + 4 Na -> 4 NaCl + Zr'): + correct = ['correct'] +else: + correct = ['incorrect'] + + + + +

(b) Write the balanced chemical equation using lowest whole numbers.

+ + + + + + + +if chemcalc.chemical_equations_equal(submission[0], 'ZrCl4 + 4 Na -> 4 NaCl + Zr', exact=True): + correct = ['correct'] +else: + correct = ['incorrect'] + + + + + + +

(c) 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]. + + + +

+
+ +

SOLUTION:

+

(b)[mathjax] \text{ZrCl}_{4 } + \mathbf{4 }\text{Na} = \mathbf{4 }\text{NaCl } + \mathbf{1 } \text{Zr} [/mathjax]

+

(c)

+

[mathjaxinline]111\text{kg ZrCl}_4 = 111000/[91.22 + (4 \times 35.45)] = 476 \text{ moles ZrCl}_4[/mathjaxinline]

+

[mathjaxinline]11.1\text{ kg Na} = 11100/22.99 = 483\text{ moles C}[/mathjaxinline]

+

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]

+

[mathjaxinline]\therefore[/mathjaxinline] reaction yield is contrained by [mathjaxinline]\text{Na}[/mathjaxinline] present

+

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

+ [mathjaxinline]121 \text{ moles Zr} \times 91.22\text{ g / mol } \mathbf{= 11.0 \text{ kg Zr} }[/mathjaxinline]
+
+
+
+ + diff --git a/common/test/data/full/problem/test_files/choiceresponse_checkbox.xml b/common/test/data/full/problem/test_files/choiceresponse_checkbox.xml new file mode 100644 index 0000000000..c087266d04 --- /dev/null +++ b/common/test/data/full/problem/test_files/choiceresponse_checkbox.xml @@ -0,0 +1,59 @@ + + + + + This is foil One. + + + This is foil Two. + + + This is foil Three. + + + This is foil Four. + + + This is foil Five. + + + + + + + This is foil One. + + + This is foil Two. + + + This is foil Three. + + + This is foil Four. + + + This is foil Five. + + + + + + + This is foil One. + + + This is foil Two. + + + This is foil Three. + + + This is foil Four. + + + This is foil Five. + + + + diff --git a/common/test/data/full/problem/test_files/choiceresponse_radio.xml b/common/test/data/full/problem/test_files/choiceresponse_radio.xml new file mode 100644 index 0000000000..a85d663b2b --- /dev/null +++ b/common/test/data/full/problem/test_files/choiceresponse_radio.xml @@ -0,0 +1,40 @@ + + + + + This is foil One. + + + This is foil Two. + + + This is foil Three. + + + This is foil Four. + + + This is foil Five. + + + + + + + This is foil One. + + + This is foil Two. + + + This is foil Three. + + + This is foil Four. + + + This is foil Five. + + + + diff --git a/common/test/data/full/problem/test_files/coderesponse.xml b/common/test/data/full/problem/test_files/coderesponse.xml new file mode 100644 index 0000000000..1c0bf8d4e6 --- /dev/null +++ b/common/test/data/full/problem/test_files/coderesponse.xml @@ -0,0 +1,33 @@ + + +

Code response

+ +

+

+ + +Write a program to compute the square of a number + + + + def square(x): + answer + grader stuff + + + + + +Write a program to compute the square of a number + + + + def square(x): + answer + grader stuff + + + + +
+
diff --git a/common/test/data/full/problem/test_files/coderesponse_externalresponseformat.xml b/common/test/data/full/problem/test_files/coderesponse_externalresponseformat.xml new file mode 100644 index 0000000000..42b6e0a54a --- /dev/null +++ b/common/test/data/full/problem/test_files/coderesponse_externalresponseformat.xml @@ -0,0 +1,101 @@ + + +

Code response

+ +

+

+ + +Write a program to compute the square of a number + + + + + + + + +Write a program to compute the cube of a number + + + + + + + +
+
diff --git a/common/test/data/full/problem/test_files/formularesponse_with_hint.xml b/common/test/data/full/problem/test_files/formularesponse_with_hint.xml new file mode 100644 index 0000000000..90248dcf04 --- /dev/null +++ b/common/test/data/full/problem/test_files/formularesponse_with_hint.xml @@ -0,0 +1,45 @@ + + + + +

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.

+ +

+What is the equation of the line which passess through ($x1,$y1) and +($x2,$y2)?

+ +

The correct answer is $answer. A common error is to invert the equation for the slope. Enter +$wrongans to see a hint.

+ +
+ + + + y = + + + + + You have inverted the slope in the question. + + + +
+ diff --git a/common/test/data/full/problem/test_files/imageresponse.xml b/common/test/data/full/problem/test_files/imageresponse.xml new file mode 100644 index 0000000000..34dba37e3b --- /dev/null +++ b/common/test/data/full/problem/test_files/imageresponse.xml @@ -0,0 +1,21 @@ + +

+Two skiers are on frictionless black diamond ski slopes. +Hello

+ + + +Click on the image where the top skier will stop momentarily if the top skier starts from rest. + +Click on the image where the lower skier will stop momentarily if the lower skier starts from rest. + +Click on either of the two positions as discussed previously. + +Click on either of the two positions as discussed previously. + +Click on either of the two positions as discussed previously. + +

Use conservation of energy.

+
+
+
diff --git a/common/test/data/full/problem/test_files/javascriptresponse.xml b/common/test/data/full/problem/test_files/javascriptresponse.xml new file mode 100644 index 0000000000..439866e62c --- /dev/null +++ b/common/test/data/full/problem/test_files/javascriptresponse.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + diff --git a/common/test/data/full/problem/test_files/multi_bare.xml b/common/test/data/full/problem/test_files/multi_bare.xml new file mode 100644 index 0000000000..20bc8f853d --- /dev/null +++ b/common/test/data/full/problem/test_files/multi_bare.xml @@ -0,0 +1,21 @@ + + + + + This is foil One. + + + This is foil Two. + + + This is foil Three. + + + This is foil Four. + + + This is foil Five. + + + + diff --git a/common/test/data/full/problem/test_files/multichoice.xml b/common/test/data/full/problem/test_files/multichoice.xml new file mode 100644 index 0000000000..60bf02ec59 --- /dev/null +++ b/common/test/data/full/problem/test_files/multichoice.xml @@ -0,0 +1,21 @@ + + + + + This is foil One. + + + This is foil Two. + + + This is foil Three. + + + This is foil Four. + + + This is foil Five. + + + + diff --git a/common/test/data/full/problem/test_files/multiplechoicelresponse_demo.xml b/common/test/data/full/problem/test_files/multiplechoicelresponse_demo.xml new file mode 100644 index 0000000000..b3e89a39e3 --- /dev/null +++ b/common/test/data/full/problem/test_files/multiplechoicelresponse_demo.xml @@ -0,0 +1,17 @@ + + +

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?

+ + + + + + The ion would deflect identically as both species have the same charge. + 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. + The deflection will be in the same direction but smaller in magnitude due to the larger mass of the ion. + 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. + + + + +
\ No newline at end of file diff --git a/common/test/data/full/problem/test_files/numericalresponse_demo.xml b/common/test/data/full/problem/test_files/numericalresponse_demo.xml new file mode 100644 index 0000000000..629b56edfd --- /dev/null +++ b/common/test/data/full/problem/test_files/numericalresponse_demo.xml @@ -0,0 +1,31 @@ + + + +

Gaseous hydrogen can be reacted with gaseous oxygen in the presence of a flame to produce water vapor according to the following reaction:

+ [mathjax] \text{ a } \text{H}_{2 } + \text{ b }\text{O}_{2 } = \text{ c }\text{H}_{2 }\text{O }[/mathjax] +

Balance the equation i.e., specify the values of a, b, and c. Use the lowest whole number coefficients.

+ +

a =

+ + + + + + +

b = + + + +

+ +

c = + + + +

+ + +
+
+ + diff --git a/common/test/data/full/problem/test_files/optionresponse.xml b/common/test/data/full/problem/test_files/optionresponse.xml new file mode 100644 index 0000000000..99a17e8fac --- /dev/null +++ b/common/test/data/full/problem/test_files/optionresponse.xml @@ -0,0 +1,63 @@ + + +

+Why do bicycles benefit from having larger wheels when going up a bump as shown in the picture?
+Assume that for both bicycles:
+1.) The tires have equal air pressure.
+2.) The bicycles never leave the contact with the bump.
+3.) The bicycles have the same mass. The bicycle tires (regardless of size) have the same mass.
+

+
+ +
    +
  • + +

    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.

    +
    + + +
  • +
  • + +

    The bicycles with larger wheels always have a smaller vertical displacement regardless of speed.

    +
    + + +
  • +
  • + +

    The bicycles with larger wheels experience a force backward with less magnitude for the same amount of time.

    +
    + + +
  • +
  • + +

    The bicycles with larger wheels experience a force backward with less magnitude for a greater amount of time.

    +
    + + +
  • +
  • + +

    The bicycles with larger wheels have more kinetic energy turned into gravitational potential energy.

    +
    + + +
  • +
  • + +

    The bicycles with larger wheels have more rotational kinetic energy, so the horizontal velocity of the biker changes less.

    +
    + + +
  • +
+ + +
+
+
+
+
+
diff --git a/common/test/data/full/problem/test_files/stringresponse_with_hint.xml b/common/test/data/full/problem/test_files/stringresponse_with_hint.xml new file mode 100644 index 0000000000..86efdf0f18 --- /dev/null +++ b/common/test/data/full/problem/test_files/stringresponse_with_hint.xml @@ -0,0 +1,25 @@ + +

Example: String Response Problem

+
+
+ + Which US state has Lansing as its capital? + + + + + + + + + The state capital of Wisconsin is Madison. + + + The state capital of Minnesota is St. Paul. + + + The state you are looking for is also known as the 'Great Lakes State' + + + +
diff --git a/common/test/data/full/problem/test_files/symbolicresponse.xml b/common/test/data/full/problem/test_files/symbolicresponse.xml new file mode 100644 index 0000000000..4dc2bc9d7b --- /dev/null +++ b/common/test/data/full/problem/test_files/symbolicresponse.xml @@ -0,0 +1,29 @@ + + +

Example: Symbolic Math Response Problem

+ +

+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. +

+ +

This is a correct answer which may be entered below:

+

cos(theta)*[[1,0],[0,1]] + i*sin(theta)*[[0,1],[1,0]]

+ + + Compute [mathjax] U = \exp\left( i \theta \left[ \begin{matrix} 0 & 1 \\ 1 & 0 \end{matrix} \right] \right) [/mathjax] + and give the resulting \(2 \times 2\) matrix.
+ Your input should be typed in as a list of lists, eg [[1,2],[3,4]].
+ [mathjax]U=[/mathjax] + + +
+
+ +
+
diff --git a/common/test/data/full/problem/test_files/truefalse.xml b/common/test/data/full/problem/test_files/truefalse.xml new file mode 100644 index 0000000000..60018f7a2d --- /dev/null +++ b/common/test/data/full/problem/test_files/truefalse.xml @@ -0,0 +1,21 @@ + + + + + This is foil One. + + + This is foil Two. + + + This is foil Three. + + + This is foil Four. + + + This is foil Five. + + + + diff --git a/common/test/data/full/vertical/test_problems.xml b/common/test/data/full/vertical/test_problems.xml new file mode 100644 index 0000000000..6cdc7977d9 --- /dev/null +++ b/common/test/data/full/vertical/test_problems.xml @@ -0,0 +1,20 @@ + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/common/test/data/self_assessment/README.md b/common/test/data/self_assessment/README.md new file mode 100644 index 0000000000..7fe58ac17f --- /dev/null +++ b/common/test/data/self_assessment/README.md @@ -0,0 +1 @@ +This is a very very simple course, useful for debugging self assessment code. diff --git a/common/test/data/self_assessment/course.xml b/common/test/data/self_assessment/course.xml new file mode 120000 index 0000000000..49041310f6 --- /dev/null +++ b/common/test/data/self_assessment/course.xml @@ -0,0 +1 @@ +roots/2012_Fall.xml \ No newline at end of file diff --git a/common/test/data/self_assessment/course/2012_Fall.xml b/common/test/data/self_assessment/course/2012_Fall.xml new file mode 100644 index 0000000000..bbbfb8b900 --- /dev/null +++ b/common/test/data/self_assessment/course/2012_Fall.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/common/test/data/self_assessment/policies/2012_Fall.json b/common/test/data/self_assessment/policies/2012_Fall.json new file mode 100644 index 0000000000..aae4670296 --- /dev/null +++ b/common/test/data/self_assessment/policies/2012_Fall.json @@ -0,0 +1,14 @@ +{ + "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", + }, +} diff --git a/common/test/data/self_assessment/roots/2012_Fall.xml b/common/test/data/self_assessment/roots/2012_Fall.xml new file mode 100644 index 0000000000..ea7d5c420d --- /dev/null +++ b/common/test/data/self_assessment/roots/2012_Fall.xml @@ -0,0 +1 @@ + diff --git a/common/test/data/self_assessment/selfassessment/SampleQuestion.xml b/common/test/data/self_assessment/selfassessment/SampleQuestion.xml new file mode 100644 index 0000000000..6c383763b1 --- /dev/null +++ b/common/test/data/self_assessment/selfassessment/SampleQuestion.xml @@ -0,0 +1,14 @@ + + + What is the meaning of life? + + + This is a rubric. + + + Thanks for your submission! + + + Enter a hint below: + + diff --git a/create-dev-env.sh b/create-dev-env.sh index 2149161bb6..e481d3fd5e 100755 --- a/create-dev-env.sh +++ b/create-dev-env.sh @@ -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 ;; *) diff --git a/doc/mongo.md b/doc/mongo.md new file mode 100644 index 0000000000..efe3b4494f --- /dev/null +++ b/doc/mongo.md @@ -0,0 +1,145 @@ +# 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 } } diff --git a/doc/xml-format.md b/doc/xml-format.md index d9c0d27653..46082b90ad 100644 --- a/doc/xml-format.md +++ b/doc/xml-format.md @@ -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 diff --git a/docs/Makefile b/docs/Makefile new file mode 100644 index 0000000000..1d3bb030a1 --- /dev/null +++ b/docs/Makefile @@ -0,0 +1,153 @@ +# 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 ' where 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." diff --git a/docs/source/_static/homepage-bg.jpg b/docs/source/_static/homepage-bg.jpg new file mode 100644 index 0000000000..61da5545c1 Binary files /dev/null and b/docs/source/_static/homepage-bg.jpg differ diff --git a/docs/source/_templates/layout.html b/docs/source/_templates/layout.html new file mode 100644 index 0000000000..66ff998af1 --- /dev/null +++ b/docs/source/_templates/layout.html @@ -0,0 +1,5 @@ +{% extends "!layout.html" %} + +{% block header %} +Edx logo +{% endblock %} \ No newline at end of file diff --git a/docs/source/capa.rst b/docs/source/capa.rst new file mode 100644 index 0000000000..f83d89f52d --- /dev/null +++ b/docs/source/capa.rst @@ -0,0 +1,54 @@ +******************************************* +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: diff --git a/docs/source/cms.rst b/docs/source/cms.rst new file mode 100644 index 0000000000..02dcaccb5a --- /dev/null +++ b/docs/source/cms.rst @@ -0,0 +1,89 @@ +******************************************* +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 diff --git a/docs/source/common-lib.rst b/docs/source/common-lib.rst new file mode 100644 index 0000000000..4fa5eaeb0a --- /dev/null +++ b/docs/source/common-lib.rst @@ -0,0 +1,9 @@ +Common / lib +=============================== +Contents: + +.. toctree:: + :maxdepth: 2 + + xmodule.rst + capa.rst \ No newline at end of file diff --git a/docs/source/conf.py b/docs/source/conf.py new file mode 100644 index 0000000000..3b1e9dc5b9 --- /dev/null +++ b/docs/source/conf.py @@ -0,0 +1,330 @@ +# -*- coding: utf-8 -*- +# +# MITx documentation build configuration file, created by +# sphinx-quickstart on Fri Nov 2 15:43:00 2012. +# +# This file is execfile()d with the current directory set to its containing dir. +# +# Note that not all possible configuration values are present in this +# autogenerated file. +# +# All configuration values have a default; values that are commented out +# serve to show the default. + +import sys, os + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +sys.path.insert(0, os.path.abspath('.')) +sys.path.insert(0, os.path.abspath('../..')) # mitx folder +sys.path.insert(0, os.path.join(os.path.abspath('../..'), 'common', 'lib', 'capa')) # capa module +sys.path.insert(0, os.path.join(os.path.abspath('../..'), 'common', 'lib', 'xmodule')) # xmodule +sys.path.insert(0, os.path.join(os.path.abspath('../..'), 'lms', 'djangoapps')) # lms djangoapps +sys.path.insert(0, os.path.join(os.path.abspath('../..'), 'cms', 'djangoapps')) # cms djangoapps +sys.path.insert(0, os.path.join(os.path.abspath('../..'), 'common', 'djangoapps')) # common djangoapps + +# django configuration - careful here +import os +os.environ['DJANGO_SETTINGS_MODULE'] = 'lms.envs.dev' + + +# -- General configuration ----------------------------------------------------- + +# If your documentation needs a minimal Sphinx version, state it here. +#needs_sphinx = '1.0' + +# Add any Sphinx extension module names here, as strings. They can be extensions +# coming with Sphinx (named 'sphinx.ext.*') or your custom ones. +extensions = ['sphinx.ext.autodoc', 'sphinx.ext.doctest', 'sphinx.ext.intersphinx', 'sphinx.ext.todo', 'sphinx.ext.coverage', 'sphinx.ext.pngmath', 'sphinx.ext.mathjax', 'sphinx.ext.viewcode'] + +# Add any paths that contain templates here, relative to this directory. +templates_path = ['_templates'] + +# The suffix of source filenames. +source_suffix = '.rst' + +# The encoding of source files. +#source_encoding = 'utf-8-sig' + +# The master toctree document. +master_doc = 'index' + +# General information about the project. +project = u'MITx' +copyright = u'2012, MITx team' + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The short X.Y version. +version = '1.0' +# The full version, including alpha/beta/rc tags. +release = '1.0' + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +#language = None + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +#today = '' +# Else, today_fmt is used as the format for a strftime call. +#today_fmt = '%B %d, %Y' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +exclude_patterns = [] + +# The reST default role (used for this markup: `text`) to use for all documents. +#default_role = None + +# If true, '()' will be appended to :func: etc. cross-reference text. +#add_function_parentheses = True + +# If true, the current module name will be prepended to all description +# unit titles (such as .. function::). +#add_module_names = True + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +#show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = 'sphinx' + +# A list of ignored prefixes for module index sorting. +#modindex_common_prefix = [] + + +# -- Options for HTML output --------------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +html_theme = 'sphinxdoc' + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +#html_theme_options = {} + +# Add any paths that contain custom themes here, relative to this directory. +#html_theme_path = [] + +# The name for this set of Sphinx documents. If None, it defaults to +# " v documentation". +#html_title = None + +# A shorter title for the navigation bar. Default is the same as html_title. +#html_short_title = None + +# The name of an image file (relative to this directory) to place at the top +# of the sidebar. +#html_logo = None + +# The name of an image file (within the static path) to use as favicon of the +# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 +# pixels large. +#html_favicon = None + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ['_static'] + +# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, +# using the given strftime format. +#html_last_updated_fmt = '%b %d, %Y' + +# If true, SmartyPants will be used to convert quotes and dashes to +# typographically correct entities. +#html_use_smartypants = True + +# Custom sidebar templates, maps document names to template names. +#html_sidebars = {} + +# Additional templates that should be rendered to pages, maps page names to +# template names. +#html_additional_pages = {} + +# If false, no module index is generated. +#html_domain_indices = True + +# If false, no index is generated. +#html_use_index = True + +# If true, the index is split into individual pages for each letter. +#html_split_index = False + +# If true, links to the reST sources are added to the pages. +#html_show_sourcelink = True + +# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. +#html_show_sphinx = True + +# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. +#html_show_copyright = True + +# If true, an OpenSearch description file will be output, and all pages will +# contain a tag referring to it. The value of this option must be the +# base URL from which the finished HTML is served. +#html_use_opensearch = '' + +# This is the file name suffix for HTML files (e.g. ".xhtml"). +#html_file_suffix = None + +# Output file base name for HTML help builder. +htmlhelp_basename = 'MITxdoc' + + +# -- Options for LaTeX output -------------------------------------------------- + +latex_elements = { +# The paper size ('letterpaper' or 'a4paper'). +#'papersize': 'letterpaper', + +# The font size ('10pt', '11pt' or '12pt'). +#'pointsize': '10pt', + +# Additional stuff for the LaTeX preamble. +#'preamble': '', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, author, documentclass [howto/manual]). +latex_documents = [ + ('index', 'MITx.tex', u'MITx Documentation', + u'MITx team', 'manual'), +] + +# The name of an image file (relative to this directory) to place at the top of +# the title page. +#latex_logo = None + +# For "manual" documents, if this is true, then toplevel headings are parts, +# not chapters. +#latex_use_parts = False + +# If true, show page references after internal links. +#latex_show_pagerefs = False + +# If true, show URL addresses after external links. +#latex_show_urls = False + +# Documents to append as an appendix to all manuals. +#latex_appendices = [] + +# If false, no module index is generated. +#latex_domain_indices = True + + +# -- Options for manual page output -------------------------------------------- + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + ('index', 'mitx', u'MITx Documentation', + [u'MITx team'], 1) +] + +# If true, show URL addresses after external links. +#man_show_urls = False + + +# -- Options for Texinfo output ------------------------------------------------ + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + ('index', 'MITx', u'MITx Documentation', + u'MITx team', 'MITx', 'One line description of project.', + 'Miscellaneous'), +] + +# Documents to append as an appendix to all manuals. +#texinfo_appendices = [] + +# If false, no module index is generated. +#texinfo_domain_indices = True + +# How to display URL addresses: 'footnote', 'no', or 'inline'. +#texinfo_show_urls = 'footnote' + + +# Example configuration for intersphinx: refer to the Python standard library. +intersphinx_mapping = {'http://docs.python.org/': None} + +# from http://djangosnippets.org/snippets/2533/ +# autogenerate models definitions + +import inspect +from django.utils.html import strip_tags +from django.utils.encoding import force_unicode + + +def process_docstring(app, what, name, obj, options, lines): + # This causes import errors if left outside the function + from django.db import models + # from django import forms + # from django.forms.models import BaseInlineFormSet + + # Only look at objects that inherit from Django's base MODEL class + if inspect.isclass(obj) and issubclass(obj, models.Model): + # Grab the field list from the meta class + fields = obj._meta._fields() + + for field in fields: + # Decode and strip any html out of the field's help text + help_text = strip_tags(force_unicode(field.help_text)) + + # Decode and capitalize the verbose name, for use if there isn't + # any help text + verbose_name = force_unicode(field.verbose_name).capitalize() + + if help_text: + # Add the model field to the end of the docstring as a param + # using the help text as the description + lines.append(u':param %s: %s' % (field.attname, help_text)) + else: + # Add the model field to the end of the docstring as a param + # using the verbose name as the description + lines.append(u':param %s: %s' % (field.attname, verbose_name)) + + # Add the field's type to the docstring + lines.append(u':type %s: %s' % (field.attname, type(field).__name__)) + # Only look at objects that inherit from Django's base FORM class + # elif (inspect.isclass(obj) and issubclass(obj, forms.ModelForm) or issubclass(obj, forms.ModelForm) or issubclass(obj, BaseInlineFormSet)): + # pass + # # Grab the field list from the meta class + # import ipdb; ipdb.set_trace() + # fields = obj._meta._fields() + # import ipdb; ipdb.set_trace() + # for field in fields: + # import ipdb; ipdb.set_trace() + # # Decode and strip any html out of the field's help text + # help_text = strip_tags(force_unicode(field.help_text)) + + # # Decode and capitalize the verbose name, for use if there isn't + # # any help text + # verbose_name = force_unicode(field.verbose_name).capitalize() + + # if help_text: + # # Add the model field to the end of the docstring as a param + # # using the help text as the description + # lines.append(u':param %s: %s' % (field.attname, help_text)) + # else: + # # Add the model field to the end of the docstring as a param + # # using the verbose name as the description + # lines.append(u':param %s: %s' % (field.attname, verbose_name)) + + # # Add the field's type to the docstring + # lines.append(u':type %s: %s' % (field.attname, type(field).__name__)) + # Return the extended docstring + return lines + + +def setup(app): + # Register the docstring processor with sphinx + app.connect('autodoc-process-docstring', process_docstring) diff --git a/docs/source/djangoapps-common.rst b/docs/source/djangoapps-common.rst new file mode 100644 index 0000000000..0d67dfd591 --- /dev/null +++ b/docs/source/djangoapps-common.rst @@ -0,0 +1,54 @@ +******************************************* +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 diff --git a/docs/source/djangoapps.rst b/docs/source/djangoapps.rst new file mode 100644 index 0000000000..7a8414189a --- /dev/null +++ b/docs/source/djangoapps.rst @@ -0,0 +1,10 @@ +Django applications +=============================== +Contents: + +.. toctree:: + :maxdepth: 2 + + lms.rst + cms.rst + djangoapps-common.rst \ No newline at end of file diff --git a/docs/source/index.rst b/docs/source/index.rst new file mode 100644 index 0000000000..92c535a624 --- /dev/null +++ b/docs/source/index.rst @@ -0,0 +1,25 @@ +.. 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` + diff --git a/docs/source/lms.rst b/docs/source/lms.rst new file mode 100644 index 0000000000..36622114ab --- /dev/null +++ b/docs/source/lms.rst @@ -0,0 +1,401 @@ +******************************************* +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: diff --git a/docs/source/overview.rst b/docs/source/overview.rst new file mode 100644 index 0000000000..007c7582ad --- /dev/null +++ b/docs/source/overview.rst @@ -0,0 +1,20 @@ +******************************************* +What the pieces are? +******************************************* + +What +==== + +... + +How +=== + +... + + +Who +=== + + +... \ No newline at end of file diff --git a/docs/source/xmodule.rst b/docs/source/xmodule.rst new file mode 100644 index 0000000000..45caa82c30 --- /dev/null +++ b/docs/source/xmodule.rst @@ -0,0 +1,180 @@ +******************************************* +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: diff --git a/github-requirements.txt b/github-requirements.txt new file mode 100644 index 0000000000..468d55ce65 --- /dev/null +++ b/github-requirements.txt @@ -0,0 +1,5 @@ +# 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 diff --git a/jenkins/quality.sh b/jenkins/quality.sh new file mode 100755 index 0000000000..4cf26d76bf --- /dev/null +++ b/jenkins/quality.sh @@ -0,0 +1,14 @@ +#! /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" diff --git a/jenkins/test_edge.sh b/jenkins/test_edge.sh new file mode 100755 index 0000000000..7b58b481f6 --- /dev/null +++ b/jenkins/test_edge.sh @@ -0,0 +1,29 @@ +#! /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 diff --git a/jenkins/test_lms.sh b/jenkins/test_lms.sh new file mode 100755 index 0000000000..98640c2b5b --- /dev/null +++ b/jenkins/test_lms.sh @@ -0,0 +1,27 @@ +#! /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 diff --git a/lms/.coveragerc b/lms/.coveragerc new file mode 100644 index 0000000000..acac3ed4f2 --- /dev/null +++ b/lms/.coveragerc @@ -0,0 +1,13 @@ +# .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 diff --git a/lms/djangoapps/certificates/management/commands/find_unicode_certs.py b/lms/djangoapps/certificates/management/commands/find_unicode_certs.py new file mode 100644 index 0000000000..49497622c6 --- /dev/null +++ b/lms/djangoapps/certificates/management/commands/find_unicode_certs.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- + +from django.core.management.base import BaseCommand +from certificates.models import certificate_status_for_student +from certificates.queue import XQueueCertInterface +from django.contrib.auth.models import User +from student.models import UserProfile + + +class Command(BaseCommand): + + help = """ + Looks for names that have unicode characters + and queues them up for a certificate request + """ + + def handle(self, *args, **options): + + # TODO this is only temporary for CS169 certs + + course_id = 'BerkeleyX/CS169.1x/2012_Fall' + + enrolled_students = User.objects.filter( + courseenrollment__course_id=course_id).prefetch_related( + "groups").order_by('username') + xq = XQueueCertInterface() + print "Looking for unusual names.." + for student in enrolled_students: + if certificate_status_for_student( + student, course_id)['status'] == 'unavailable': + continue + name = UserProfile.objects.get(user=student).name + for c in name: + if ord(c) >= 0x200: + ret = xq.add_cert(student, course_id) + if ret == 'generating': + print 'generating for {0}'.format(student) + break diff --git a/lms/djangoapps/certificates/management/commands/ungenerated_certs.py b/lms/djangoapps/certificates/management/commands/ungenerated_certs.py index 7d384103ab..82e86c2097 100644 --- a/lms/djangoapps/certificates/management/commands/ungenerated_certs.py +++ b/lms/djangoapps/certificates/management/commands/ungenerated_certs.py @@ -1,22 +1,30 @@ -from django.utils.simplejson import dumps -from django.core.management.base import BaseCommand, CommandError -from certificates.models import GeneratedCertificate +from django.core.management.base import BaseCommand +from certificates.models import certificate_status_for_student +from certificates.queue import XQueueCertInterface +from django.contrib.auth.models import User class Command(BaseCommand): help = """ - This command finds all GeneratedCertificate objects that do not have a - certificate generated. These come into being when a user requests a - certificate, or when grade_all_students is called (for pre-generating - certificates). + Find all students that have need certificates + and put certificate requests on the queue - It returns a json formatted list of users and their user ids + This is only for BerkeleyX/CS169.1x/2012_Fall """ def handle(self, *args, **options): - users = GeneratedCertificate.objects.filter( - download_url=None) - user_output = [{'user_id':user.user_id, 'name':user.name} - for user in users] - self.stdout.write(dumps(user_output) + "\n") + + # TODO This is only temporary for CS169 certs + + course_id = 'BerkeleyX/CS169.1x/2012_Fall' + enrolled_students = User.objects.filter( + courseenrollment__course_id=course_id).prefetch_related( + "groups").order_by('username') + xq = XQueueCertInterface() + for student in enrolled_students: + if certificate_status_for_student( + student, course_id)['status'] == 'unavailable': + ret = xq.add_cert(student, course_id) + if ret == 'generating': + print 'generating for {0}'.format(student) diff --git a/lms/djangoapps/certificates/migrations/0008_auto__del_revokedcertificate__del_field_generatedcertificate_name__add.py b/lms/djangoapps/certificates/migrations/0008_auto__del_revokedcertificate__del_field_generatedcertificate_name__add.py new file mode 100644 index 0000000000..cbec7214c0 --- /dev/null +++ b/lms/djangoapps/certificates/migrations/0008_auto__del_revokedcertificate__del_field_generatedcertificate_name__add.py @@ -0,0 +1,163 @@ +# -*- coding: utf-8 -*- +import datetime +from south.db import db +from south.v2 import SchemaMigration +from django.db import models + + +class Migration(SchemaMigration): + + def forwards(self, orm): + # Deleting model 'RevokedCertificate' + db.delete_table('certificates_revokedcertificate') + + # Deleting field 'GeneratedCertificate.name' + db.delete_column('certificates_generatedcertificate', 'name') + + # Adding field 'GeneratedCertificate.course_id' + db.add_column('certificates_generatedcertificate', 'course_id', + self.gf('django.db.models.fields.CharField')(default=False, max_length=255), + keep_default=False) + + # Adding field 'GeneratedCertificate.key' + db.add_column('certificates_generatedcertificate', 'key', + self.gf('django.db.models.fields.CharField')(default=False, max_length=32), + keep_default=False) + + + # Changing field 'GeneratedCertificate.grade' + db.alter_column('certificates_generatedcertificate', 'grade', self.gf('django.db.models.fields.CharField')(max_length=5)) + + # Changing field 'GeneratedCertificate.certificate_id' + db.alter_column('certificates_generatedcertificate', 'certificate_id', self.gf('django.db.models.fields.CharField')(max_length=32)) + + # Changing field 'GeneratedCertificate.download_url' + db.alter_column('certificates_generatedcertificate', 'download_url', self.gf('django.db.models.fields.CharField')(max_length=128)) + + # Changing field 'GeneratedCertificate.graded_download_url' + db.alter_column('certificates_generatedcertificate', 'graded_download_url', self.gf('django.db.models.fields.CharField')(max_length=128)) + + # Changing field 'GeneratedCertificate.graded_certificate_id' + db.alter_column('certificates_generatedcertificate', 'graded_certificate_id', self.gf('django.db.models.fields.CharField')(max_length=32)) + + def backwards(self, orm): + # Adding model 'RevokedCertificate' + db.create_table('certificates_revokedcertificate', ( + ('grade', self.gf('django.db.models.fields.CharField')(max_length=5, null=True)), + ('certificate_id', self.gf('django.db.models.fields.CharField')(default=None, max_length=32, null=True)), + ('explanation', self.gf('django.db.models.fields.TextField')(blank=True)), + ('graded_download_url', self.gf('django.db.models.fields.CharField')(max_length=128, null=True)), + ('user', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['auth.User'])), + ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), + ('name', self.gf('django.db.models.fields.CharField')(max_length=255, blank=True)), + ('enabled', self.gf('django.db.models.fields.BooleanField')(default=False)), + ('download_url', self.gf('django.db.models.fields.CharField')(max_length=128, null=True)), + ('graded_certificate_id', self.gf('django.db.models.fields.CharField')(default=None, max_length=32, null=True)), + )) + db.send_create_signal('certificates', ['RevokedCertificate']) + + # Adding field 'GeneratedCertificate.name' + db.add_column('certificates_generatedcertificate', 'name', + self.gf('django.db.models.fields.CharField')(default='', max_length=255, blank=True), + keep_default=False) + + # Deleting field 'GeneratedCertificate.course_id' + db.delete_column('certificates_generatedcertificate', 'course_id') + + # Deleting field 'GeneratedCertificate.key' + db.delete_column('certificates_generatedcertificate', 'key') + + + # Changing field 'GeneratedCertificate.grade' + db.alter_column('certificates_generatedcertificate', 'grade', self.gf('django.db.models.fields.CharField')(max_length=5, null=True)) + + # Changing field 'GeneratedCertificate.certificate_id' + db.alter_column('certificates_generatedcertificate', 'certificate_id', self.gf('django.db.models.fields.CharField')(max_length=32, null=True)) + + # Changing field 'GeneratedCertificate.download_url' + db.alter_column('certificates_generatedcertificate', 'download_url', self.gf('django.db.models.fields.CharField')(max_length=128, null=True)) + + # Changing field 'GeneratedCertificate.graded_download_url' + db.alter_column('certificates_generatedcertificate', 'graded_download_url', self.gf('django.db.models.fields.CharField')(max_length=128, null=True)) + + # Changing field 'GeneratedCertificate.graded_certificate_id' + db.alter_column('certificates_generatedcertificate', 'graded_certificate_id', self.gf('django.db.models.fields.CharField')(max_length=32, null=True)) + + models = { + 'auth.group': { + 'Meta': {'object_name': 'Group'}, + 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), + 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), + 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) + }, + 'auth.permission': { + 'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'}, + 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), + 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}), + 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), + 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) + }, + 'auth.user': { + 'Meta': {'object_name': 'User'}, + 'about': ('django.db.models.fields.TextField', [], {'blank': 'True'}), + 'avatar_type': ('django.db.models.fields.CharField', [], {'default': "'n'", 'max_length': '1'}), + 'bronze': ('django.db.models.fields.SmallIntegerField', [], {'default': '0'}), + 'consecutive_days_visit_count': ('django.db.models.fields.IntegerField', [], {'default': '0'}), + 'country': ('django_countries.fields.CountryField', [], {'max_length': '2', 'blank': 'True'}), + 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), + 'date_of_birth': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}), + 'display_tag_filter_strategy': ('django.db.models.fields.SmallIntegerField', [], {'default': '0'}), + 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), + 'email_isvalid': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), + 'email_key': ('django.db.models.fields.CharField', [], {'max_length': '32', 'null': 'True'}), + 'email_tag_filter_strategy': ('django.db.models.fields.SmallIntegerField', [], {'default': '1'}), + 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), + 'gold': ('django.db.models.fields.SmallIntegerField', [], {'default': '0'}), + 'gravatar': ('django.db.models.fields.CharField', [], {'max_length': '32'}), + 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}), + 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), + 'ignored_tags': ('django.db.models.fields.TextField', [], {'blank': 'True'}), + 'interesting_tags': ('django.db.models.fields.TextField', [], {'blank': 'True'}), + 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), + 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), + 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), + 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), + 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), + 'last_seen': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), + 'location': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}), + 'new_response_count': ('django.db.models.fields.IntegerField', [], {'default': '0'}), + 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), + 'questions_per_page': ('django.db.models.fields.SmallIntegerField', [], {'default': '10'}), + 'real_name': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}), + 'reputation': ('django.db.models.fields.PositiveIntegerField', [], {'default': '1'}), + 'seen_response_count': ('django.db.models.fields.IntegerField', [], {'default': '0'}), + 'show_country': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), + 'silver': ('django.db.models.fields.SmallIntegerField', [], {'default': '0'}), + 'status': ('django.db.models.fields.CharField', [], {'default': "'w'", 'max_length': '2'}), + 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), + 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}), + 'website': ('django.db.models.fields.URLField', [], {'max_length': '200', 'blank': 'True'}) + }, + 'certificates.generatedcertificate': { + 'Meta': {'object_name': 'GeneratedCertificate'}, + 'certificate_id': ('django.db.models.fields.CharField', [], {'default': 'False', 'max_length': '32'}), + 'course_id': ('django.db.models.fields.CharField', [], {'default': 'False', 'max_length': '255'}), + 'download_url': ('django.db.models.fields.CharField', [], {'default': 'False', 'max_length': '128'}), + 'enabled': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), + 'grade': ('django.db.models.fields.CharField', [], {'default': 'False', 'max_length': '5'}), + 'graded_certificate_id': ('django.db.models.fields.CharField', [], {'default': 'False', 'max_length': '32'}), + 'graded_download_url': ('django.db.models.fields.CharField', [], {'default': 'False', 'max_length': '128'}), + 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), + 'key': ('django.db.models.fields.CharField', [], {'default': 'False', 'max_length': '32'}), + 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}) + }, + 'contenttypes.contenttype': { + 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, + 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), + 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), + 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), + 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) + } + } + + complete_apps = ['certificates'] \ No newline at end of file diff --git a/lms/djangoapps/certificates/migrations/0009_auto__del_field_generatedcertificate_graded_download_url__del_field_ge.py b/lms/djangoapps/certificates/migrations/0009_auto__del_field_generatedcertificate_graded_download_url__del_field_ge.py new file mode 100644 index 0000000000..40637452cc --- /dev/null +++ b/lms/djangoapps/certificates/migrations/0009_auto__del_field_generatedcertificate_graded_download_url__del_field_ge.py @@ -0,0 +1,95 @@ +# -*- coding: utf-8 -*- +import datetime +from south.db import db +from south.v2 import SchemaMigration +from django.db import models + + +class Migration(SchemaMigration): + + def forwards(self, orm): + # Deleting field 'GeneratedCertificate.graded_download_url' + db.delete_column('certificates_generatedcertificate', 'graded_download_url') + + # Deleting field 'GeneratedCertificate.graded_certificate_id' + db.delete_column('certificates_generatedcertificate', 'graded_certificate_id') + + # Adding field 'GeneratedCertificate.distinction' + db.add_column('certificates_generatedcertificate', 'distinction', + self.gf('django.db.models.fields.BooleanField')(default=False), + keep_default=False) + + # Adding unique constraint on 'GeneratedCertificate', fields ['course_id', 'user'] + db.create_unique('certificates_generatedcertificate', ['course_id', 'user_id']) + + + def backwards(self, orm): + # Removing unique constraint on 'GeneratedCertificate', fields ['course_id', 'user'] + db.delete_unique('certificates_generatedcertificate', ['course_id', 'user_id']) + + # Adding field 'GeneratedCertificate.graded_download_url' + db.add_column('certificates_generatedcertificate', 'graded_download_url', + self.gf('django.db.models.fields.CharField')(default=False, max_length=128), + keep_default=False) + + # Adding field 'GeneratedCertificate.graded_certificate_id' + db.add_column('certificates_generatedcertificate', 'graded_certificate_id', + self.gf('django.db.models.fields.CharField')(default=False, max_length=32), + keep_default=False) + + # Deleting field 'GeneratedCertificate.distinction' + db.delete_column('certificates_generatedcertificate', 'distinction') + + + models = { + 'auth.group': { + 'Meta': {'object_name': 'Group'}, + 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), + 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), + 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) + }, + 'auth.permission': { + 'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'}, + 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), + 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}), + 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), + 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) + }, + 'auth.user': { + 'Meta': {'object_name': 'User'}, + 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), + 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), + 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), + 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}), + 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), + 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), + 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), + 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), + 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), + 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), + 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), + 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), + 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) + }, + 'certificates.generatedcertificate': { + 'Meta': {'unique_together': "(('user', 'course_id'),)", 'object_name': 'GeneratedCertificate'}, + 'certificate_id': ('django.db.models.fields.CharField', [], {'default': 'False', 'max_length': '32'}), + 'course_id': ('django.db.models.fields.CharField', [], {'default': 'False', 'max_length': '255'}), + 'distinction': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), + 'download_url': ('django.db.models.fields.CharField', [], {'default': 'False', 'max_length': '128'}), + 'enabled': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), + 'grade': ('django.db.models.fields.CharField', [], {'default': 'False', 'max_length': '5'}), + 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), + 'key': ('django.db.models.fields.CharField', [], {'default': 'False', 'max_length': '32'}), + 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}) + }, + 'contenttypes.contenttype': { + 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, + 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), + 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), + 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), + 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) + } + } + + complete_apps = ['certificates'] \ No newline at end of file diff --git a/lms/djangoapps/certificates/migrations/0010_auto__del_field_generatedcertificate_enabled__add_field_generatedcerti.py b/lms/djangoapps/certificates/migrations/0010_auto__del_field_generatedcertificate_enabled__add_field_generatedcerti.py new file mode 100644 index 0000000000..5970c96f6b --- /dev/null +++ b/lms/djangoapps/certificates/migrations/0010_auto__del_field_generatedcertificate_enabled__add_field_generatedcerti.py @@ -0,0 +1,81 @@ +# -*- coding: utf-8 -*- +import datetime +from south.db import db +from south.v2 import SchemaMigration +from django.db import models + + +class Migration(SchemaMigration): + + def forwards(self, orm): + # Deleting field 'GeneratedCertificate.enabled' + db.delete_column('certificates_generatedcertificate', 'enabled') + + # Adding field 'GeneratedCertificate.status' + db.add_column('certificates_generatedcertificate', 'status', + self.gf('django.db.models.fields.CharField')(default='unavailable', max_length=32), + keep_default=False) + + + def backwards(self, orm): + # Adding field 'GeneratedCertificate.enabled' + db.add_column('certificates_generatedcertificate', 'enabled', + self.gf('django.db.models.fields.BooleanField')(default=False), + keep_default=False) + + # Deleting field 'GeneratedCertificate.status' + db.delete_column('certificates_generatedcertificate', 'status') + + + models = { + 'auth.group': { + 'Meta': {'object_name': 'Group'}, + 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), + 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), + 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) + }, + 'auth.permission': { + 'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'}, + 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), + 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}), + 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), + 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) + }, + 'auth.user': { + 'Meta': {'object_name': 'User'}, + 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), + 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), + 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), + 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}), + 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), + 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), + 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), + 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), + 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), + 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), + 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), + 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), + 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) + }, + 'certificates.generatedcertificate': { + 'Meta': {'unique_together': "(('user', 'course_id'),)", 'object_name': 'GeneratedCertificate'}, + 'certificate_id': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '32', 'blank': 'True'}), + 'course_id': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '255', 'blank': 'True'}), + 'distinction': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), + 'download_url': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '128', 'blank': 'True'}), + 'grade': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '5', 'blank': 'True'}), + 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), + 'key': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '32', 'blank': 'True'}), + 'status': ('django.db.models.fields.CharField', [], {'default': "'unavailable'", 'max_length': '32'}), + 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}) + }, + 'contenttypes.contenttype': { + 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, + 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), + 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), + 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), + 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) + } + } + + complete_apps = ['certificates'] \ No newline at end of file diff --git a/lms/djangoapps/certificates/migrations/0011_auto__del_field_generatedcertificate_certificate_id__add_field_generat.py b/lms/djangoapps/certificates/migrations/0011_auto__del_field_generatedcertificate_certificate_id__add_field_generat.py new file mode 100644 index 0000000000..36d6e5d4f3 --- /dev/null +++ b/lms/djangoapps/certificates/migrations/0011_auto__del_field_generatedcertificate_certificate_id__add_field_generat.py @@ -0,0 +1,90 @@ +# -*- coding: utf-8 -*- +import datetime +from south.db import db +from south.v2 import SchemaMigration +from django.db import models + + +class Migration(SchemaMigration): + + def forwards(self, orm): + # Deleting field 'GeneratedCertificate.certificate_id' + db.delete_column('certificates_generatedcertificate', 'certificate_id') + + # Adding field 'GeneratedCertificate.verify_uuid' + db.add_column('certificates_generatedcertificate', 'verify_uuid', + self.gf('django.db.models.fields.CharField')(default='', max_length=32, blank=True), + keep_default=False) + + # Adding field 'GeneratedCertificate.download_uuid' + db.add_column('certificates_generatedcertificate', 'download_uuid', + self.gf('django.db.models.fields.CharField')(default='', max_length=32, blank=True), + keep_default=False) + + + def backwards(self, orm): + # Adding field 'GeneratedCertificate.certificate_id' + db.add_column('certificates_generatedcertificate', 'certificate_id', + self.gf('django.db.models.fields.CharField')(default='', max_length=32, blank=True), + keep_default=False) + + # Deleting field 'GeneratedCertificate.verify_uuid' + db.delete_column('certificates_generatedcertificate', 'verify_uuid') + + # Deleting field 'GeneratedCertificate.download_uuid' + db.delete_column('certificates_generatedcertificate', 'download_uuid') + + + models = { + 'auth.group': { + 'Meta': {'object_name': 'Group'}, + 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), + 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), + 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) + }, + 'auth.permission': { + 'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'}, + 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), + 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}), + 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), + 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) + }, + 'auth.user': { + 'Meta': {'object_name': 'User'}, + 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), + 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), + 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), + 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}), + 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), + 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), + 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), + 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), + 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), + 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), + 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), + 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), + 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) + }, + 'certificates.generatedcertificate': { + 'Meta': {'unique_together': "(('user', 'course_id'),)", 'object_name': 'GeneratedCertificate'}, + 'course_id': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '255', 'blank': 'True'}), + 'distinction': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), + 'download_url': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '128', 'blank': 'True'}), + 'download_uuid': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '32', 'blank': 'True'}), + 'grade': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '5', 'blank': 'True'}), + 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), + 'key': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '32', 'blank': 'True'}), + 'status': ('django.db.models.fields.CharField', [], {'default': "'unavailable'", 'max_length': '32'}), + 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}), + 'verify_uuid': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '32', 'blank': 'True'}) + }, + 'contenttypes.contenttype': { + 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, + 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), + 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), + 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), + 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) + } + } + + complete_apps = ['certificates'] \ No newline at end of file diff --git a/lms/djangoapps/certificates/migrations/0012_auto__add_field_generatedcertificate_name__add_field_generatedcertific.py b/lms/djangoapps/certificates/migrations/0012_auto__add_field_generatedcertificate_name__add_field_generatedcertific.py new file mode 100644 index 0000000000..4195860ca5 --- /dev/null +++ b/lms/djangoapps/certificates/migrations/0012_auto__add_field_generatedcertificate_name__add_field_generatedcertific.py @@ -0,0 +1,93 @@ +# -*- coding: utf-8 -*- +import datetime +from south.db import db +from south.v2 import SchemaMigration +from django.db import models + + +class Migration(SchemaMigration): + + def forwards(self, orm): + # Adding field 'GeneratedCertificate.name' + db.add_column('certificates_generatedcertificate', 'name', + self.gf('django.db.models.fields.CharField')(default='', max_length=255, blank=True), + keep_default=False) + + # Adding field 'GeneratedCertificate.created_date' + db.add_column('certificates_generatedcertificate', 'created_date', + self.gf('django.db.models.fields.DateTimeField')(default=datetime.datetime.now, auto_now_add=True, blank=True), + keep_default=False) + + # Adding field 'GeneratedCertificate.modified_date' + db.add_column('certificates_generatedcertificate', 'modified_date', + self.gf('django.db.models.fields.DateTimeField')(default=datetime.datetime.now, auto_now=True, blank=True), + keep_default=False) + + + def backwards(self, orm): + # Deleting field 'GeneratedCertificate.name' + db.delete_column('certificates_generatedcertificate', 'name') + + # Deleting field 'GeneratedCertificate.created_date' + db.delete_column('certificates_generatedcertificate', 'created_date') + + # Deleting field 'GeneratedCertificate.modified_date' + db.delete_column('certificates_generatedcertificate', 'modified_date') + + + models = { + 'auth.group': { + 'Meta': {'object_name': 'Group'}, + 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), + 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), + 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) + }, + 'auth.permission': { + 'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'}, + 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), + 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}), + 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), + 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) + }, + 'auth.user': { + 'Meta': {'object_name': 'User'}, + 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), + 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), + 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), + 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}), + 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), + 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), + 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), + 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), + 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), + 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), + 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), + 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), + 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) + }, + 'certificates.generatedcertificate': { + 'Meta': {'unique_together': "(('user', 'course_id'),)", 'object_name': 'GeneratedCertificate'}, + 'course_id': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '255', 'blank': 'True'}), + 'created_date': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'auto_now_add': 'True', 'blank': 'True'}), + 'distinction': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), + 'download_url': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '128', 'blank': 'True'}), + 'download_uuid': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '32', 'blank': 'True'}), + 'grade': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '5', 'blank': 'True'}), + 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), + 'key': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '32', 'blank': 'True'}), + 'modified_date': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'auto_now': 'True', 'blank': 'True'}), + 'name': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}), + 'status': ('django.db.models.fields.CharField', [], {'default': "'unavailable'", 'max_length': '32'}), + 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}), + 'verify_uuid': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '32', 'blank': 'True'}) + }, + 'contenttypes.contenttype': { + 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, + 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), + 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), + 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), + 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) + } + } + + complete_apps = ['certificates'] \ No newline at end of file diff --git a/lms/djangoapps/certificates/migrations/0013_auto__add_field_generatedcertificate_error_reason.py b/lms/djangoapps/certificates/migrations/0013_auto__add_field_generatedcertificate_error_reason.py new file mode 100644 index 0000000000..7f31e6ebd9 --- /dev/null +++ b/lms/djangoapps/certificates/migrations/0013_auto__add_field_generatedcertificate_error_reason.py @@ -0,0 +1,78 @@ +# -*- coding: utf-8 -*- +import datetime +from south.db import db +from south.v2 import SchemaMigration +from django.db import models + + +class Migration(SchemaMigration): + + def forwards(self, orm): + # Adding field 'GeneratedCertificate.error_reason' + db.add_column('certificates_generatedcertificate', 'error_reason', + self.gf('django.db.models.fields.CharField')(default='', max_length=512, blank=True), + keep_default=False) + + + def backwards(self, orm): + # Deleting field 'GeneratedCertificate.error_reason' + db.delete_column('certificates_generatedcertificate', 'error_reason') + + + models = { + 'auth.group': { + 'Meta': {'object_name': 'Group'}, + 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), + 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), + 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) + }, + 'auth.permission': { + 'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'}, + 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), + 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}), + 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), + 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) + }, + 'auth.user': { + 'Meta': {'object_name': 'User'}, + 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), + 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), + 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), + 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}), + 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), + 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), + 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), + 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), + 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), + 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), + 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), + 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), + 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) + }, + 'certificates.generatedcertificate': { + 'Meta': {'unique_together': "(('user', 'course_id'),)", 'object_name': 'GeneratedCertificate'}, + 'course_id': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '255', 'blank': 'True'}), + 'created_date': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'auto_now_add': 'True', 'blank': 'True'}), + 'distinction': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), + 'download_url': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '128', 'blank': 'True'}), + 'download_uuid': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '32', 'blank': 'True'}), + 'error_reason': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '512', 'blank': 'True'}), + 'grade': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '5', 'blank': 'True'}), + 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), + 'key': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '32', 'blank': 'True'}), + 'modified_date': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'auto_now': 'True', 'blank': 'True'}), + 'name': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}), + 'status': ('django.db.models.fields.CharField', [], {'default': "'unavailable'", 'max_length': '32'}), + 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}), + 'verify_uuid': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '32', 'blank': 'True'}) + }, + 'contenttypes.contenttype': { + 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, + 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), + 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), + 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), + 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) + } + } + + complete_apps = ['certificates'] \ No newline at end of file diff --git a/lms/djangoapps/certificates/models.py b/lms/djangoapps/certificates/models.py index 5815db64ca..2d6f384443 100644 --- a/lms/djangoapps/certificates/models.py +++ b/lms/djangoapps/certificates/models.py @@ -1,144 +1,108 @@ -from django.conf import settings as settings - from django.contrib.auth.models import User from django.db import models +from datetime import datetime - -''' +""" Certificates are created for a student and an offering of a course. When a certificate is generated, a unique ID is generated so that the certificate can be verified later. The ID is a UUID4, so that -it can't be easily guessed and so that it is unique. Even though -we save these generated certificates (for later verification), we -also record the UUID so that if we regenerate the certificate it -will have the same UUID. +it can't be easily guessed and so that it is unique. -If certificates are being generated on the fly, a GeneratedCertificate -should be created with the user, certificate_id, and enabled set -when a student requests a certificate. When the certificate has been -generated, the download_url should be set. +Certificates are generated in batches by a cron job, when a +certificate is available for download the GeneratedCertificate +table is updated with information that will be displayed +on the course overview page. -Certificates can also be pre-generated. In this case, the user, -certificate_id, and download_url are all set before the user does -anything. When the user requests the certificate, only enabled -needs to be set to true. -''' +State diagram: + +[deleted,error,unavailable] [error,downloadable] + + + + + | | | + | | | + add_cert regen_cert del_cert + | | | + v v v + [generating] [regenerating] [deleting] + + + + + | | | + certificate certificate certificate + created removed,created deleted + +----------------+-------------+------->[error] + | | | + | | | + v v v + [downloadable] [downloadable] [deleted] + +""" + + +class CertificateStatuses(object): + unavailable = 'unavailable' + generating = 'generating' + regenerating = 'regenerating' + deleting = 'deleting' + deleted = 'deleted' + downloadable = 'downloadable' + notpassing = 'notpassing' + error = 'error' class GeneratedCertificate(models.Model): - user = models.ForeignKey(User, db_index=True) - # This is the name at the time of request + user = models.ForeignKey(User) + course_id = models.CharField(max_length=255, blank=True, default='') + verify_uuid = models.CharField(max_length=32, blank=True, default='') + download_uuid = models.CharField(max_length=32, blank=True, default='') + download_url = models.CharField(max_length=128, blank=True, default='') + grade = models.CharField(max_length=5, blank=True, default='') + key = models.CharField(max_length=32, blank=True, default='') + distinction = models.BooleanField(default=False) + status = models.CharField(max_length=32, default='unavailable') name = models.CharField(blank=True, max_length=255) + created_date = models.DateTimeField( + auto_now_add=True, default=datetime.now) + modified_date = models.DateTimeField( + auto_now=True, default=datetime.now) + error_reason = models.CharField(max_length=512, blank=True, default='') - certificate_id = models.CharField(max_length=32, null=True, default=None) - graded_certificate_id = models.CharField(max_length=32, null=True, default=None) - - download_url = models.CharField(max_length=128, null=True) - graded_download_url = models.CharField(max_length=128, null=True) - - grade = models.CharField(max_length=5, null=True) - - # enabled should only be true if the student has earned a grade in the course - # The student must have a grade and request a certificate for enabled to be True - enabled = models.BooleanField(default=False) + class Meta: + unique_together = (('user', 'course_id'),) -class RevokedCertificate(models.Model): - """ - This model is for when a GeneratedCertificate must be regenerated. This model - contains all the same fields, to store a record of what the GeneratedCertificate - was before it was revoked (at which time all of it's information can change when - it is regenerated). - - GeneratedCertificate may be deleted once they are revoked, and then created again. - For this reason, the only link between a GeneratedCertificate and RevokedCertificate - is that they share the same user. - """ - ####-------------------New Fields--------------------#### - explanation = models.TextField(blank=True) - - ####---------Fields from GeneratedCertificate---------#### - user = models.ForeignKey(User, db_index=True) - # This is the name at the time of request - name = models.CharField(blank=True, max_length=255) - - certificate_id = models.CharField(max_length=32, null=True, default=None) - graded_certificate_id = models.CharField(max_length=32, null=True, default=None) - - download_url = models.CharField(max_length=128, null=True) - graded_download_url = models.CharField(max_length=128, null=True) - - grade = models.CharField(max_length=5, null=True) - - enabled = models.BooleanField(default=False) - - -def revoke_certificate(certificate, explanation): - """ - This method takes a GeneratedCertificate. It records its information from the certificate - into a RevokedCertificate, and then marks the certificate as needing regenerating. - When the new certificiate is regenerated it will have new IDs and download URLS. - - Once this method has been called, it is safe to delete the certificate, or modify the - certificate's name or grade until it has been generated again. - """ - revoked = RevokedCertificate(user=certificate.user, - name=certificate.name, - certificate_id=certificate.certificate_id, - graded_certificate_id=certificate.graded_certificate_id, - download_url=certificate.download_url, - graded_download_url=certificate.graded_download_url, - grade=certificate.grade, - enabled=certificate.enabled) - - revoked.explanation = explanation - - certificate.certificate_id = None - certificate.graded_certificate_id = None - certificate.download_url = None - certificate.graded_download_url = None - - certificate.save() - revoked.save() - - -def certificate_state_for_student(student, grade): +def certificate_status_for_student(student, course_id): ''' - This returns a dictionary with a key for state, and other information. The state is one of the - following: + This returns a dictionary with a key for status, and other information. + The status is one of the following: - unavailable - A student is not eligible for a certificate. - requestable - A student is eligible to request a certificate - generating - A student has requested a certificate, but it is not generated yet. - downloadable - The certificate has been requested and is available for download. + unavailable - A student is not eligible for a certificate. + generating - A request has been made to generate a certificate, + but it has not been generated yet. + regenerating - A request has been made to regenerate a certificate, + but it has not been generated yet. + deleting - A request has been made to delete a certificate. - If the state is "downloadable", the dictionary also contains "download_url" and "graded_download_url". + deleted - The certificate has been deleted. + downloadable - The certificate is available for download. + notpassing - The student was graded but is not passing + If the status is "downloadable", the dictionary also contains + "download_url". + + If the student has been graded, the dictionary also contains their + grade for the course. ''' - if grade: - #TODO: Remove the following after debugging - if settings.DEBUG_SURVEY: - return {'state': 'requestable'} + try: + generated_certificate = GeneratedCertificate.objects.get( + user=student, course_id=course_id) + d = {'status': generated_certificate.status} + if generated_certificate.grade: + d['grade'] = generated_certificate.grade + if generated_certificate.status == CertificateStatuses.downloadable: + d['download_url'] = generated_certificate.download_url - try: - generated_certificate = GeneratedCertificate.objects.get(user=student) - if generated_certificate.enabled: - if generated_certificate.download_url: - return {'state': 'downloadable', - 'download_url': generated_certificate.download_url, - 'graded_download_url': generated_certificate.graded_download_url} - else: - return {'state': 'generating'} - else: - # If enabled=False, it may have been pre-generated but not yet requested - # Our output will be the same as if the GeneratedCertificate did not exist - pass - except GeneratedCertificate.DoesNotExist: - pass - return {'state': 'requestable'} - else: - # No grade, no certificate. No exceptions - return {'state': 'unavailable'} + return d + except GeneratedCertificate.DoesNotExist: + pass + return {'status': CertificateStatuses.unavailable} diff --git a/lms/djangoapps/certificates/queue.py b/lms/djangoapps/certificates/queue.py new file mode 100644 index 0000000000..b3a9ddc9c7 --- /dev/null +++ b/lms/djangoapps/certificates/queue.py @@ -0,0 +1,262 @@ +from certificates.models import GeneratedCertificate +from certificates.models import certificate_status_for_student +from certificates.models import CertificateStatuses as status + +from courseware import grades, courses +from django.test.client import RequestFactory +from capa.xqueue_interface import XQueueInterface +from capa.xqueue_interface import make_xheader, make_hashkey +from django.conf import settings +from requests.auth import HTTPBasicAuth +from student.models import UserProfile + +import json +import random +import logging + + +logger = logging.getLogger(__name__) + + +class XQueueCertInterface(object): + """ + XQueueCertificateInterface provides an + interface to the xqueue server for + managing student certificates. + + Instantiating an object will create a new + connection to the queue server. + + See models.py for valid state transitions, + summary of methods: + + add_cert: Add a new certificate. Puts a single + request on the queue for the student/course. + Once the certificate is generated a post + will be made to the update_certificate + view which will save the certificate + download URL. + + regen_cert: Regenerate an existing certificate. + For a user that already has a certificate + this will delete the existing one and + generate a new cert. + + + del_cert: Delete an existing certificate + For a user that already has a certificate + this will delete his cert. + + """ + + def __init__(self, request=None): + + # Get basic auth (username/password) for + # xqueue connection if it's in the settings + + if settings.XQUEUE_INTERFACE.get('basic_auth') is not None: + requests_auth = HTTPBasicAuth( + *settings.XQUEUE_INTERFACE['basic_auth']) + else: + requests_auth = None + + if request is None: + factory = RequestFactory() + self.request = factory.get('/') + else: + self.request = request + + self.xqueue_interface = XQueueInterface( + settings.XQUEUE_INTERFACE['url'], + settings.XQUEUE_INTERFACE['django_auth'], + requests_auth, + ) + + def regen_cert(self, student, course_id): + """ + Arguments: + student - User.object + course_id - courseenrollment.course_id (string) + + Removes certificate for a student, will change + the certificate status to 'regenerating'. + + Certificate must be in the 'error' or 'downloadable' state + + If the student has a passing grade a certificate + request will be put on the queue + + If the student is not passing his state will change + to status.notpassing + + otherwise it will return the current state + + """ + + VALID_STATUSES = [status.error, status.downloadable] + + cert_status = certificate_status_for_student( + student, course_id)['status'] + + if cert_status in VALID_STATUSES: + # grade the student + course = courses.get_course_by_id(course_id) + grade = grades.grade(student, self.request, course) + + profile = UserProfile.objects.get(user=student) + try: + cert = GeneratedCertificate.objects.get( + user=student, course_id=course_id) + except GeneratedCertificate.DoesNotExist: + logger.critical("Attempting to regenerate a certificate" + "for a user that doesn't have one") + raise + + if grade['grade'] is not None: + + cert.status = status.regenerating + cert.name = profile.name + + contents = { + 'action': 'regen', + 'delete_verify_uuid': cert.verify_uuid, + 'delete_download_uuid': cert.download_uuid, + 'username': cert.user.username, + 'course_id': cert.course_id, + 'name': profile.name, + } + + key = cert.key + self._send_to_xqueue(contents, key) + cert.save() + + else: + cert.status = status.notpassing + cert.name = profile.name + cert.save() + + return cert_status + + def del_cert(self, student, course_id): + + """ + Arguments: + student - User.object + course_id - courseenrollment.course_id (string) + + Removes certificate for a student, will change + the certificate status to 'deleting'. + + Certificate must be in the 'error' or 'downloadable' state + otherwise it will return the current state + + """ + + VALID_STATUSES = [status.error, status.downloadable] + + cert_status = certificate_status_for_student( + student, course_id)['status'] + + if cert_status in VALID_STATUSES: + + try: + cert = GeneratedCertificate.objects.get( + user=student, course_id=course_id) + except GeneratedCertificate.DoesNotExist: + logger.warning("Attempting to delete a certificate" + "for a user that doesn't have one") + raise + + cert.status = status.deleting + + contents = { + 'action': 'delete', + 'delete_verify_uuid': cert.verify_uuid, + 'delete_download_uuid': cert.download_uuid, + 'username': cert.user.username, + } + + key = cert.key + self._send_to_xqueue(contents, key) + cert.save() + return cert_status + + def add_cert(self, student, course_id): + """ + + Arguments: + student - User.object + course_id - courseenrollment.course_id (string) + + Request a new certificate for a student. + Will change the certificate status to 'deleting'. + + Certificate must be in the 'unavailable', 'error', + or 'deleted' state. + + If a student has a passing grade a request will made + for a new cert + + If a student does not have a passing grade the status + will change to status.notpassing + + Returns the student's status + + """ + + VALID_STATUSES = [status.unavailable, status.deleted, status.error, + status.notpassing] + + cert_status = certificate_status_for_student( + student, course_id)['status'] + + if cert_status in VALID_STATUSES: + # grade the student + course = courses.get_course_by_id(course_id) + grade = grades.grade(student, self.request, course) + profile = UserProfile.objects.get(user=student) + cert, created = GeneratedCertificate.objects.get_or_create( + user=student, course_id=course_id) + + if grade['grade'] is not None: + cert_status = status.generating + key = make_hashkey(random.random()) + + cert.status = cert_status + cert.grade = grade['percent'] + cert.user = student + cert.course_id = course_id + cert.key = key + cert.name = profile.name + + contents = { + 'action': 'create', + 'username': student.username, + 'course_id': course_id, + 'name': profile.name, + } + + self._send_to_xqueue(contents, key) + cert.save() + else: + cert_status = status.notpassing + + cert.status = cert_status + cert.user = student + cert.course_id = course_id + cert.name = profile.name + cert.save() + + return cert_status + + def _send_to_xqueue(self, contents, key): + + xheader = make_xheader( + 'https://{0}/update_certificate?{1}'.format( + settings.SITE_NAME, key), key, settings.CERT_QUEUE) + + (error, msg) = self.xqueue_interface.send_to_queue( + header=xheader, body=json.dumps(contents)) + if error: + logger.critical('Unable to add a request to the queue') + raise Exception('Unable to send queue message') diff --git a/lms/djangoapps/certificates/views.py b/lms/djangoapps/certificates/views.py index 472215ab5c..ae15245588 100644 --- a/lms/djangoapps/certificates/views.py +++ b/lms/djangoapps/certificates/views.py @@ -1,146 +1,77 @@ -import json import logging -import uuid +from certificates.models import GeneratedCertificate +from certificates.models import CertificateStatuses as status +from django.views.decorators.csrf import csrf_exempt +from django.http import HttpResponse +import json -from django.conf import settings -from django.contrib.auth.decorators import login_required -from django.core.mail import send_mail -from django.http import Http404, HttpResponse -from django.shortcuts import redirect - -import courseware.grades as grades -from certificates.models import GeneratedCertificate, certificate_state_for_student, revoke_certificate -from mitxmako.shortcuts import render_to_response, render_to_string -from student.models import UserProfile -#TODO: Finish migrating these changes from stable -# from student.survey_questions import exit_survey_list_for_student -# from student.views import student_took_survey, record_exit_survey - -log = logging.getLogger("mitx.certificates") +logger = logging.getLogger(__name__) -@login_required -def certificate_request(request): - ''' Attempt to send a certificate. ''' - if not settings.END_COURSE_ENABLED: - raise Http404 +@csrf_exempt +def update_certificate(request): + """ + Will update GeneratedCertificate for a new certificate or + modify an existing certificate entry. + + See models.py for a state diagram of certificate states + + This view should only ever be accessed by the xqueue server + """ if request.method == "POST": - honor_code_verify = request.POST.get('cert_request_honor_code_verify', 'false') - name_verify = request.POST.get('cert_request_name_verify', 'false') - id_verify = request.POST.get('cert_request_id_verify', 'false') - error = '' - def return_error(error): - return HttpResponse(json.dumps({'success': False, - 'error': error})) - - if honor_code_verify != 'true': - error += 'Please verify that you have followed the honor code to receive a certificate. ' - - if name_verify != 'true': - error += 'Please verify that your name is correct to receive a certificate. ' - - if id_verify != 'true': - error += 'Please certify that you understand the unique ID on the certificate. ' - - if len(error) > 0: - return return_error(error) - - survey_response = record_exit_survey(request, internal_request=True) - if not survey_response['success']: - return return_error(survey_response['error']) - - grade = None - student_gradesheet = grades.grade(request.user, request, course) - grade = student_gradesheet['grade'] - - if not grade: - return return_error('You have not earned a grade in this course. ') - - generate_certificate(request.user, grade) - - return HttpResponse(json.dumps({'success': True})) - - else: - #This is not a POST, we should render the page with the form - - student_gradesheet = grades.grade(request.user, request, course) - certificate_state = certificate_state_for_student(request.user, grade_sheet['grade']) - - if certificate_state['state'] != "requestable": - return redirect("/profile") - - user_info = UserProfile.objects.get(user=request.user) - - took_survey = student_took_survey(user_info) - if settings.DEBUG_SURVEY: - took_survey = False - survey_list = [] - if not took_survey: - survey_list = exit_survey_list_for_student(request.user) - - context = {'certificate_state': certificate_state, - 'took_survey': took_survey, - 'survey_list': survey_list, - 'name': user_info.name} - - return render_to_response('cert_request.html', context) - - -# This method should only be called if the user has a grade and has requested a certificate -def generate_certificate(user, grade): - # Make sure to see the comments in models.GeneratedCertificate to read about the valid - # states for a GeneratedCertificate object - if grade and user.is_active: - generated_certificate = None + xqueue_body = json.loads(request.POST.get('xqueue_body')) + xqueue_header = json.loads(request.POST.get('xqueue_header')) try: - generated_certificate = GeneratedCertificate.objects.get(user=user) + cert = GeneratedCertificate.objects.get( + user__username=xqueue_body['username'], + course_id=xqueue_body['course_id'], + key=xqueue_header['lms_key']) + except GeneratedCertificate.DoesNotExist: - generated_certificate = GeneratedCertificate(user=user) + logger.critical('Unable to lookup certificate\n' + 'xqueue_body: {0}\n' + 'xqueue_header: {1}'.format( + xqueue_body, xqueue_header)) - generated_certificate.enabled = True - if generated_certificate.graded_download_url and (generated_certificate.grade != grade): - log.critical(u"A graded certificate has been pre-generated with the grade " - "of {gen_grade} but requested by user id {userid} with grade " - "{req_grade}! The download URLs were {graded_dl_url} and " - "{ungraded_dl_url}".format( - gen_grade=generated_certificate.grade, - req_grade=grade, - graded_dl_url=generated_certificate.graded_download_url, - ungraded_dl_url=generated_certificate.download_url, - userid=user.id)) - revoke_certificate(generated_certificate, "The grade on this certificate may be inaccurate.") + return HttpResponse(json.dumps({ + 'return_code': 1, + 'content': 'unable to lookup key'}), + mimetype='application/json') - user_name = UserProfile.objects.get(user=user).name - if generated_certificate.download_url and (generated_certificate.name != user_name): - log.critical(u"A Certificate has been pre-generated with the name of " - "{gen_name} but current name is {user_name} (user id is " - "{userid})! The download URLs were {graded_dl_url} and " - "{ungraded_dl_url}".format( - gen_name=generated_certificate.name.encode('utf-8'), - user_name=user_name.encode('utf-8'), - graded_dl_url=generated_certificate.graded_download_url, - ungraded_dl_url=generated_certificate.download_url, - userid=user.id)) - revoke_certificate(generated_certificate, "The name on this certificate may be inaccurate.") + if 'error' in xqueue_body: + cert.status = status.error + if 'error_reason' in xqueue_body: - generated_certificate.grade = grade - generated_certificate.name = user_name - generated_certificate.save() + # Hopefully we will record a meaningful error + # here if something bad happened during the + # certificate generation process + # + # example: + # (aamorm BerkeleyX/CS169.1x/2012_Fall) + # : + # HTTP error (reason=error(32, 'Broken pipe'), filename=None) : + # certificate_agent.py:175 - certificate_id = generated_certificate.certificate_id - log.debug("Generating certificate for " + str(user.username) + " with ID: " + str(certificate_id)) - - # TODO: If the certificate was pre-generated, send the email that it is ready to download - if certificate_state_for_student(user, grade)['state'] == "downloadable": - subject = render_to_string('emails/certificate_ready_subject.txt', {}) - subject = ''.join(subject.splitlines()) - message = render_to_string('emails/certificate_ready.txt', {}) - - res = send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, [user.email, ]) - - else: - log.warning("Asked to generate a certificate for student " + str(user.username) + " but with a grade of " + str(grade) + " and active status " + str(user.is_active)) + cert.error_reason = xqueue_body['error_reason'] + else: + if cert.status in [status.generating, status.regenerating]: + cert.download_uuid = xqueue_body['download_uuid'] + cert.verify_uuid = xqueue_body['verify_uuid'] + cert.download_url = xqueue_body['url'] + cert.status = status.downloadable + elif cert.status in [status.deleting]: + cert.status = status.deleted + else: + logger.critical('Invalid state for cert update: {0}'.format( + cert.status)) + return HttpResponse(json.dumps({ + 'return_code': 1, + 'content': 'invalid cert status'}), + mimetype='application/json') + cert.save() + return HttpResponse(json.dumps({'return_code': 0}), + mimetype='application/json') diff --git a/lms/djangoapps/courseware/models.py b/lms/djangoapps/courseware/models.py index 393cb0918b..ffc7c929de 100644 --- a/lms/djangoapps/courseware/models.py +++ b/lms/djangoapps/courseware/models.py @@ -108,7 +108,6 @@ class StudentModuleCache(object): else: self.cache = [] - @classmethod def cache_for_descriptor_descendents(cls, course_id, user, descriptor, depth=None, descriptor_filter=lambda descriptor: True, @@ -138,7 +137,6 @@ class StudentModuleCache(object): return descriptors - descriptors = get_child_descriptors(descriptor, depth, descriptor_filter) return StudentModuleCache(course_id, user, descriptors, select_for_update) diff --git a/lms/djangoapps/courseware/module_render.py b/lms/djangoapps/courseware/module_render.py index e0b0c3aaec..67927c0ee7 100644 --- a/lms/djangoapps/courseware/module_render.py +++ b/lms/djangoapps/courseware/module_render.py @@ -337,7 +337,7 @@ def xqueue_callback(request, course_id, userid, id, dispatch): ''' # Test xqueue package, which we expect to be: # xpackage = {'xqueue_header': json.dumps({'lms_key':'secretkey',...}), - # 'xqueue_body' : 'Message from grader} + # 'xqueue_body' : 'Message from grader'} get = request.POST.copy() for key in ['xqueue_header', 'xqueue_body']: if not get.has_key(key): @@ -372,7 +372,8 @@ def xqueue_callback(request, course_id, userid, id, dispatch): # We go through the "AJAX" path # So far, the only dispatch from xqueue will be 'score_update' try: - ajax_return = instance.handle_ajax(dispatch, get) # Can ignore the "ajax" return in 'xqueue_callback' + # Can ignore the return value--not used for xqueue_callback + instance.handle_ajax(dispatch, get) except: log.exception("error processing ajax call") raise @@ -386,12 +387,12 @@ def xqueue_callback(request, course_id, userid, id, dispatch): #Bin score into range and increment stats score_bucket=get_score_bucket(instance_module.grade, instance_module.max_grade) - org, course_num, run=course_id.split("/") + org, course_num, run=course_id.split("/") statsd.increment("lms.courseware.question_answered", tags=["org:{0}".format(org), "course:{0}".format(course_num), - "run:{0}".format(run), - "score_bucket:{0}".format(score_bucket), + "run:{0}".format(run), + "score_bucket:{0}".format(score_bucket), "type:xqueue"]) return HttpResponse("") @@ -479,12 +480,12 @@ def modx_dispatch(request, dispatch, location, course_id): #Bin score into range and increment stats score_bucket=get_score_bucket(instance_module.grade, instance_module.max_grade) - org, course_num, run=course_id.split("/") + org, course_num, run=course_id.split("/") statsd.increment("lms.courseware.question_answered", tags=["org:{0}".format(org), "course:{0}".format(course_num), - "run:{0}".format(run), - "score_bucket:{0}".format(score_bucket), + "run:{0}".format(run), + "score_bucket:{0}".format(score_bucket), "type:ajax"]) diff --git a/lms/djangoapps/courseware/views.py b/lms/djangoapps/courseware/views.py index 58bd6924af..d8def76473 100644 --- a/lms/djangoapps/courseware/views.py +++ b/lms/djangoapps/courseware/views.py @@ -217,6 +217,7 @@ def index(request, course_id, chapter=None, section=None, 'init': '', 'content': '', 'staff_access': staff_access, + 'xqa_server': settings.MITX_FEATURES.get('USE_XQA_SERVER','http://xqa:server@content-qa.mitx.mit.edu/xqa') } chapter_descriptor = course.get_child_by_url_name(chapter) diff --git a/lms/djangoapps/django_comment_client/models.py b/lms/djangoapps/django_comment_client/models.py index 605a731517..ff2146afac 100644 --- a/lms/djangoapps/django_comment_client/models.py +++ b/lms/djangoapps/django_comment_client/models.py @@ -2,6 +2,7 @@ from django.db import models from django.contrib.auth.models import User import logging +from courseware.courses import get_course_by_id class Role(models.Model): name = models.CharField(max_length=30, null=False, blank=False) @@ -23,6 +24,12 @@ class Role(models.Model): self.permissions.add(Permission.objects.get_or_create(name=permission)[0]) def has_permission(self, permission): + course = get_course_by_id(self.course_id) + if self.name == "Student" and \ + (permission.startswith('edit') or permission.startswith('update') or permission.startswith('create')) and \ + (not course.forum_posts_allowed): + return False + return self.permissions.filter(name=permission).exists() diff --git a/lms/djangoapps/django_comment_client/tests.py b/lms/djangoapps/django_comment_client/tests.py index 55f18de8ea..2f3126be2c 100644 --- a/lms/djangoapps/django_comment_client/tests.py +++ b/lms/djangoapps/django_comment_client/tests.py @@ -19,7 +19,7 @@ class PermissionsTestCase(TestCase): def setUp(self): - self.course_id = "MITx/6.002x/2012_Fall" + self.course_id = "edX/toy/2012_Fall" self.moderator_role = Role.objects.get_or_create(name="Moderator", course_id=self.course_id)[0] self.student_role = Role.objects.get_or_create(name="Student", course_id=self.course_id)[0] diff --git a/lms/envs/aws.py b/lms/envs/aws.py index 926b30d173..b58bc5602b 100644 --- a/lms/envs/aws.py +++ b/lms/envs/aws.py @@ -22,7 +22,7 @@ DEFAULT_FILE_STORAGE = 'storages.backends.s3boto.S3BotoStorage' # Enable Berkeley forums MITX_FEATURES['ENABLE_DISCUSSION_SERVICE'] = True -# IMPORTANT: With this enabled, the server must always be behind a proxy that +# IMPORTANT: With this enabled, the server must always be behind a proxy that # strips the header HTTP_X_FORWARDED_PROTO from client requests. Otherwise, # a user can fool our server into thinking it was an https connection. # See https://docs.djangoproject.com/en/dev/ref/settings/#secure-proxy-ssl-header @@ -59,6 +59,7 @@ COURSE_LISTINGS = ENV_TOKENS.get('COURSE_LISTINGS', {}) SUBDOMAIN_BRANDING = ENV_TOKENS.get('SUBDOMAIN_BRANDING', {}) COMMENTS_SERVICE_URL = ENV_TOKENS.get("COMMENTS_SERVICE_URL",'') COMMENTS_SERVICE_KEY = ENV_TOKENS.get("COMMENTS_SERVICE_KEY",'') +CERT_QUEUE = ENV_TOKENS.get("CERT_QUEUE", 'test-pull') ############################## SECURE AUTH ITEMS ############################### # Secret things: passwords, access keys, etc. @@ -74,3 +75,6 @@ AWS_STORAGE_BUCKET_NAME = 'edxuploads' DATABASES = AUTH_TOKENS['DATABASES'] XQUEUE_INTERFACE = AUTH_TOKENS['XQUEUE_INTERFACE'] + +PEARSON_TEST_USER = "pearsontest" +PEARSON_TEST_PASSWORD = AUTH_TOKENS.get("PEARSON_TEST_PASSWORD") diff --git a/lms/envs/dev.py b/lms/envs/dev.py index d2445f0f8c..bf72284425 100644 --- a/lms/envs/dev.py +++ b/lms/envs/dev.py @@ -172,3 +172,8 @@ FILE_UPLOAD_HANDLERS = ( ########################### PIPELINE ################################# PIPELINE_SASS_ARGUMENTS = '-r {proj_dir}/static/sass/bourbon/lib/bourbon.rb'.format(proj_dir=PROJECT_ROOT) + +########################## PEARSON TESTING ########################### +MITX_FEATURES['ENABLE_PEARSON_HACK_TEST'] = True +PEARSON_TEST_USER = "pearsontest" +PEARSON_TEST_PASSWORD = "12345" diff --git a/lms/envs/test.py b/lms/envs/test.py index b47cbc43ee..e815efdf4e 100644 --- a/lms/envs/test.py +++ b/lms/envs/test.py @@ -27,18 +27,11 @@ SOUTH_TESTS_MIGRATE = False # To disable migrations and use syncdb instead # Nose Test Runner INSTALLED_APPS += ('django_nose',) -NOSE_ARGS = [] -# Turning off coverage speeds up tests dramatically... until we have better config, -# leave it here for manual fiddling. -_coverage = True -if _coverage: - NOSE_ARGS = ['--cover-erase', '--with-xunit', '--with-xcoverage', '--cover-html', - # '-v', '--pdb', # When really stuck, uncomment to start debugger on error - '--cover-inclusive', '--cover-html-dir', - os.environ.get('NOSE_COVER_HTML_DIR', 'cover_html')] - for app in os.listdir(PROJECT_ROOT / 'djangoapps'): - NOSE_ARGS += ['--cover-package', app] +NOSE_ARGS = [ + '--with-xunit', + # '-v', '--pdb', # When really stuck, uncomment to start debugger on error +] TEST_RUNNER = 'django_nose.NoseTestSuiteRunner' # Local Directories diff --git a/lms/static/images/press/amradiowrks_press_logo_178x138.jpg b/lms/static/images/press/amradiowrks_press_logo_178x138.jpg new file mode 100755 index 0000000000..fb76aefc9c Binary files /dev/null and b/lms/static/images/press/amradiowrks_press_logo_178x138.jpg differ diff --git a/lms/static/images/press/ap_logo_178x138.jpg b/lms/static/images/press/ap_logo_178x138.jpg new file mode 100644 index 0000000000..48f150021e Binary files /dev/null and b/lms/static/images/press/ap_logo_178x138.jpg differ diff --git a/lms/static/images/press/arstechnica_logo_178x138.jpg b/lms/static/images/press/arstechnica_logo_178x138.jpg new file mode 100755 index 0000000000..2e471640ec Binary files /dev/null and b/lms/static/images/press/arstechnica_logo_178x138.jpg differ diff --git a/lms/static/images/press/austin_statesman_logo_178x138.jpg b/lms/static/images/press/austin_statesman_logo_178x138.jpg new file mode 100644 index 0000000000..2e760899cd Binary files /dev/null and b/lms/static/images/press/austin_statesman_logo_178x138.jpg differ diff --git a/lms/static/images/press/busweek_logo_178x138.jpg b/lms/static/images/press/busweek_logo_178x138.jpg new file mode 100644 index 0000000000..5bfd9450c6 Binary files /dev/null and b/lms/static/images/press/busweek_logo_178x138.jpg differ diff --git a/lms/static/images/press/campdenfb_logo_178x138.jpg b/lms/static/images/press/campdenfb_logo_178x138.jpg new file mode 100644 index 0000000000..1d2c047540 Binary files /dev/null and b/lms/static/images/press/campdenfb_logo_178x138.jpg differ diff --git a/lms/static/images/press/campustech_logo_178x138.jpg b/lms/static/images/press/campustech_logo_178x138.jpg new file mode 100644 index 0000000000..9026d08dc2 Binary files /dev/null and b/lms/static/images/press/campustech_logo_178x138.jpg differ diff --git a/lms/static/images/press/center_digeducation_logo_178x138.jpg b/lms/static/images/press/center_digeducation_logo_178x138.jpg new file mode 100644 index 0000000000..8da07ef28f Binary files /dev/null and b/lms/static/images/press/center_digeducation_logo_178x138.jpg differ diff --git a/lms/static/images/press/cnn_logo_178x138.jpg b/lms/static/images/press/cnn_logo_178x138.jpg new file mode 100644 index 0000000000..f747b4dc0a Binary files /dev/null and b/lms/static/images/press/cnn_logo_178x138.jpg differ diff --git a/lms/static/images/press/college_classes_logo_178x138.jpg b/lms/static/images/press/college_classes_logo_178x138.jpg new file mode 100644 index 0000000000..aa216623b2 Binary files /dev/null and b/lms/static/images/press/college_classes_logo_178x138.jpg differ diff --git a/lms/static/images/press/concord_consortium_logo.jpg b/lms/static/images/press/concord_consortium_logo.jpg new file mode 100644 index 0000000000..ef3552fc9c Binary files /dev/null and b/lms/static/images/press/concord_consortium_logo.jpg differ diff --git a/lms/static/images/press/dailycollegian_logo_178x138.jpg b/lms/static/images/press/dailycollegian_logo_178x138.jpg new file mode 100644 index 0000000000..e704c9e9bb Binary files /dev/null and b/lms/static/images/press/dailycollegian_logo_178x138.jpg differ diff --git a/lms/static/images/press/dailynews_india_logo_178x138.jpg b/lms/static/images/press/dailynews_india_logo_178x138.jpg new file mode 100644 index 0000000000..6e2262bf83 Binary files /dev/null and b/lms/static/images/press/dailynews_india_logo_178x138.jpg differ diff --git a/lms/static/images/press/edtechtimes_logo_178x138.jpg b/lms/static/images/press/edtechtimes_logo_178x138.jpg new file mode 100755 index 0000000000..c87355fd7b Binary files /dev/null and b/lms/static/images/press/edtechtimes_logo_178x138.jpg differ diff --git a/lms/static/images/press/eduinvest_logo_178x138.jpg b/lms/static/images/press/eduinvest_logo_178x138.jpg new file mode 100644 index 0000000000..a907c27f42 Binary files /dev/null and b/lms/static/images/press/eduinvest_logo_178x138.jpg differ diff --git a/lms/static/images/press/forbes_logo_178x138.jpg b/lms/static/images/press/forbes_logo_178x138.jpg new file mode 100755 index 0000000000..14f3e250a3 Binary files /dev/null and b/lms/static/images/press/forbes_logo_178x138.jpg differ diff --git a/lms/static/images/press/ft_logo_178x138.jpg b/lms/static/images/press/ft_logo_178x138.jpg new file mode 100644 index 0000000000..72a89bf5b0 Binary files /dev/null and b/lms/static/images/press/ft_logo_178x138.jpg differ diff --git a/lms/static/images/press/govtech_logo_178x138.jpg b/lms/static/images/press/govtech_logo_178x138.jpg new file mode 100644 index 0000000000..bd119e95a0 Binary files /dev/null and b/lms/static/images/press/govtech_logo_178x138.jpg differ diff --git a/lms/static/images/press/ibtimes_logo_178x138.jpg b/lms/static/images/press/ibtimes_logo_178x138.jpg new file mode 100644 index 0000000000..80cde4af9b Binary files /dev/null and b/lms/static/images/press/ibtimes_logo_178x138.jpg differ diff --git a/lms/static/images/press/knowledgespeak_logo_178x138.jpg b/lms/static/images/press/knowledgespeak_logo_178x138.jpg new file mode 100644 index 0000000000..20c9d7e095 Binary files /dev/null and b/lms/static/images/press/knowledgespeak_logo_178x138.jpg differ diff --git a/lms/static/images/press/masshightech_logo_178x138.jpg b/lms/static/images/press/masshightech_logo_178x138.jpg new file mode 100644 index 0000000000..ff8272d3ed Binary files /dev/null and b/lms/static/images/press/masshightech_logo_178x138.jpg differ diff --git a/lms/static/images/press/npq_logo_178x138.jpg b/lms/static/images/press/npq_logo_178x138.jpg new file mode 100644 index 0000000000..69a8d6593a Binary files /dev/null and b/lms/static/images/press/npq_logo_178x138.jpg differ diff --git a/lms/static/images/press/nz_listener_logo_178x138.jpg b/lms/static/images/press/nz_listener_logo_178x138.jpg new file mode 100644 index 0000000000..88e05b81ec Binary files /dev/null and b/lms/static/images/press/nz_listener_logo_178x138.jpg differ diff --git a/lms/static/images/press/online_colleges_logo_178x138.jpg b/lms/static/images/press/online_colleges_logo_178x138.jpg new file mode 100644 index 0000000000..703e9c065b Binary files /dev/null and b/lms/static/images/press/online_colleges_logo_178x138.jpg differ diff --git a/lms/static/images/press/outsell_logo_178x138.jpg b/lms/static/images/press/outsell_logo_178x138.jpg new file mode 100644 index 0000000000..1e885fba08 Binary files /dev/null and b/lms/static/images/press/outsell_logo_178x138.jpg differ diff --git a/lms/static/images/press/reuters_logo_178x138.jpg b/lms/static/images/press/reuters_logo_178x138.jpg new file mode 100644 index 0000000000..4f4ee9ec22 Binary files /dev/null and b/lms/static/images/press/reuters_logo_178x138.jpg differ diff --git a/lms/static/images/press/techreview_logo_178x138.jpg b/lms/static/images/press/techreview_logo_178x138.jpg old mode 100755 new mode 100644 index ffbd3756c9..7a2e063d77 Binary files a/lms/static/images/press/techreview_logo_178x138.jpg and b/lms/static/images/press/techreview_logo_178x138.jpg differ diff --git a/lms/static/images/press/test/bbc_logo_178x138.jpg b/lms/static/images/press/test/bbc_logo_178x138.jpg new file mode 100755 index 0000000000..b047d814fe Binary files /dev/null and b/lms/static/images/press/test/bbc_logo_178x138.jpg differ diff --git a/lms/static/images/press/test/bostonglobe_logo_178x138.jpg b/lms/static/images/press/test/bostonglobe_logo_178x138.jpg new file mode 100755 index 0000000000..9d2aa0bb10 Binary files /dev/null and b/lms/static/images/press/test/bostonglobe_logo_178x138.jpg differ diff --git a/lms/static/images/press/test/bostonmag_logo_178x138.jpg b/lms/static/images/press/test/bostonmag_logo_178x138.jpg new file mode 100644 index 0000000000..5a756ccb24 Binary files /dev/null and b/lms/static/images/press/test/bostonmag_logo_178x138.jpg differ diff --git a/lms/static/images/press/test/nyt_logo_178x138.jpg b/lms/static/images/press/test/nyt_logo_178x138.jpg new file mode 100755 index 0000000000..8a9a75b7f1 Binary files /dev/null and b/lms/static/images/press/test/nyt_logo_178x138.jpg differ diff --git a/lms/static/images/press/test/usnews_logo_178x138.jpg b/lms/static/images/press/test/usnews_logo_178x138.jpg new file mode 100755 index 0000000000..09d4c07280 Binary files /dev/null and b/lms/static/images/press/test/usnews_logo_178x138.jpg differ diff --git a/lms/static/images/press/texaspulse_logo_178x138.jpg b/lms/static/images/press/texaspulse_logo_178x138.jpg new file mode 100644 index 0000000000..059fa39d55 Binary files /dev/null and b/lms/static/images/press/texaspulse_logo_178x138.jpg differ diff --git a/lms/static/images/press/texastribune_logo_178x138.jpg b/lms/static/images/press/texastribune_logo_178x138.jpg new file mode 100644 index 0000000000..dc93010d69 Binary files /dev/null and b/lms/static/images/press/texastribune_logo_178x138.jpg differ diff --git a/lms/static/images/press/theadvocate_logo_178x138.jpg b/lms/static/images/press/theadvocate_logo_178x138.jpg new file mode 100644 index 0000000000..824cfbe9c5 Binary files /dev/null and b/lms/static/images/press/theadvocate_logo_178x138.jpg differ diff --git a/lms/static/images/press/thehopen_logo_178x138.jpg b/lms/static/images/press/thehopen_logo_178x138.jpg new file mode 100644 index 0000000000..4f6a95d737 Binary files /dev/null and b/lms/static/images/press/thehopen_logo_178x138.jpg differ diff --git a/lms/static/images/press/timeshighered_logo_178x138.jpg b/lms/static/images/press/timeshighered_logo_178x138.jpg new file mode 100644 index 0000000000..33920d2bdc Binary files /dev/null and b/lms/static/images/press/timeshighered_logo_178x138.jpg differ diff --git a/lms/static/images/press/washpost_logo_178x138.jpg b/lms/static/images/press/washpost_logo_178x138.jpg new file mode 100644 index 0000000000..928cf227b7 Binary files /dev/null and b/lms/static/images/press/washpost_logo_178x138.jpg differ diff --git a/lms/static/images/press/wsj_logo_178x138.jpg b/lms/static/images/press/wsj_logo_178x138.jpg new file mode 100644 index 0000000000..0920557417 Binary files /dev/null and b/lms/static/images/press/wsj_logo_178x138.jpg differ diff --git a/lms/static/sass/base/_variables.scss b/lms/static/sass/base/_variables.scss index fad5feff3a..8d1b78a0eb 100644 --- a/lms/static/sass/base/_variables.scss +++ b/lms/static/sass/base/_variables.scss @@ -26,7 +26,6 @@ $sidebar-color: #f6f6f6; $outer-border-color: #aaa; // old variables - $light-gray: #ddd; $dark-gray: #333; $text-color: $dark-gray; diff --git a/lms/static/sass/course/base/_base.scss b/lms/static/sass/course/base/_base.scss index 62237fd7a9..6183c8a675 100644 --- a/lms/static/sass/course/base/_base.scss +++ b/lms/static/sass/course/base/_base.scss @@ -132,7 +132,7 @@ img { } .site-status { - display: block; + display: block; } .toast-notification { diff --git a/lms/static/sass/course/courseware/_courseware.scss b/lms/static/sass/course/courseware/_courseware.scss index 010d47ba29..350665dbce 100644 --- a/lms/static/sass/course/courseware/_courseware.scss +++ b/lms/static/sass/course/courseware/_courseware.scss @@ -242,4 +242,29 @@ div.course-wrapper { } +section.self-assessment { + textarea.answer { + height: 200px; + padding: 5px; + margin-top: 5px; + margin-bottom: 5px; + } + + textarea.hint { + height: 100px; + padding: 5px; + margin-top: 5px; + margin-bottom: 5px; + } + + div { + margin-top: 5px; + margin-bottom: 5px; + } + + .error { + font-size: 14px; + font-weight: bold; + } +} diff --git a/lms/static/sass/multicourse/_dashboard.scss b/lms/static/sass/multicourse/_dashboard.scss index 53418bc0dd..ccd5650da4 100644 --- a/lms/static/sass/multicourse/_dashboard.scss +++ b/lms/static/sass/multicourse/_dashboard.scss @@ -179,6 +179,7 @@ overflow: hidden; position: relative; width: flex-grid(12); + z-index: 20; @include transition(all, 0.15s, linear); &:last-child { @@ -318,6 +319,19 @@ } } + .course-status-completed { + background: #ccc; + color: #fff; + + p { + color: #222; + + span { + font-weight: bold; + } + } + } + .enter-course { @include button(shiny, $blue); @include box-sizing(border-box); @@ -357,10 +371,113 @@ border-color: darken(rgb(200,200,200), 3%); @include box-shadow(0 1px 0 0 rgba(255,255,255, 0.6)); } + + .course-status-completed { + background: #888; + color: #fff; + } } } } + .message-status { + @include border-radius(3px); + @include box-shadow(0 1px 4px 0 rgba(0,0,0, 0.1), inset 0 -1px 0 0 rgba(255,255,255, 0.8), inset 0 1px 0 0 rgba(255,255,255, 0.8)); + display: none; + position: relative; + top: -15px; + z-index: 10; + margin: 0 0 20px 0; + padding: 15px 20px; + font-family: "Open Sans", Verdana, Geneva, sans-serif; + background: #fffcf0; + border: 1px solid #ccc; + + .message-copy { + margin: 0; + + .grade-value { + font-size: 1.4rem; + font-weight: bold; + } + } + + .actions { + @include clearfix; + list-style: none; + margin: 15px 0 0 0; + padding: 0; + + .action { + float: left; + margin:0 15px 10px 0; + + .btn, .cta { + display: inline-block; + } + + .btn { + @include button(shiny, $blue); + @include box-sizing(border-box); + @include border-radius(3px); + float: left; + font: normal 0.8rem/1.2rem $sans-serif; + letter-spacing: 1px; + padding: 6px 12px; + text-align: center; + + &.disabled { + @include button(shiny, #eee); + cursor: default !important; + + &:hover { + background: #eee; + background-image: -webkit-linear-gradient(top, #EEE 0%, #C2C2C2 50%, #ABABAB 50%, #B0B0B0 100%); + background-image: -moz-linear-gradient(top, #EEE 0%, #C2C2C2 50%, #ABABAB 50%, #B0B0B0 100%); + background-image: -ms-linear-gradient(top, #EEE 0%, #C2C2C2 50%, #ABABAB 50%, #B0B0B0 100%); + background-image: -o-linear-gradient(top, #EEE 0%, #C2C2C2 50%, #ABABAB 50%, #B0B0B0 100%); + background-image: linear-gradient(top, #EEE 0%, #C2C2C2 50%, #ABABAB 50%, #B0B0B0 100%); + } + } + } + + .cta { + @include button(shiny, #666); + float: left; + font: normal 0.8rem/1.2rem $sans-serif; + letter-spacing: 1px; + padding: 6px 12px; + text-align: center; + } + } + } + + &.is-shown { + display: block; + } + + &.course-status-processing { + + } + + &.course-status-certnotavailable { + // background: #fee8d6; + } + + &.course-status-certrendering { + // background: #d9e7db; + + .cta { + margin-top: 2px; + } + } + + &.course-status-certavailable { + // background: #d9e7db; + } + } + + a.unenroll { float: right; font-style: italic; diff --git a/lms/static/sass/multicourse/_jobs.scss b/lms/static/sass/multicourse/_jobs.scss index d2f86e93a6..f9629232d6 100644 --- a/lms/static/sass/multicourse/_jobs.scss +++ b/lms/static/sass/multicourse/_jobs.scss @@ -136,6 +136,14 @@ margin-bottom: 15px; } + h4 { + font-size: 1.0em; + font-family: $sans-serif; + font-weight: 700; + margin-top: 25px; + margin-bottom: 10px; + } + ul { padding-left: 50px; } diff --git a/lms/templates/courseware/courseware.html b/lms/templates/courseware/courseware.html index 62af7d6f82..1ea3df1b5a 100644 --- a/lms/templates/courseware/courseware.html +++ b/lms/templates/courseware/courseware.html @@ -25,7 +25,9 @@ <%static:js group='discussion'/> <%include file="../discussion/_js_body_dependencies.html" /> - + % if staff_access: + <%include file="xqa_interface.html"/> + % endif + \ No newline at end of file diff --git a/lms/templates/dashboard.html b/lms/templates/dashboard.html index 3fdcbb5c1c..2069685a6c 100644 --- a/lms/templates/dashboard.html +++ b/lms/templates/dashboard.html @@ -2,6 +2,7 @@ from django.core.urlresolvers import reverse from courseware.courses import course_image_url, get_course_about_section from courseware.access import has_access + from certificates.models import CertificateStatuses %> <%inherit file="main.html" /> @@ -135,8 +136,16 @@

${get_course_about_section(course, 'university')}

${course.number} ${course.title}

-
-

Class Starts - ${course.start_date_text}

+
+

+ % if course.has_ended(): + Course Completed - ${course.end_date_text} + % elif course.has_started(): + Course Started - ${course.start_date_text} + % else: # hasn't started yet + Course Starts - ${course.start_date_text} + % endif +

% if course.id in show_courseware_links_for:

View Courseware

@@ -144,6 +153,68 @@
+ + <% + cert_status = cert_statuses.get(course.id) + %> + % if course.has_ended() and cert_status: + <% + passing_grade = False + cert_button = False + survey_button = False + if cert_status['status'] in [CertificateStatuses.generating, CertificateStatuses.regenerating]: + status_css_class = 'course-status-certrendering' + cert_button = True + survey_button = True + passing_grade = True + elif cert_status['status'] == CertificateStatuses.downloadable: + status_css_class = 'course-status-certavailable' + cert_button = True + survey_button = True + passing_grade = True + elif cert_status['status'] == CertificateStatuses.notpassing: + status_css_class = 'course-status-certnotavailable' + survey_button = True + else: + # This is primarily the 'unavailable' state, but also 'error', 'deleted', etc. + status_css_class = 'course-status-processing' + + if survey_button and not course.end_of_course_survey_url: + survey_button = False + %> +
+ + % if cert_status['status'] == CertificateStatuses.unavailable: +

Final course details are being wrapped up at this time. + Your final standing will be available shortly.

+ % elif passing_grade: +

You have received a grade of + ${cert_status['grade']} + in this course.

+ % elif cert_status['status'] == CertificateStatuses.notpassing: +

You did not complete the necessary requirements for completion of this course. +

+ % endif + % if cert_button or survey_button: +
    + % if cert_button and cert_status['status'] in [CertificateStatuses.generating, CertificateStatuses.regenerating]: +
  • Your Certificate is Generating
  • + % elif cert_button and cert_status['status'] == CertificateStatuses.downloadable: +
  • + + Download Your PDF Certificate
  • + % endif + % if survey_button: +
  • + Complete our course feedback survey
  • + % endif +
+ % endif +
+ + % endif + Unregister % endfor @@ -280,4 +351,3 @@
- diff --git a/lms/templates/discussion/_discussion_course_navigation.html b/lms/templates/discussion/_discussion_course_navigation.html index 13b291196b..d770cacc96 100644 --- a/lms/templates/discussion/_discussion_course_navigation.html +++ b/lms/templates/discussion/_discussion_course_navigation.html @@ -1,5 +1,8 @@ +<%! from django_comment_client.permissions import has_permission %> <%inherit file="../courseware/course_navigation.html" /> <%block name="extratabs"> +% if has_permission(user, 'create_thread', course.id):
  • New Post
  • +% endif \ No newline at end of file diff --git a/lms/templates/discussion/_discussion_module.html b/lms/templates/discussion/_discussion_module.html index bb172093f6..8fced92f7f 100644 --- a/lms/templates/discussion/_discussion_module.html +++ b/lms/templates/discussion/_discussion_module.html @@ -3,4 +3,6 @@ diff --git a/lms/templates/discussion/_underscore_templates.html b/lms/templates/discussion/_underscore_templates.html index 0a691ac36f..be238811c2 100644 --- a/lms/templates/discussion/_underscore_templates.html +++ b/lms/templates/discussion/_underscore_templates.html @@ -1,3 +1,5 @@ +<%! from django_comment_client.permissions import has_permission %> + @@ -75,6 +79,7 @@
    1. + % if course is UNDEFINED or has_permission(user, 'create_sub_comment', course.id):
        Submit
        + % endif
      diff --git a/lms/templates/google_analytics.html b/lms/templates/google_analytics.html new file mode 100644 index 0000000000..273fbac970 --- /dev/null +++ b/lms/templates/google_analytics.html @@ -0,0 +1,11 @@ + diff --git a/lms/templates/index.html b/lms/templates/index.html index 151525f715..096bfe9fcc 100644 --- a/lms/templates/index.html +++ b/lms/templates/index.html @@ -128,17 +128,18 @@ diff --git a/lms/templates/main.html b/lms/templates/main.html index f234aa72cf..5d3fd29104 100644 --- a/lms/templates/main.html +++ b/lms/templates/main.html @@ -19,22 +19,12 @@ <%static:css group='ie-fixes'/> + % if not course: - + <%include file="google_analytics.html" /> % endif + diff --git a/lms/templates/portal/course_about.html b/lms/templates/portal/course_about.html index 6fced73565..b35c7a1b6f 100644 --- a/lms/templates/portal/course_about.html +++ b/lms/templates/portal/course_about.html @@ -7,7 +7,12 @@ <%inherit file="../main.html" /> +<%block name="headextra"> + <%include file="../google_analytics.html" /> + + <%block name="js_extra"> + % if not registered: %if user.is_authenticated(): ## If the user is authenticated, clicking the enroll button just submits a form diff --git a/lms/templates/press.json b/lms/templates/press.json index e4aeb48675..24e4028bc7 100644 --- a/lms/templates/press.json +++ b/lms/templates/press.json @@ -1,5 +1,617 @@ [ + { + "title": "The Year of the MOOC", + "url": "http://www.nytimes.com/2012/11/04/education/edlife/massive-open-online-courses-are-multiplying-at-a-rapid-pace.html", + "author": "Laura Pappano", + "image": "nyt_logo_178x138.jpeg", + "deck": null, + "publication": "The New York Times", + "publish_date": "November 2, 2012" + }, + { + "title": "The Most Important Education Technology in 200 Years", + "url": "http://www.technologyreview.com/news/506351/the-most-important-education-technology-in-200-years/", + "author": "Antonio Regalado", + "image": "techreview_logo_178x138.jpg", + "deck": null, + "publication": "Technology Review", + "publish_date": "November 2, 2012" + }, + { + "title": "Classroom in the Cloud", + "url": "http://harvardmagazine.com/2012/11/classroom-in-the-cloud", + "author": null, + "image": "harvardmagazine_logo_178x138.jpeg", + "deck": null, + "publication": "Harvard Magazine", + "publish_date": "November-December 2012" + }, + { + "title": "How do you stop online students cheating?", + "url": "http://www.bbc.co.uk/news/business-19661899", + "author": "Sean Coughlan", + "image": "bbc_logo_178x138.jpeg", + "deck": null, + "publication": "BBC", + "publish_date": "October 31, 2012" + }, + { + "title": "VMware to provide software for HarvardX CS50x", + "url": "http://tech.mit.edu/V132/N48/edxvmware.html", + "author": "Stan Gill", + "image": "thetech_logo_178x138.jpg", + "deck": null, + "publication": "The Tech", + "publish_date": "October 26, 2012" + }, + { + "title": "EdX platform integrates into classes", + "url": "http://tech.mit.edu/V132/N48/801edx.html", + "author": "Leon Lin", + "image": "thetech_logo_178x138.jpg", + "deck": null, + "publication": "The Tech", + "publish_date": "October 26, 2012" + }, + { + "title": "VMware Offers Free Software to edX Learners", + "url": "http://campustechnology.com/articles/2012/10/25/vmware-offers-free-virtualization-software-for-edx-computer-science-students.aspx", + "author": "Joshua Bolkan", + "image": "campustech_logo_178x138.jpg", + "deck": "VMware Offers Free Virtualization Software for EdX Computer Science Students", + "publication": "Campus Technology", + "publish_date": "October 25, 2012" + }, + { + "title": "Lone Star moots charges to make Moocs add up", + "url": "http://www.timeshighereducation.co.uk/story.asp?sectioncode=26&storycode=421577&c=1", + "author": "David Matthews", + "image": "timeshighered_logo_178x138.jpg", + "deck": null, + "publication": "Times Higher Education", + "publish_date": "October 25, 2012" + }, + { + "title": "Free, high-quality and with mass appeal", + "url": "http://www.ft.com/intl/cms/s/2/73030f44-d4dd-11e1-9444-00144feabdc0.html#axzz2A9qvk48A", + "author": "Rebecca Knight", + "image": "ft_logo_178x138.jpg", + "deck": null, + "publication": "Financial Times", + "publish_date": "October 22, 2012" + }, + { + "title": "Getting the most out of an online education", + "url": "http://www.reuters.com/article/2012/10/19/us-education-courses-online-idUSBRE89I17120121019", + "author": "Kathleen Kingsbury", + "image": "reuters_logo_178x138.jpg", + "deck": null, + "publication": "Reuters", + "publish_date": "October 19, 2012" + }, + { + "title": "EdX announces partnership with Cengage", + "url": "http://tech.mit.edu/V132/N46/cengage.html", + "author": "Leon Lin", + "image": "thetech_logo_178x138.jpg", + "deck": null, + "publication": "The Tech", + "publish_date": "October 19, 2012" + }, + { + "title": "U Texas System Joins EdX", + "url": "http://campustechnology.com/articles/2012/10/18/u-texas-system-joins-edx.aspx", + "author": "Joshua Bolkan", + "image": "campustech_logo_178x138.jpg", + "deck": null, + "publication": "Campus Technology", + "publish_date": "October 18, 2012" + }, + { + "title": "San Jose State University Runs Blended Learning Course Using edX ", + "url": "http://chronicle.com/blogs/wiredcampus/san-jose-state-u-says-replacing-live-lectures-with-videos-increased-test-scores/40470", + "author": "Alisha Azevedo", + "image": "chroniclehighered_logo_178x138.jpeg", + "deck": "San Jose State U. Says Replacing Live Lectures With Videos Increased Test Scores", + "publication": "Chronicle of Higher Education", + "publish_date": "October 17, 2012" + }, + { + "title": "Online university to charge tuition fees", + "url": "http://www.bbc.co.uk/news/education-19964787", + "author": "Sean Coughlan", + "image": "bbc_logo_178x138.jpeg", + "deck": null, + "publication": "BBC", + "publish_date": "October 17, 2012" + }, + { + "title": "HarvardX marks the spot", + "url": "http://news.harvard.edu/gazette/story/2012/10/harvardx-marks-the-spot/", + "author": "Tania delLuzuriaga", + "image": "harvardgazette_logo_178x138.jpeg", + "deck": null, + "publication": "Harvard Gazette", + "publish_date": "October 17, 2012" + }, + { + "title": "Harvard EdX Enrolls Near 100000 Students for Free Online Classes", + "url": "http://www.collegeclasses.com/harvard-edx-enrolls-near-100000-students-for-free-online-classes/", + "author": "Keith Koong", + "image": "college_classes_logo_178x138.jpg", + "deck": null, + "publication": "CollegeClasses.com", + "publish_date": "October 17, 2012" + }, + { + "title": "Cengage Learning to Provide Book Content and Pedagogy through edX's Not-for-Profit Interactive Study Via the Web", + "url": "http://www.outsellinc.com/our_industry/headlines/1087978", + "author": null, + "image": "outsell_logo_178x138.jpg", + "deck": null, + "publication": "Outsell.com", + "publish_date": "October 17, 2012" + }, + { + "title": "University of Texas System Embraces MOOCs", + "url": "http://www.usnewsuniversitydirectory.com/articles/university-of-texas-system-embraces-moocs_12713.aspx#.UIBLVq7bNzo", + "author": "Chris Hassan", + "image": "usnews_logo_178x138.jpeg", + "deck": null, + "publication": "US News", + "publish_date": "October 17, 2012" + }, + { + "title": "Texas MOOCs for Credit?", + "url": "http://www.insidehighered.com/news/2012/10/16/u-texas-aims-use-moocs-reduce-costs-increase-completion", + "author": "Steve Kolowich", + "image": "insidehighered_logo_178x138.jpg", + "deck": null, + "publication": "Insider Higher Ed", + "publish_date": "October 16, 2012" + }, + { + "title": "University of Texas Joins Harvard-Founded edX", + "url": "http://www.thecrimson.com/article/2012/10/16/University-of-Texas-edX/", + "author": "Kevin J. Wu", + "image": "harvardcrimson_logo_178x138.jpeg", + "deck": null, + "publication": "The Crimson", + "publish_date": "October 16, 2012" + }, + { + "title": "Entire UT System to join edX", + "url": "http://tech.mit.edu/V132/N45/edx.html", + "author": "Ethan A. Solomon", + "image": "thetech_logo_178x138.jpg", + "deck": null, + "publication": "The Tech", + "publish_date": "October 16, 2012" + }, + { + "title": "First University System Joins edX Platform", + "url": "http://www.govtech.com/education/First-University-System-Joins-edX-platform.html", + "author": "Tanya Roscoria", + "image": "govtech_logo_178x138.jpg", + "deck": null, + "publication": "GovTech.com", + "publish_date": "October 16, 2012" + }, + { + "title": "University of Texas Joining Harvard, MIT Online Venture", + "url": "http://www.bloomberg.com/news/2012-10-15/university-of-texas-joining-harvard-mit-online-venture.html", + "author": "David Mildenberg", + "image": "bloomberg_logo_178x138.jpeg", + "deck": null, + "publication": "Bloomberg", + "publish_date": "October 15, 2012" + }, + { + "title": "University of Texas Joining Harvard, MIT Online Venture", + "url": "http://www.businessweek.com/news/2012-10-15/university-of-texas-joining-harvard-mit-online-venture", + "author": "David Mildenberg", + "image": "busweek_logo_178x138.jpg", + "deck": null, + "publication": "Business Week", + "publish_date": "October 15, 2012" + }, + { + "title": "Univ. of Texas joins online course program edX", + "url": "http://news.yahoo.com/univ-texas-joins-online-course-program-edx-172202035--finance.html", + "author": "Chris Tomlinson", + "image": "ap_logo_178x138.jpg", + "deck": null, + "publication": "Associated Press", + "publish_date": "October 15, 2012" + }, + { + "title": "U. of Texas Plans to Join edX", + "url": "http://www.insidehighered.com/quicktakes/2012/10/15/u-texas-plans-join-edx", + "author": null, + "image": "insidehighered_logo_178x138.jpg", + "deck": null, + "publication": "Inside Higher Ed", + "publish_date": "October 15, 2012" + }, + { + "title": "U. of Texas System Is Latest to Sign Up With edX for Online Courses", + "url": "http://chronicle.com/blogs/wiredcampus/u-of-texas-system-is-latest-to-sign-up-with-edx-for-online-courses/40440", + "author": "Alisha Azevedo", + "image": "chroniclehighered_logo_178x138.jpeg", + "deck": null, + "publication": "Chronicle of Higher Education", + "publish_date": "October 15, 2012" + }, + { + "title": "First University System Joins edX", + "url": "http://www.centerdigitaled.com/news/First-University-System-Joins-edX.html", + "author": "Tanya Roscoria", + "image": "center_digeducation_logo_178x138.jpg", + "deck": null, + "publication": "Center for Digital Education", + "publish_date": "October 15, 2012" + }, + { + "title": "University of Texas Joins Harvard, MIT in edX Online Learning Venture", + "url": "http://harvardmagazine.com/2012/10/university-of-texas-joins-harvard-mit-edx", + "author": null, + "image": "harvardmagazine_logo_178x138.jpeg", + "deck": null, + "publication": "Harvard Magazine", + "publish_date": "October 15, 2012" + }, + { + "title": "University of Texas joins edX", + "url": "http://www.masshightech.com/stories/2012/10/15/daily13-University-of-Texas-joins-edX.html", + "author": "Don Seiffert", + "image": "masshightech_logo_178x138.jpg", + "deck": null, + "publication": "MassHighTech", + "publish_date": "October 15, 2012" + }, + { + "title": "UT System to Forge Partnership with EdX", + "url": "http://www.texastribune.org/texas-education/higher-education/ut-system-announce-partnership-edx/", + "author": "Reeve Hamilton", + "image": "texastribune_logo_178x138.jpg", + "deck": null, + "publication": "Texas Tribune", + "publish_date": "October 15, 2012" + }, + { + "title": "UT System puts $5 million into online learning initiative", + "url": "http://www.statesman.com/news/news/local/ut-system-puts-5-million-into-online-learning-init/nSdd5/", + "author": "Ralph K.M. Haurwitz", + "image": "austin_statesman_logo_178x138.jpg", + "deck": null, + "publication": "The Austin Statesman", + "publish_date": "October 15, 2012" + }, + { + "title": "Harvard’s Online Classes Sound Pretty Popular", + "url": "http://blogs.bostonmagazine.com/boston_daily/2012/10/15/harvards-online-classes-sound-pretty-popular/", + "author": "Eric Randall", + "image": "bostonmag_logo_178x138.jpg", + "deck": null, + "publication": "Boston Magazine", + "publish_date": "October 15, 2012" + }, + { + "title": "Harvard Debuts Free Online Courses", + "url": "http://www.ibtimes.com/harvard-debuts-free-online-courses-846629", + "author": "Eli Epstein", + "image": "ibtimes_logo_178x138.jpg", + "deck": null, + "publication": "International Business Times", + "publish_date": "October 15, 2012" + }, + { + "title": "UT System Joins Online Learning Effort", + "url": "http://www.texastechpulse.com/ut_system_joins_online_learning_effort/s-0045632.html", + "author": null, + "image": "texaspulse_logo_178x138.jpg", + "deck": null, + "publication": "Texas Tech Pulse", + "publish_date": "October 15, 2012" + }, + { + "title": "University of Texas Joins edX", + "url": "http://www.onlinecolleges.net/2012/10/15/university-of-texas-joins-edx/", + "author": "Alex Wukman", + "image": "online_colleges_logo_178x138.jpg", + "deck": null, + "publication": "Online Colleges.net", + "publish_date": "October 15, 2012" + }, + { + "title": "100,000 sign up for first Harvard online courses", + "url": "http://www.masslive.com/news/index.ssf/2012/10/100000_sign_up_for_first_harva.html", + "author": null, + "image": "ap_logo_178x138.jpg", + "deck": null, + "publication": "Associated Press", + "publish_date": "October 15, 2012" + }, + { + "title": "In the new Listener, on sale from 14.10.12", + "url": "http://www.listener.co.nz/commentary/the-internaut/in-the-new-listener-on-sale-from-14-10-12/", + "author": null, + "image": "nz_listener_logo_178x138.jpg", + "deck": null, + "publication": "The Listener", + "publish_date": "October 14, 2012" + }, + { + "title": "HarvardX Classes to Begin Tomorrow", + "url": "http://www.thecrimson.com/article/2012/10/14/harvardx-classes-start-tomorrow/", + "author": "Hana N. Rouse", + "image": "harvardcrimson_logo_178x138.jpeg", + "deck": null, + "publication": "The Crimson", + "publish_date": "October 14, 2012" + }, + { + "title": "Online Harvard University courses draw well", + "url": "http://bostonglobe.com/metro/2012/10/14/harvard-launching-free-online-courses-sign-for-first-two-classes/zBDuHY0zqD4OESrXWfEgML/story.html", + "author": "Brock Parker", + "image": "bostonglobe_logo_178x138.jpeg", + "deck": null, + "publication": "Boston Globe", + "publish_date": "October 14, 2012" + }, + { + "title": "Harvard ready to launch its first free online courses Monday", + "url": "http://www.boston.com/yourtown/news/cambridge/2012/10/harvard_ready_to_launch_its_fi.html", + "author": "Brock Parker", + "image": "bostonglobe_logo_178x138.jpeg", + "deck": null, + "publication": "Boston Globe", + "publish_date": "October 12, 2012" + }, + { + "title": "edX: Harvard's New Domain", + "url": "http://www.thecrimson.com/article/2012/10/4/edx-scrutiny-online-learning/ ", + "author": "Delphine Rodrik and Kevin Su", + "image": "harvardcrimson_logo_178x138.jpeg", + "deck": null, + "publication": "The Crimson", + "publish_date": "October 4, 2012" + }, + { + "title": "New Experiments in the edX Higher Ed Petri Dish", + "url": "http://www.nonprofitquarterly.org/policysocial-context/21116-new-experiments-in-the-edx-higher-ed-petri-dish.html", + "author": "Michelle Shumate", + "image": "npq_logo_178x138.jpg", + "deck": null, + "publication": "Non-Profit Quarterly", + "publish_date": "October 4, 2012" + }, + { + "title": "What Campuses Can Learn From Online Teaching", + "url": "http://online.wsj.com/article/SB10000872396390444620104578012262106378182.html?mod=googlenews_wsj", + "author": "Rafael Reif", + "image": "wsj_logo_178x138.jpg", + "deck": null, + "publication": "Wall Street Journal", + "publish_date": "October 2, 2012" + }, + { + "title": "MongoDB courses to be offered via edX", + "url": "http://tech.mit.edu/V132/N42/edxmongodb.html", + "author": "Jake H. Gunter", + "image": "thetech_logo_178x138.jpg", + "deck": null, + "publication": "The Tech", + "publish_date": "October 2, 2012" + }, + { + "title": "5 Ways That edX Could Change Education", + "url": "http://chronicle.com/article/5-Ways-That-edX-Could-Change/134672/", + "author": "Marc Parry", + "image": "chroniclehighered_logo_178x138.jpeg", + "deck": null, + "publication": "Chronicle of Higher Education", + "publish_date": "October 1, 2012" + }, + { + "title": "MIT profs wait to teach you, for free", + "url": "http://www.dnaindia.com/mumbai/report_mit-profs-wait-to-teach-you-for-free_1747273", + "author": "Kanchan Srivastava", + "image": "dailynews_india_logo_178x138.jpg", + "deck": null, + "publication": "Daily News and Analysis India", + "publish_date": "October 1, 2012" + }, + { + "title": "EdX offers free higher education online", + "url": "http://www.youtube.com/watch?v=yr5Ep7RN4Bs", + "author": "via YouTube", + "image": "cnn_logo_178x138.jpg", + "deck": null, + "publication": "CNN", + "publish_date": "October, 2012" + }, + { + "title": "Students weigh in on value of massive open online classes", + "url": "http://dailycollegian.com/2012/09/27/students-weigh-in-on-value-of-massive-open-online-classes/", + "author": "Sam Hayes", + "image": "dailycollegian_logo_178x138.jpg", + "deck": null, + "publication": "The Daily Collegian", + "publish_date": "September 27, 2012" + }, + { + "title": "The Crisis in Higher Education", + "url": "http://www.technologyreview.com/featured-story/429376/the-crisis-in-higher-education ", + "author": "Nicholas Carr", + "image": "techreview_logo_178x138.jpg", + "deck": null, + "publication": "Technology Review", + "publish_date": "September 27, 2012" + }, + { + "title": "10gen Offering Free MongoDB Training through EdX Platform", + "url": "http://campustechnology.com/articles/2012/09/27/10gen-offering-free-mongodb-training-through-edx-platform.aspx", + "author": "Dian Schaffhauser", + "image": "campustech_logo_178x138.jpg", + "deck": null, + "publication": "Campus Technology", + "publish_date": "September 27, 2012" + }, + { + "title": "edX Students To Use Free Elsevier Online Textbook", + "url": "http://campustechnology.com/articles/2012/09/27/edx-students-to-use-free-elsevier-online-textbook.aspx", + "author": "Tim Sohn", + "image": "campustech_logo_178x138.jpg", + "deck": null, + "publication": "Campus Technology", + "publish_date": "September 27, 2012" + }, + { + "title": "Students weigh in on value of massive open online classes", + "url": "http://dailycollegian.com/2012/09/27/students-weigh-in-on-value-of-massive-open-online-classes/", + "author": "Sam Hayes", + "image": "dailycollegian_logo_178x138.jpg", + "deck": null, + "publication": "The Daily Collegian", + "publish_date": "September 27, 2012" + }, + { + "title": "Elsevier partners with edX offering interactive study via the web", + "url": "http://www.knowledgespeak.com/newsArchieveviewdtl.asp?pickUpBatch=2046", + "author": null, + "image": "cnn_logo_178x138.jpg", + "deck": null, + "publication": "Knowledge Speak", + "publish_date": "September 26, 2012" + }, + { + "title": "Coming back, looking forward", + "url": "http://news.harvard.edu/gazette/story/2012/09/governing_board_reunion/", + "author": "Alvin Powell", + "image": "harvardgazette_logo_178x138.jpeg", + "deck": "Governing boards’ reunion mixes nostalgia, innovation", + "publication": "Harvard Gazette", + "publish_date": "September 26, 2012" + }, + { + "title": "MongoDB developers team with EdX open learning collaboration", + "url": "http://arstechnica.com/information-technology/2012/09/mongodb-developers-team-with-edx-open-learning-collaboration/", + "author": "Sean Gallagher", + "image": "arstechnica_logo_178x138.jpg", + "deck": " To offer free MongoDB developer and DBA training, help open-source EdX platform.", + "publication": "Ars Technica", + "publish_date": "September 26, 2012" + }, + { + "title": "Marketing to the MOOC Masses", + "url": "http://www.insidehighered.com/news/2012/09/26/elsevier-partners-edx-provide-free-versions-textbooks-mooc-students", + "author": "Steve Kolowich", + "image": "insidehighered_logo_178x138.jpg", + "deck": null, + "publication": "Inside Higher Ed", + "publish_date": "September 26, 2012" + }, + { + "title": "Five buzzwords you’re likely to hear in education this school year", + "url": "http://schoolsofthought.blogs.cnn.com/2012/09/26/five-buzzwords-youre-likely-to-hear-in-education-this-school-year/", + "author": "Donna Krache", + "image": "cnn_logo_178x138.jpg", + "deck": null, + "publication": "CNN", + "publish_date": "September 26, 2012" + }, + { + "title": "10gen will provide online MongoDB training", + "url": "http://www.h-online.com/open/news/item/10gen-will-provide-online-MongoDB-training-1716936.html", + "author": null, + "image": "thehopen_logo_178x138.jpg", + "deck": null, + "publication": "The H Open", + "publish_date": "September 25, 2012" + }, + { + "title": "Opinion: MIT should create an education degree", + "url": "http://tech.mit.edu/V132/N40/normandin.html", + "author": "Ryan Normandin", + "image": "thetech_logo_178x138.jpg", + "deck": "For MIT to lead the way in education, it should use its graduates", + "publication": "The Tech", + "publish_date": "September 25, 2012" + }, + { + "title": "Want free MongoDB classes? edX and 10gen are happy to oblige", + "url": "http://gigaom.com/2012/09/25/want-free-mongodb-classes-edx-and-10gen-are-happy-to-oblige/", + "author": "Ki Mae Heussner", + "image": "gigaom_logo_178x138.jpeg", + "deck": null, + "publication": "GIGAOM", + "publish_date": "September 25, 2012" + }, + { + "title": "MOOCs Shift From Curiousity to Employability", + "url": "http://www.huffingtonpost.com/tom-vander-ark/moocs-shift-from-curiousi_b_1912059.html", + "author": "Tom Vander Ark", + "image": "huffpost_logo_178x138.jpeg", + "deck": null, + "publication": "HUFF POST", + "publish_date": "September 25, 2012" + }, + { + "title": "A president next door", + "url": "http://news.harvard.edu/gazette/story/2012/09/a-president-next-door/", + "author": "Katie Koch", + "image": "harvardgazette_logo_178x138.jpeg", + "deck": "Faust lauds Reif at his inauguration as MIT’s leader ", + "publication": "Harvard Gazette", + "publish_date": "September 21, 2012" + }, + { + "title": "Is Everybody Right When it Comes to the Future of Education?", + "url": "http://bostinno.com/2012/09/23/is-everybody-right-when-it-comes-to-the-future-of-education/", + "author": "Lauren Landry", + "image": "bostinno_logo_178x138.jpg", + "deck": null, + "publication": "BostInno", + "publish_date": "September 23, 2012" + }, + { + "title": "Keyboard College: How Technology is Revolutionizing Higher Education", + "url": "http://americanradioworks.publicradio.org/features/tomorrows-college/keyboard-college/", + "author": "Stephen Smith", + "image": "amradiowrks_press_logo_178x138.jpg", + "deck": null, + "publication": "American RadioWorks", + "publish_date": "September, 2012" + }, + { + "title": "Google Releases Open-Source Online-Education Software", + "url": "http://chronicle.com/blogs/wiredcampus/google-releases-open-source-online-education-software/39882", + "author": "Azevedo", + "image": "chroniclehighered_logo_178x138.jpeg", + "deck": null, + "publication": "The Chronicle of Higher Education", + "publish_date": "September 13, 2012" + }, + { + "title": "President Faust’s Beginning-of-2012-2013 Message", + "url": "http://harvardmagazine.com/2012/09/harvards-faust-beginning-of-year-message", + "author": null, + "image": "harvardmagazine_logo_178x138.jpeg", + "deck": null, + "publication": "Harvard Magazine", + "publish_date": "September 13, 2012" + }, + { + "title": "The MOOC Survivors", + "url": "http://www.insidehighered.com/news/2012/09/12/edx-explores-demographics-most-persistent-mooc-students", + "author": "Steve Kolowich", + "image": "insidehighered_logo_178x138.jpg", + "deck": null, + "publication": "Inside Higher Education", + "publish_date": "September 12, 2012" + }, { "title": "College may never be the same", "url": "http://www.usatoday.com/news/nation/story/2012/09/12/college-may-never-be-the-same/57752972/1", @@ -9,6 +621,15 @@ "publication": "USA Today", "publish_date": "September 12, 2012" }, + { + "title": "The first 71 days of office", + "url": "http://tech.mit.edu/V132/N36/reif.html", + "author": "Bruno B.F. Faviero", + "image": "thetech_logo_178x138.jpg", + "deck": null, + "publication": "The Tech", + "publish_date": "September 11, 2012" + }, { "title": "Is MIT Giving Away the Farm?", "url": "http://www.technologyreview.com/mitnews/428698/is-mit-giving-away-the-farm/", @@ -16,27 +637,53 @@ "image": "techreview_logo_178x138.jpg", "deck": "The surprising logic of MIT's free online education program.", "publication": "Technology Review", - "publish_date": "September/October 2012" + "publish_date": "September-October 2012" }, { "title": "School’s Out, Forever", - "url": "http://www.bostonmagazine.com/articles/2012/08/edx-online-classes-schools-ou
t-forever/", + "url": "http://www.bostonmagazine.com/articles/2012/08/edx-online-classes-schools-out-forever/", "author": "Chris Vogel", "image": "bostonmag_logo_178x138.jpg", "deck": "A new online education program from Harvard and MIT is poised to transform what it means to go to college.", "publication": "Boston Magazine", - "publish_date": "September 2012" + "publish_date": "September, 2012" }, { - "title": "Q&A: Anant Agarwal, edX’s president and first professor", - "url": "http://www.bostonmagazine.com/articles/2012/08/edx-online-classes-schools-ou
t-forever/", - "author": " Molly Petrilla ", - "image": "smartplanet_logo_178x138.jpg", - "deck": "", - "publication": "Smart Planet", - "publish_date": "September 3, 2012" + "title": "Pearson partners with online learning provider", + "url": "http://www.educationinvestor.co.uk/%28A%28sJl5vujFzQEkAAAAMWZkZTlhNjktODE0Mi00NjliLThlN2MtZTNhNDYxZDU4NGU3x4PawVukQHrQR1HU1YmDjMvTJNs1%29S%28rfj4z455jgfjljudyovhsyzb%29%29/ShowArticle.aspx?ID=2949", + "author": null, + "image": "eduinvest_logo_178x138.jpg", + "deck": null, + "publication": "EducationInvestor", + "publish_date": "September 10, 2012" + }, + { + "title": "Pearson to provide test centers for edX courses", + "url": "http://edtechtimes.com/2012/09/10/pearson-to-provide-test-centers-for-edx-courses/", + "author": null, + "image": "edtechtimes_logo_178x138.jpg", + "deck": null, + "publication": "The EdTech Times", + "publish_date": "September 10, 2012" + }, + { + "title": "Online education - the future of learning", + "url": "http://www.campdenfb.com/article/sponsored-feature-online-education-future-learning", + "author": null, + "image": "campdenfb_logo_178x138.jpg", + "deck": null, + "publication": "Campden FB", + "publish_date": "September 9, 2012" + }, + { + "title": "Step Forward For New Higher Education Model", + "url": "http://www.forbes.com/sites/susanadams/2012/09/07/step-forward-for-new-higher-education-model/", + "author": "Susan Adams", + "image": "forbes_logo_178x138.jpg", + "deck": null, + "publication": "Forbes", + "publish_date": "September 7, 2012" }, - { "title": "EdX To Offer Proctored Final Exam For One Course", "url": "http://www.thecrimson.com/article/2012/9/7/edx-offer-proctored-exams/", @@ -77,9 +724,9 @@ "title": "Harvard-MIT Online School EdX to Offer Supervised Final Exams", "url": "http://www.businessweek.com/news/2012-09-06/harvard-mit-online-school-edx-to-offer-supervised-final-exams", "author": "Oliver Staley", - "image": "bloomberg_logo_178x138.jpeg", + "image": "busweek_logo_178x138.jpg", "deck": "", - "publication": "Bloomberg Business Week", + "publication": "Business Week", "publish_date": "September 6, 2012" }, { @@ -109,14 +756,13 @@ "publication": "ITBriefing.net", "publish_date": "September 6, 2012" }, - { "title": "Student Loans: Debt for Life", "url": "http://www.businessweek.com/articles/2012-09-06/student-loans-debt-for-life#p3", "author": "Peter Coy", - "image": "bloomberg_logo_178x138.jpeg", + "image": "busweek_logo_178x138.jpg", "deck": "", - "publication": "Bloomberg Business Week", + "publication": "Business Week", "publish_date": "September 6, 2012" }, { @@ -146,15 +792,6 @@ "publication": "Time", "publish_date": "September 4, 2012" }, - { - "title": "Ivy walls lower with free online classes from Coursera and edX ", - "url": "http://www.csmonitor.com/Innovation/Pioneers/2012/0903/Ivy-walls-lower-with-free-online-classes-from-Coursera-and-edX", - "author": "Chris Gaylord", - "image": "csmonitor_logo_178x138.jpg", - "deck": "", - "publication": "Christian Science Monitor", - "publish_date": "September 3, 2012" - }, { "title": "Summer recap. RLADs, new edX partner, Institute files amicus brief", "url": "http://tech.mit.edu/V132/N34/summer.html", @@ -164,6 +801,15 @@ "publication": "The Tech", "publish_date": "September 4, 2012" }, + { + "title": "Ivy walls lower with free online classes from Coursera and edX ", + "url": "http://www.csmonitor.com/Innovation/Pioneers/2012/0903/Ivy-walls-lower-with-free-online-classes-from-Coursera-and-edX", + "author": "Chris Gaylord", + "image": "csmonitor_logo_178x138.jpg", + "deck": "", + "publication": "Christian Science Monitor", + "publish_date": "September 3, 2012" + }, { "title": "Into the Future With MOOC's", "url": "http://chronicle.com/article/Into-the-Future-With-MOOCs/134080/", @@ -182,6 +828,15 @@ "publication": "NPR/Radio Boston", "publish_date": "August 20, 2012" }, + { + "title": "LSU urged to adapt to changes in higher ed", + "url": "http://theadvocate.com/csp/mediapool/sites/Advocate/assets/templates/FullStoryPrint.csp?cid=3462091&preview=y", + "author": "Koran Addo", + "image": "theadvocate_logo_178x138.jpg", + "deck": null, + "publication": "The Advocate", + "publish_date": "August 3, 2012" + }, { "title": "Berkeley Joins edX", "url": "http://www.insidehighered.com/quicktakes/2012/07/24/berkeley-joins-edx", @@ -216,7 +871,7 @@ "image": "latimes_logo_178x138.jpeg", "deck": "EdX, founded by Harvard and MIT, will host two not-for-credit UC Berkeley courses this fall.", "publication": "Los Angeles Times", - "publish_date": "July 2012" + "publish_date": "July, 2012" }, { "title": "Berkeley Joins 'EdX' Effort to Offer Free Open Courses", @@ -236,15 +891,6 @@ "publication": "Bloomberg", "publish_date": "July 24, 2012" }, - { - "title": "Free online courses divide UC professors", - "url": "http://www.mercurynews.com/education/ci_21144592", - "author": "Matt Krupnick", - "image": "mercurynews_logo_178x138.jpeg", - "deck": "", - "publication": "Mercury News", - "publish_date": "July 24, 2012" - }, { "title": "UC Berkeley joins edX", "url": "http://news.harvard.edu/gazette/story/2012/07/uc-berkeley-joins-edx/", @@ -270,7 +916,7 @@ "image": "ieee_logo_178x138.jpeg", "deck": "This latest experiment in remote learning is not for a casual audience.", "publication": "IEEE Spectrum", - "publish_date": "July 2012" + "publish_date": "July, 2012" }, { "title": "More universities sign on to free online course initiative", @@ -279,7 +925,7 @@ "image": "univworldnews_logo_178x138.jpeg", "deck": null, "publication": "University World News", - "publish_date": "July 19, 2012 Issue No:231" + "publish_date": "July 19, 2012" }, { "title": "One Course, 150,000 Students", @@ -297,7 +943,7 @@ "image": "mit_logo_178x138.jpeg", "deck": "As the team behind MIT's ambitious online learning program gears up to introduce new courses in the fall, it takes stock of its initial experiences.", "publication": "MIT News", - "publish_date": "7/16/2012" + "publish_date": "July 16, 2012" }, { "title": "Software \"coding\": not just for programmers anymore", @@ -414,7 +1060,7 @@ "image": "mit_logo_178x138.jpeg", "deck": "Answering common questions about MIT and Harvard's new partnership in online education.", "publication": "MIT News", - "publish_date": "May 02, 2012" + "publish_date": "May 2, 2012" }, { "title": "MIT and Harvard announce edX", @@ -423,7 +1069,7 @@ "image": "mit_logo_178x138.jpeg", "deck": "Joint partnership builds on MITx and Harvard distance learning; aims to benefit campus-based education and beyond.", "publication": "MIT News", - "publish_date": "May 02, 2012" + "publish_date": "May 2, 2012" }, { "title": "MIT and Harvard launch a 'revolution in education'", @@ -432,6 +1078,6 @@ "image": "mit_logo_178x138.jpeg", "deck": "Online edX courses will open both universities' classrooms to the world while enhancing on-campus learning.", "publication": "MIT News", - "publish_date": "May 02, 2012" + "publish_date": "May 2, 2012" } ] diff --git a/lms/templates/self_assessment_hint.html b/lms/templates/self_assessment_hint.html new file mode 100644 index 0000000000..64c45b809e --- /dev/null +++ b/lms/templates/self_assessment_hint.html @@ -0,0 +1,7 @@ +
      +
      + ${hint_prompt} +
      + +
      diff --git a/lms/templates/self_assessment_prompt.html b/lms/templates/self_assessment_prompt.html new file mode 100644 index 0000000000..88549e9f56 --- /dev/null +++ b/lms/templates/self_assessment_prompt.html @@ -0,0 +1,20 @@ +
      +
      +
      + ${prompt} +
      + +
      + +
      + +
      ${initial_rubric}
      + +
      ${initial_hint}
      + +
      ${initial_message}
      + + + +
      diff --git a/lms/templates/self_assessment_rubric.html b/lms/templates/self_assessment_rubric.html new file mode 100644 index 0000000000..5bcb3bba93 --- /dev/null +++ b/lms/templates/self_assessment_rubric.html @@ -0,0 +1,15 @@ +
      +
      +

      Self-assess your answer with this rubric:

      + ${rubric} +
      + + % if not read_only: + + % endif + +
      diff --git a/lms/templates/staff_problem_info.html b/lms/templates/staff_problem_info.html index 6d9d1a3a30..0f1893ee4f 100644 --- a/lms/templates/staff_problem_info.html +++ b/lms/templates/staff_problem_info.html @@ -1,6 +1,14 @@ ${module_content} %if edit_link: - +
      + Edit / + QA +
      % endif @@ -50,77 +58,19 @@ category = ${category | h}
      -## leanModal needs to be included here otherwise this breaks when in a - - diff --git a/lms/templates/static_templates/jobs.html b/lms/templates/static_templates/jobs.html index f2b3b69cab..15fcbfcdca 100644 --- a/lms/templates/static_templates/jobs.html +++ b/lms/templates/static_templates/jobs.html @@ -1,5 +1,4 @@ <%namespace name='static' file='../static_content.html'/> - <%inherit file="../main.html" /> <%block name="title">Jobs @@ -31,32 +30,20 @@
      -
      +
      -

      EdX Content Engineer

      -

      Content Engineers support edX Fellows and edX Course Managers in the overall technical development of course content, assessments, and domain-specific online tools. Tasks include developing graders for rich problems, designing automated tools for import of problems from other formats, as well as creating new ways for students to interact with domain-specific problems in the system.

      -

      A candidate must have:

      -
        -
      • Python or JavaScript development experience
      • -
      • A deep interest in pedagogy and education
      • -
      -

      Knowledge of GWT or Backbone.js a plus.

      If you are interested in this position, please send an email to jobs@edx.org.

      -
      -
      -
      -
      -

      Platform Developer

      -

      Platform Developers build the core learning platform that powers edX, writing both front-end and back-end code. They tackle a wide range of technical challenges, and so the best candidates will have a strong background in one or more of the following areas: machine learning, education, user interaction design, big data, social network analysis, and devops. Specialists are encouraged to apply, but team members often wear many hats. Our ideal candidate would have excellent coding skills, a proven history of delivering projects, and a deep research background.

      -

      If you are interested in this position, please send an email to jobs@edx.org

      -
      +

      We're hiring!

      +

      Are you passionate? Want to help change the world? Good, you've found the right company! We're growing and our team needs the best and brightest in creating the next evolution in interactive online education.

      +

      Want to apply to edX?

      +

      Send your resume and cover letter to jobs@edx.org.

      +

      Note: We'll review each and every resume but please note you may not get a response due to the volume of inquiries.

      -

      Positions

      - + + + +

      How to Apply

      E-mail your resume, coverletter and any other materials to jobs@edx.org

      Our Location

      diff --git a/lms/templates/video.html b/lms/templates/video.html index 47556095cb..5c041d5c70 100644 --- a/lms/templates/video.html +++ b/lms/templates/video.html @@ -18,3 +18,9 @@

      Download video here.

      % endif + +% if track: +
      +

      Download subtitles here.

      +
      +% endif diff --git a/lms/urls.py b/lms/urls.py index f26dd7de3c..527f3f858e 100644 --- a/lms/urls.py +++ b/lms/urls.py @@ -10,6 +10,9 @@ if settings.DEBUG: admin.autodiscover() urlpatterns = ('', + # certificate view + + url(r'^update_certificate$', 'certificates.views.update_certificate'), url(r'^$', 'branding.views.index', name="root"), # Main marketing page, or redirect to courseware url(r'^dashboard$', 'student.views.dashboard', name="dashboard"), @@ -26,6 +29,11 @@ urlpatterns = ('', url(r'^reject_name_change$', 'student.views.reject_name_change'), url(r'^pending_name_changes$', 'student.views.pending_name_changes'), + url(r'^testcenter/login$', 'student.views.test_center_login'), + + # url(r'^testcenter/login$', 'student.test_center_views.login'), + # url(r'^testcenter/logout$', 'student.test_center_views.logout'), + url(r'^event$', 'track.views.user_track'), url(r'^t/(?P