<commit_before>from __future__ import with_statement
import re
import tokenize
from token import *
import random
from pprint import pformat
from json import loads as fromJS, dumps as toJS
from cgi import escape
from datetime import datetime, time
from threading import enumerate as threads

from rorn.Box import ErrorBox, SuccessBox
from rorn.Session import sessions, delay, undelay
from rorn.ResponseWriter import ResponseWriter
from rorn.code import highlightCode

from DB import db, DiskQueue
from Privilege import Privilege, admin as requireAdmin, defaults as privDefaults
from Project import Project
from User import User
from Button import Button
from Table import LRTable
from Cron import Cron
from LoadValues import getLoadtime, setDevMode
from Log import LogEntry, log
from Settings import settings
from Event import Event
from Lock import locks
from relativeDates import timesince
from utils import *

pages = []
def admin(url, name, icon):
	def wrap(f):
		pages.append({'url': url, 'name': name, 'icon': icon})
		return get(url)(f)
	return wrap

@get('admin')
def adminIndex(handler, request):
	handler.title('Admin')
	requireAdmin(handler)

	for page in pages:
		print "<div class=\"admin-list-entry\"><a href=\"%(url)s\"><img class=\"admin-icon\" src=\"/static/images/admin-%(icon)s.png\"></a><br>%(name)s</div>" % page

@admin('admin/info', 'Information', 'info')
def adminInfo(handler, request):
	handler.title('Information')
	requireAdmin(handler)

	print """
<style type="text/css">
table {
    border-color: #000;
    border-collapse: collapse
}
table tr th {
    background-color: #ccc;
}

table tr td.center {
    text-align: center;
}
</style>
"""

	print "<h3>Uptime</h3>"
	loadTime = getLoadtime()
	print "Started %s<br>" % loadTime
	print "Up for %s<br>" % timesince(loadTime)

	print "<h3>Database</h3>"
	print "Writing to memory; mirroring to disk every %d seconds / %d writes<br>" % (DiskQueue.PERIOD, DiskQueue.SIZE)
	print "Current queue size: %d<br>" % db().diskQueue.size
	print "Last sync: %s (%s ago)<br>" % (db().diskQueue.lastFlush, pluralize(int((datetime.now() - db().diskQueue.lastFlush).total_seconds()), 'second', 'seconds'))
	print "Disk writes: %d<br>" % db().counts['flush']
	print "Total requests: %d" % db().counts['total']

	print "<h3>Threads</h3>"
	print "<table border=\"1\" cellspacing=\"0\" cellpadding=\"4\">"
	print "<tr><th>ID</th><th>Name</th><th>Alive</th><th>Daemon</th></tr>"
	for thread in threads():
		print "<tr><td>%s</td><td>%s</td><td class=\"center\"><img src=\"/static/images/%s.png\"></td><td class=\"center\"><img src=\"/static/images/%s.png\"></td></tr>" % (thread.ident, thread.name, 'tick' if thread.isAlive() else 'cross', 'tick' if thread.daemon else 'cross')
	print "</table>"

	print "<h3>Locks</h3>"
	print "<table border=\"1\" cellspacing=\"0\" cellpadding=\"4\">"
	print "<tr><th>Name</th><th>Available</th><th>Reentrant</th></tr>"
	for (name, lock) in locks.iteritems():
		print "<tr><td>%s</td><td class=\"center\"><img src=\"/static/images/%s.png\"></td><td class=\"center\"><img src=\"/static/images/%s.png\"></td></tr>" % (name, 'tick' if lock.avail() else 'cross', 'tick' if lock.reentrant() else 'cross')
	print "</table>"

@admin('admin/test', 'Test pages', 'test-pages')
def adminTest(handler, request):
	handler.title('Test pages')
	requireAdmin(handler)

	with open('handlers/test.py') as f:
		found = 0
		for token, tokString, tokStart, tokEnd, line in tokenize.generate_tokens(f.readline):
			if token == OP and tokString == '@':
				found = 1
			elif token == NEWLINE:
				found = 0
			elif token == NAME and tokString == 'get' and found == 1:
				found = 2
			elif token == STRING and found == 2:
				tokString = tokString.replace("'", "")
				print "<a href=\"/%s\">%s</a><br>" % (tokString, stripTags(tokString))
				found = 0

