Wiki now supports circuits, modulo bugs

This commit is contained in:
Piotr Mitros
2012-01-04 19:00:52 -05:00
parent 510dd854e6
commit 85e8b3a2e9
17 changed files with 191 additions and 9 deletions

0
circuit/__init__.py Normal file
View File

11
circuit/models.py Normal file
View File

@@ -0,0 +1,11 @@
from django.db import models
from django.contrib.auth.models import User
import uuid
class ServerCircuit(models.Model):
# Later, add owner, who can edit, part of what app, etc.
name = models.CharField(max_length=32, unique=True, db_index=True)
schematic = models.TextField(blank=True)
def __unicode__(self):
return self.name+":"+self.schematic[:8]

16
circuit/tests.py Normal file
View File

@@ -0,0 +1,16 @@
"""
This file demonstrates writing tests using the unittest module. These will pass
when you run "manage.py test".
Replace this with more appropriate tests for your application.
"""
from django.test import TestCase
class SimpleTest(TestCase):
def test_basic_addition(self):
"""
Tests that 1 + 1 always equals 2.
"""
self.assertEqual(1 + 1, 2)

64
circuit/views.py Normal file
View File

@@ -0,0 +1,64 @@
from djangomako.shortcuts import render_to_response, render_to_string
from django.shortcuts import redirect
import os
from django.conf import settings
from django.http import Http404
from models import ServerCircuit
import json
import xml.etree.ElementTree
from django.http import HttpResponse
def circuit_line(circuit):
if not circuit.isalnum():
raise Http404()
try:
sc = ServerCircuit.objects.get(name=circuit)
schematic = sc.schematic
print "Got"
except:
schematic = ''
print "not got"
print "X", schematic
circuit_line = xml.etree.ElementTree.Element('input')
circuit_line.set('type', 'hidden')
circuit_line.set('class', 'schematic')
circuit_line.set('width', '640')
circuit_line.set('height', '480')
circuit_line.set('name', 'schematic')
circuit_line.set('id', 'schematic_'+circuit)
circuit_line.set('value', schematic) # We do it this way for security -- guarantees users cannot put funny stuff in schematic.
return xml.etree.ElementTree.tostring(circuit_line)
def edit_circuit(request, circuit):
try:
sc = ServerCircuit.objects.get(name=circuit)
except:
sc = None
if not circuit.isalnum():
raise Http404()
response = render_to_response('edit_circuit.html', {'name':circuit,
'circuit_line':circuit_line(circuit)})
response['Cache-Control'] = 'no-cache'
return response
def save_circuit(request, circuit):
if not circuit.isalnum():
raise Http404()
print dict(request.POST)
schematic = request.POST['schematic']
print schematic
try:
sc = ServerCircuit.objects.get(name=circuit)
except:
sc = ServerCircuit()
sc.name = circuit
sc.schematic = schematic
print ":", sc.schematic
sc.save()
json_str = json.dumps({'results': 'success'})
response = HttpResponse(json_str, mimetype='application/json')
response['Cache-Control'] = 'no-cache'
return response

View File

@@ -116,3 +116,4 @@ if __name__=='__main__':
print evaluator({'a': 2.2997471478310274, 'k': 9, 'm': 8, 'x': 0.66009498411213041}, {}, "5")
print evaluator({},{}, "-1")
print evaluator({},{}, "-(7+5)")
print evaluator({},{}, "QWSEKO")

View File

@@ -162,6 +162,7 @@ class LoncapaModule(XModule):
return json.dumps({"error":"Past due date"})
elif dispatch=='problem_check':
response = self.check_problem(get)
print response
elif dispatch=='problem_reset':
response = self.reset_problem(get)
elif dispatch=='problem_save':
@@ -231,19 +232,27 @@ class LoncapaModule(XModule):
print "cpdr"
raise Http404
self.attempts = self.attempts + 1
self.lcp.done=True
answers=dict()
# input_resistor_1 ==> resistor_1
for key in get:
answers['_'.join(key.split('_')[1:])]=get[key]
correct_map = self.lcp.grade_answers(answers)
try:
ocm = lcp.correct_map
oa = lcp.answers
correct_map = self.lcp.grade_answers(answers)
except:
lcp.correct_map = ocm # HACK: Reset state
lcp.answers = oa
return json.dumps({'success':'syntax'})
success = True
self.attempts = self.attempts + 1
self.lcp.done=True
success = 'finished'
for i in correct_map:
if correct_map[i]!='correct':
success = False
success = 'errors'
js=json.dumps({'correct_map' : correct_map,
'success' : success})

View File

@@ -6,7 +6,8 @@ from xml.dom.minidom import parse, parseString
from calc import evaluator
def strip_dict(d):
''' Takes a dict. Returns an identical dict, with all non-word keys stripped out. '''
''' Takes a dict. Returns an identical dict, with all non-word
keys stripped out. '''
d=dict([(k, float(d[k])) for k in d if type(k)==str and \
k.isalnum() and \
(type(d[k]) == float or type(d[k]) == int) ])

View File