@admin('admin/settings', 'Settings', 'settings')
def adminSettings(handler, request):
	handler.title('Settings')
	requireAdmin(handler)
	undelay(handler)

	print "<style type=\"text/css\">"
	print "table.list td.right > * {width: 400px;}"
	print "table.list td.right button {width: 200px;}" # Half of the above value
	print "table.list tr td:first-of-type {font-weight: bold;}"
	print "</style>"

	print "<h3>Mutable settings</h3>"
	print "<form method=\"post\" action=\"/admin/settings\">"
	print "<table class=\"list\">"
	print "<tr><td class=\"left\">E-mail domain:</td><td class=\"right\"><input type=\"text\" name=\"emailDomain\" value=\"%s\"></td></tr>" % settings.emailDomain
	print "<tr><td class=\"left\">System message:</td><td class=\"right\"><input type=\"text\" name=\"systemMessage\" value=\"%s\"></td></tr>" % (settings.systemMessage or '')
	print "<tr><td class=\"left\">Bugzilla URL:</td><td class=\"right\"><input type=\"text\" name=\"bugzillaURL\" value=\"%s\"></td></tr>" % (settings.bugzillaURL or '')
	print "<tr><td class=\"left\">Redis host:</td><td class=\"right\"><input type=\"text\" name=\"redis\" value=\"%s\"></td></tr>" % (settings.redis or '')
	print "<tr><td class=\"left\">Kerberos realm:</td><td class=\"right\"><input type=\"text\" name=\"kerberosRealm\" value=\"%s\"></td></tr>" % (settings.kerberosRealm or '')
	print "<tr><td class=\"left\">&nbsp;</td><td class=\"right\">"
	print Button('Save', id = 'save-button', type = 'submit').positive()<commit_msg>Escape quotes on settings page<commit_after>from __future__ import with_statement
import re
import tokenize
from token import *
import random
from pprint import pformat
from json import loads as fromJS, dumps as toJS
from cgi import escape
from datetime import datetime, time
from threading import enumerate as threads

from rorn.Box import ErrorBox, SuccessBox
from rorn.Session import sessions, delay, undelay
from rorn.ResponseWriter import ResponseWriter
from rorn.code import highlightCode

from DB import db, DiskQueue
from Privilege import Privilege, admin as requireAdmin, defaults as privDefaults
from Project import Project
from User import User
from Button import Button
from Table import LRTable
from Cron import Cron
from LoadValues import getLoadtime, setDevMode
from Log import LogEntry, log
from Settings import settings
from Event import Event
from Lock import locks
from relativeDates import timesince
from utils import *

pages = []
def admin(url, name, icon):
	def wrap(f):
		pages.append({'url': url, 'name': name, 'icon': icon})
		return get(url)(f)
	return wrap

@get('admin')
def adminIndex(handler, request):
	handler.title('Admin')
	requireAdmin(handler)

	for page in pages:
		print "<div class=\"admin-list-entry\"><a href=\"%(url)s\"><img class=\"admin-icon\" src=\"/static/images/admin-%(icon)s.png\"></a><br>%(name)s</div>" % page

@admin('admin/info', 'Information', 'info')
def adminInfo(handler, request):
	handler.title('Information')
	requireAdmin(handler)

	print """
<style type="text/css">
table {
    border-color: #000;
    border-collapse: collapse
}
table tr th {
    background-color: #ccc;
}

table tr td.center {
    text-align: center;
}
</style>
"""

	print "<h3>Uptime</h3>"
	loadTime = getLoadtime()
	print "Started %s<br>" % loadTime
	print "Up for %s<br>" % timesince(loadTime)

	print "<h3>Database</h3>"
	print "Writing to memory; mirroring to disk every %d seconds / %d writes<br>" % (DiskQueue.PERIOD, DiskQueue.SIZE)
	print "Current queue size: %d<br>" % db().diskQueue.size
	print "Last sync: %s (%s ago)<br>" % (db().diskQueue.lastFlush, pluralize(int((datetime.now() - db().diskQueue.lastFlush).total_seconds()), 'second', 'seconds'))
	print "Disk writes: %d<br>" % db().counts['flush']
	print "Total requests: %d" % db().counts['total']

	print "<h3>Threads</h3>"
	print "<table border=\"1\" cellspacing=\"0\" cellpadding=\"4\">"
	print "<tr><th>ID</th><th>Name</th><th>Alive</th><th>Daemon</th></tr>"
	for thread in threads():
		print "<tr><td>%s</td><td>%s</td><td class=\"center\"><img src=\"/static/images/%s.png\"></td><td class=\"center\"><img src=\"/static/images/%s.png\"></td></tr>" % (thread.ident, thread.name, 'tick' if thread.isAlive() else 'cross', 'tick' if thread.daemon else 'cross')
	print "</table>"

	print "<h3>Locks</h3>"
	print "<table border=\"1\" cellspacing=\"0\" cellpadding=\"4\">"
	print "<tr><th>Name</th><th>Available</th><th>Reentrant</th></tr>"
	for (name, lock) in locks.iteritems():
		print "<tr><td>%s</td><td class=\"center\"><img src=\"/static/images/%s.png\"></td><td class=\"center\"><img src=\"/static/images/%s.png\"></td></tr>" % (name, 'tick' if lock.avail() else 'cross', 'tick' if lock.reentrant() else 'cross')
	print "</table>"

@admin('admin/test', 'Test pages', 'test-pages')
def adminTest(handler, request):
	handler.title('Test pages')
	requireAdmin(handler)

	with open('handlers/test.py') as f:
		found = 0
		for token, tokString, tokStart, tokEnd, line in tokenize.generate_tokens(f.readline):
			if token == OP and tokString == '@':
				found = 1
			elif token == NEWLINE:
				found = 0
			elif token == NAME and tokString == 'get' and found == 1:
				found = 2
			elif token == STRING and found == 2:
				tokString = tokString.replace("'", "")
				print "<a href=\"/%s\">%s</a><br>" % (tokString, stripTags(tokString))
				found = 0

@admin('admin/settings', 'Settings', 'settings')
def adminSettings(handler, request):
	handler.title('Settings')
	requireAdmin(handler)
	undelay(handler)

	print "<style type=\"text/css\">"
	print "table.list td.right > * {width: 400px;}"
	print "table.list td.right button {width: 200px;}" # Half of the above value
	print "table.list tr td:first-of-type {font-weight: bold;}"
	print "</style>"

	def quot(str): return str.replace('"', '&quot;')

	print "<h3>Mutable settings</h3>"
	print "<form method=\"post\" action=\"/admin/settings\">"
	print "<table class=\"list\">"
	print "<tr><td class=\"left\">E-mail domain:</td><td class=\"right\"><input type=\"text\" name=\"emailDomain\" value=\"%s\"></td></tr>" % quot(settings.emailDomain)
	print "<tr><td class=\"left\">System message:</td><td class=\"right\"><input type=\"text\" name=\"systemMessage\" value=\"%s\"></td></tr>" % quot(settings.systemMessage or '')
	print "<tr><td class=\"left\">Bugzilla URL:</td><td class=\"right\"><input type=\"text\" name=\"bugzillaURL\" value=\"%s\"></td></tr>" % quot(settings.bugzillaURL or '')
	print "<tr><td class=\"left\">Redis host:</td><td class=\"right\"><input type=\"text\" name=\"redis\" value=\"%s\"></td></tr>" % quot(settings.redis or '')
	print "<tr><td class=\"left\">Kerberos realm:</td><td class=\"right\"><input type=\"text\" name=\"kerberosRealm\" value=\"%s\"></td></tr>" % quot(settings.kerberosRealm or '')
	print "<tr><td class=\"left\">&nbsp;</td><td class=\"right\">"
	print Button('Save', id = 'save-button', type = 'submit').positive()
{'fraction_non_alphanumeric': 0.2032823573293547, 'fraction_numerical': 0.005967922417008579, 'mean_word_length': 4.941828254847645, 'pattern_counts': {'":': 0, '<': 231, '<?xml version=': 0, '>': 233, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2177113', 'n_tokens_mistral': 3645, 'n_tokens_neox': 3509, 'n_words': 956}