@@ -107,6 +107,7 @@ INSTALLED_APPS = (
'staticbook',
'simplewiki',
'track',
'circuit',
# Uncomment the next line to enable the admin:
# 'django.contrib.admin',
# Uncomment the next line to enable admin documentation:
@@ -192,7 +193,7 @@ if ASKBOT_ENABLED:
'south',
'askbot.deps.livesettings',
'askbot',
'keyedcache',
#'keyedcache', # TODO: Main askbot tree has this installed, but we get intermittent errors if we include it.
'robots',
'django_countries',
'djcelery',

View File

@@ -1,3 +1,5 @@
# Source: django-simplewiki. GPL license.
import sys, os
# allow mdx_* parsers to be just dropped in the simplewiki folder

View File

@@ -1,3 +1,5 @@
# Source: django-simplewiki. GPL license.
from django.contrib import admin
from django import forms
from django.utils.translation import ugettext as _
@@ -56,4 +58,4 @@ class PermissionAdmin(admin.ModelAdmin):
admin.site.register(Article, ArticleAdmin)
admin.site.register(Revision, RevisionAdmin)
admin.site.register(Permission, PermissionAdmin)
admin.site.register(ArticleAttachment, AttachmentAdmin)
admin.site.register(ArticleAttachment, AttachmentAdmin)

View File

@@ -1,5 +1,7 @@
#!/usr/bin/env python
print "Hello"
'''
WikiLink Extention for Python-Markdown
======================================

43
simplewiki/mdx_circuit.py Normal file
View File

@@ -0,0 +1,43 @@
#!/usr/bin/env python
'''
Image Circuit Extension for Python-Markdown
======================================
circuit:name becomes the circuit.
'''
import simplewiki.settings as settings
import markdown
from markdown import etree_loader
from djangomako.shortcuts import render_to_response, render_to_string
ElementTree=etree_loader.importETree()
class CircuitExtension(markdown.Extension):
def __init__(self, configs):
for key, value in configs :
self.setConfig(key, value)
def add_inline(self, md, name, klass, re):
pattern = klass(re)
pattern.md = md
pattern.ext = self
md.inlinePatterns.add(name, pattern, "<reference")
def extendMarkdown(self, md, md_globals):
print "Here"
self.add_inline(md, 'circuit', CircuitLink, r'^circuit:(?P<name>[a-zA-Z0-9]*)$')
class CircuitLink(markdown.inlinepatterns.Pattern):
def handleMatch(self, m):
name = m.group('name')
if not name.isalnum():
return ElementTree.fromstring("<div>Circuit name must be alphanumeric</div>")
return ElementTree.fromstring(render_to_string('show_circuit.html', {'name':name}))
def makeExtension(configs=None) :
print "Here"
return CircuitExtension(configs=configs)

View File

@@ -1,5 +1,7 @@
# Source: https://github.com/mayoff/python-markdown-mathjax
print "Hello"
import markdown
class MathJaxPattern(markdown.inlinepatterns.Pattern):

View File

@@ -247,6 +247,7 @@ class Revision(models.Model):
# Create pre-parsed contents - no need to parse on-the-fly
ext = WIKI_MARKDOWN_EXTENSIONS
print "Waka", WIKI_MARKDOWN_EXTENSIONS
ext += ["wikilinks(base_url=%s/)" % reverse('wiki_view', args=('',))]
self.contents_parsed = markdown(self.contents,
extensions=ext,

View File

@@ -91,9 +91,10 @@ WIKI_MARKDOWN_EXTENSIONS = getattr(settings, 'SIMPLE_WIKI_MARKDOWN_EXTENSIONS',
'mathjax',
'camelcase', # CamelCase-style wikilinks
'video', # In-line embedding for YouTube, etc.
#'image' # In-line embedding for images - too many bugs. It has a failed REG EXP.
'circuit'
])
print WIKI_MARKDOWN_EXTENSIONS
WIKI_IMAGE_EXTENSIONS = getattr(settings,
'SIMPLE_WIKI_IMAGE_EXTENSIONS',

View File

@@ -9,6 +9,11 @@
<link rel="stylesheet" href="/static/css/local.css" type="text/css" media="all" />
<link href="/static/css/jquery-ui-1.8.16.custom.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="/static/simplewiki/js/bsn.AutoSuggest_c_2.0.js"></script>
<script type="text/javascript" src="/static/js/schematic.js"></script>
<script type="text/javascript" src="/static/lib/jquery-1.6.2.min.js"></script>
<script type="text/javascript" src="/static/js/video_player.js"></script>
<script type="text/javascript">
function set_related_article_id(s) {
document.getElementById('wiki_related_input_id').value = s.id;
@@ -35,6 +40,24 @@
displayMath: [ ['$$','$$'], ["\\[","\\]"]]}
});
</script> <script type="text/javascript" src="/static/lib/mathjax/MathJax.js?config=TeX-AMS_HTML-full"></script>
<script>
$(function(){
$.ajaxSetup ({
// Disable caching of AJAX responses
cache: false
});
$(".div_wiki_circuit").each(function(d,e) {
id = $(this).attr("id");
name = id.substring(17);
//alert(name);
$("#"+id).load("/edit_circuit/"+name);
f=this;
});
update_schematics();});
</script>
{% block wiki_head %}
{% endblock %}
</head>

View File

@@ -37,6 +37,9 @@ urlpatterns = ('',
name='auth_password_reset_complete'),
url(r'^password_reset_done/$',django.contrib.auth.views.password_reset_done,
name='auth_password_reset_done'),
# url(r'^show_circuit/(?P<circuit>[^/]*)$', 'circuit.views.show_circuit'),
url(r'^edit_circuit/(?P<circuit>[^/]*)$', 'circuit.views.edit_circuit'),
url(r'^save_circuit/(?P<circuit>[^/]*)$', 'circuit.views.save_circuit'),
)
if settings.ASKBOT_ENABLED: