Merge remote-tracking branch 'origin/master' into spark_web_fixes

This commit is contained in:
John Donaldson 2018-10-02 12:41:13 -05:00
commit 0fedbbcf7d
24 changed files with 924 additions and 1074 deletions

View File

@ -5,4 +5,5 @@ RUN go build -o /mothd /src/*.go
FROM alpine
COPY --from=builder /mothd /mothd
COPY theme /theme
ENTRYPOINT [ "/mothd" ]

View File

@ -1,7 +1,13 @@
FROM alpine
FROM alpine:3.7
RUN apk --no-cache add python3 py3-pillow && \
pip3 install aiohttp
RUN apk --no-cache add \
gcc \
musl-dev \
python3 \
python3-dev \
py3-pillow \
&& \
pip3 install aiohttp
COPY . /moth/
COPY example-puzzles /puzzles/

View File

@ -4,6 +4,7 @@ set -e
version=$(date +%Y%m%d%H%M)
cd $(dirname $0)
for img in moth moth-devel; do
echo "==== $img"
sudo docker build --build-arg http_proxy=$http_proxy --build-arg https_proxy=$https_proxy --tag dirtbags/$img --tag dirtbags/$img:$version -f Dockerfile.$img .

View File

@ -1,6 +1,7 @@
#!/usr/bin/python3
import asyncio
import cgitb
import glob
import html
from aiohttp import web
@ -15,11 +16,12 @@ import shutil
import socketserver
import sys
import traceback
import mothballer
sys.dont_write_bytecode = True # Don't write .pyc files
def mkseed():
return bytes(random.choice(b'abcdef0123456789') for i in range(40))
return bytes(random.choice(b'abcdef0123456789') for i in range(40)).decode('ascii')
class Page:
def __init__(self, title, depth=0):
@ -72,11 +74,17 @@ async def handle_front(request):
return p.response(request)
async def handle_puzzlelist(request):
seed = request.query.get("seed", mkseed())
p = Page("Puzzle Categories", 1)
p.write("<p>seed = {}</p>".format(seed))
p.write("<ul>")
for i in sorted(glob.glob(os.path.join(request.app["puzzles_dir"], "*", ""))):
bn = os.path.basename(i.strip('/\\'))
p.write('<li><a href="{}/">puzzles/{}/</a></li>'.format(bn, bn))
p.write("<li>")
p.write("<a href=\"../mothballer/{cat}?seed={seed}\" class=\"download\" title=\"download mothball\">[mb]</a>".format(cat=bn, seed=seed))
p.write(" ")
p.write("<a href=\"{cat}/?seed={seed}\">{cat}</a>".format(cat=bn, seed=seed))
p.write("</li>")
p.write("</ul>")
return p.response(request)
@ -137,7 +145,7 @@ async def handle_puzzle(request):
return p.response(request)
async def handle_puzzlefile(request):
seed = request.query.get("seed", mkseed())
seed = request.query.get("seed", mkseed()).encode('ascii')
category = request.match_info.get("category")
points = int(request.match_info.get("points"))
filename = request.match_info.get("filename")
@ -158,6 +166,25 @@ async def handle_puzzlefile(request):
resp.body = file.stream.read()
return resp
async def handle_mothballer(request):
seed = request.query.get("seed", mkseed())
category = request.match_info.get("category")
try:
catdir = os.path.join(request.app["puzzles_dir"], category)
mb = mothballer.package(category, catdir, seed)
except:
body = cgitb.html(sys.exc_info())
resp = web.Response(text=body, content_type="text/html")
return resp
mb_buf = mb.read()
resp = web.Response(
body=mb_buf,
headers={"Content-Disposition": "attachment; filename={}.mb".format(category)},
content_type="application/octet_stream",
)
return resp
if __name__ == '__main__':
import argparse
@ -192,5 +219,6 @@ if __name__ == '__main__':
app.router.add_route("GET", "/puzzles/{category}/", handle_category)
app.router.add_route("GET", "/puzzles/{category}/{points}/", handle_puzzle)
app.router.add_route("GET", "/puzzles/{category}/{points}/{filename}", handle_puzzlefile)
app.router.add_route("GET", "/mothballer/{category}", handle_mothballer)
app.router.add_static("/files/", mydir, show_index=True)
web.run_app(app, host=addr, port=port)

View File

@ -4,6 +4,7 @@ import argparse
import contextlib
import glob
import hashlib
import html
import io
import importlib.machinery
import mistune
@ -244,7 +245,7 @@ class Puzzle:
self.body.write(' ')
self.body.write(' '.join(hexes[8:]))
self.body.write(' |')
self.body.write(''.join(chars))
self.body.write(html.escape(''.join(chars)))
self.body.write('|\n')
offset += len(chars)
self.body.write('{:08x}\n'.format(offset))

176
devel/mothballer.py Executable file
View File

@ -0,0 +1,176 @@
#!/usr/bin/env python3
import argparse
import binascii
import hashlib
import io
import json
import logging
import moth
import os
import shutil
import tempfile
import zipfile
SEEDFN = "SEED"
def write_kv_pairs(ziphandle, filename, kv):
""" Write out a sorted map to file
:param ziphandle: a zipfile object
:param filename: The filename to write within the zipfile object
:param kv: the map to write out
:return:
"""
filehandle = io.StringIO()
for key in sorted(kv.keys()):
if isinstance(kv[key], list):
for val in kv[key]:
filehandle.write("%s %s\n" % (key, val))
else:
filehandle.write("%s %s\n" % (key, kv[key]))
filehandle.seek(0)
ziphandle.writestr(filename, filehandle.read())
def escape(s):
return s.replace('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;')
def generate_html(ziphandle, puzzle, puzzledir, category, points, authors, files):
html_content = io.StringIO()
file_content = io.StringIO()
if files:
file_content.write(
''' <section id="files">
<h2>Associated files:</h2>
<ul>
''')
for fn in files:
file_content.write(' <li><a href="{fn}">{efn}</a></li>\n'.format(fn=fn, efn=escape(fn)))
file_content.write(
''' </ul>
</section>
''')
scripts = ['<script src="{}"></script>'.format(s) for s in puzzle.scripts]
html_content.write(
'''<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<title>{category} {points}</title>
<link rel="stylesheet" href="../../style.css">
{scripts}
</head>
<body>
<h1>{category} for {points} points</h1>
<section id="readme">
{body} </section>
{file_content} <section id="form">
<form id="puzzler" action="../../cgi-bin/puzzler.cgi" method="get" accept-charset="utf-8" autocomplete="off">
<input type="hidden" name="c" value="{category}">
<input type="hidden" name="p" value="{points}">
<div>Team hash:<input name="t" size="8"></div>
<div>Answer:<input name="a" id="answer" size="20"></div>
<input type="submit" value="submit">
</form>
</section>
<address>Puzzle by <span class="authors" data-handle="{authors}">{authors}</span></address>
</body>
</html>'''.format(
category=category,
points=points,
body=puzzle.html_body(),
file_content=file_content.getvalue(),
authors=', '.join(authors),
scripts='\n'.join(scripts),
)
)
ziphandle.writestr(os.path.join(puzzledir, 'index.html'), html_content.getvalue())
def build_category(categorydir, outdir):
category_seed = binascii.b2a_hex(os.urandom(20))
categoryname = os.path.basename(categorydir.strip(os.sep))
zipfilename = os.path.join(outdir, "%s.mb" % categoryname)
logging.info("Building {} from {}".format(zipfilename, categorydir))
if os.path.exists(zipfilename):
# open and gather some state
existing = zipfile.ZipFile(zipfilename, 'r')
try:
category_seed = existing.open(SEEDFN).read().strip()
except Exception:
pass
existing.close()
logging.debug("Using PRNG seed {}".format(category_seed))
zipfileraw = tempfile.NamedTemporaryFile(delete=False)
mothball = package(categoryname, categorydir, category_seed)
shutil.copyfileobj(mothball, zipfileraw)
zipfileraw.close()
shutil.move(zipfileraw.name, zipfilename)
# Returns a file-like object containing the contents of the new zip file
def package(categoryname, categorydir, seed):
zfraw = io.BytesIO()
zf = zipfile.ZipFile(zfraw, 'x')
zf.writestr("category_seed.txt", seed)
cat = moth.Category(categorydir, seed)
mapping = {}
answers = {}
summary = {}
for puzzle in cat:
logging.info("Processing point value {}".format(puzzle.points))
hashmap = hashlib.sha1(seed.encode('utf-8'))
hashmap.update(str(puzzle.points).encode('utf-8'))
puzzlehash = hashmap.hexdigest()
mapping[puzzle.points] = puzzlehash
answers[puzzle.points] = puzzle.answers
summary[puzzle.points] = puzzle.summary
puzzledir = os.path.join('content', puzzlehash)
files = []
for fn, f in puzzle.files.items():
if f.visible:
files.append(fn)
payload = f.stream.read()
zf.writestr(os.path.join(puzzledir, fn), payload)
puzzledict = {
'authors': puzzle.authors,
'hashes': puzzle.hashes(),
'files': files,
'body': puzzle.html_body(),
}
puzzlejson = json.dumps(puzzledict)
zf.writestr(os.path.join(puzzledir, 'puzzle.json'), puzzlejson)
generate_html(zf, puzzle, puzzledir, categoryname, puzzle.points, puzzle.get_authors(), files)
write_kv_pairs(zf, 'map.txt', mapping)
write_kv_pairs(zf, 'answers.txt', answers)
write_kv_pairs(zf, 'summaries.txt', summary)
# clean up
zf.close()
zfraw.seek(0)
return zfraw
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Build a category package')
parser.add_argument('outdir', help='Output directory')
parser.add_argument('categorydirs', nargs='+', help='Directory of category source')
args = parser.parse_args()
logging.basicConfig(level=logging.DEBUG)
for categorydir in args.categorydirs:
build_category(categorydir, args.outdir)

View File

@ -98,7 +98,7 @@ def build_category(categorydir, outdir):
categoryname = os.path.basename(categorydir.strip(os.sep))
seedfn = os.path.join("category_seed.txt")
zipfilename = os.path.join(outdir, "%s.zip" % categoryname)
zipfilename = os.path.join(outdir, "%s.mb" % categoryname)
logging.info("Building {} from {}".format(zipfilename, categorydir))
if os.path.exists(zipfilename):

View File

@ -51,6 +51,8 @@ window.addEventListener("load", init);
<li>William Phillips</li>
<li>Jeremy Hefner</li>
<li>James Wernicke</li>
<li>Clark Taylor</li>
<li>John Donaldson</li>
</ul>
<p>

View File

@ -13,11 +13,11 @@ import (
)
type JSend struct {
Status string `json:"status"`
Data JSendData `json:"data"`
Status string `json:"status"`
Data JSendData `json:"data"`
}
type JSendData struct {
Short string `json:"short"`
Short string `json:"short"`
Description string `json:"description"`
}
@ -27,7 +27,7 @@ func ShowJSend(w http.ResponseWriter, status Status, short string, description s
resp := JSend{
Status: "success",
Data: JSendData{
Short: short,
Short: short,
Description: description,
},
}
@ -41,16 +41,24 @@ func ShowJSend(w http.ResponseWriter, status Status, short string, description s
}
respBytes, err := json.Marshal(resp)
if (err != nil) {
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK) // RFC2616 makes it pretty clear that 4xx codes are for the user-agent
w.Write(respBytes)
}
type Status int
const (
Success = iota
Fail
Error
)
// ShowHtml delevers an HTML response to w
func ShowHtml(w http.ResponseWriter, status Status, title string, body string) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
@ -333,7 +341,29 @@ func (ctx *Instance) contentHandler(w http.ResponseWriter, req *http.Request) {
}
func (ctx *Instance) staticHandler(w http.ResponseWriter, req *http.Request) {
ServeStatic(w, req, ctx.ResourcesDir)
path := req.URL.Path
if strings.Contains(path, "..") {
http.Error(w, "Invalid URL path", http.StatusBadRequest)
return
}
if path == "/" {
path = "/index.html"
}
f, err := os.Open(ctx.ResourcePath(path))
if err != nil {
http.NotFound(w, req)
return
}
defer f.Close()
d, err := f.Stat()
if err != nil {
http.NotFound(w, req)
return
}
http.ServeContent(w, req, path, d.ModTime(), f)
}
func (ctx *Instance) BindHandlers(mux *http.ServeMux) {

View File

@ -93,6 +93,11 @@ func (ctx *Instance) StatePath(parts ...string) string {
return path.Join(ctx.StateDir, tail)
}
func (ctx *Instance) ResourcePath(parts ...string) string {
tail := path.Join(parts...)
return path.Join(ctx.ResourcesDir, tail)
}
func (ctx *Instance) PointsLog() []*Award {
var ret []*Award

View File

@ -208,7 +208,7 @@ func (ctx *Instance) isEnabled() bool {
log.Print("Suspended: disabled file found")
return false
}
untilspec, err := ioutil.ReadFile(ctx.StatePath("until"))
if err == nil {
untilspecs := strings.TrimSpace(string(untilspec))

View File

@ -27,18 +27,18 @@ func main() {
)
mothballDir := flag.String(
"mothballs",
"/moth/mothballs",
"/mothballs",
"Path to read mothballs",
)
stateDir := flag.String(
"state",
"/moth/state",
"/state",
"Path to write state",
)
resourcesDir := flag.String(
"resources",
"/moth/resources",
"Path to static resources (HTML, images, css, ...)",
themeDir := flag.String(
"theme",
"/theme",
"Path to static theme resources (HTML, images, css, ...)",
)
maintenanceInterval := flag.Duration(
"maint",
@ -56,7 +56,7 @@ func main() {
log.Fatal(err)
}
ctx, err := NewInstance(*base, *mothballDir, *stateDir, *resourcesDir)
ctx, err := NewInstance(*base, *mothballDir, *stateDir, *themeDir)
if err != nil {
log.Fatal(err)
}

View File

@ -1,435 +0,0 @@
package main
import (
"fmt"
"net/http"
"os"
"path/filepath"
"strings"
)
type Status int
const (
Success = iota
Fail
Error
)
// staticStylesheet serves up a basic stylesheet.
// This is designed to be usable on small touchscreens (like mobile phones)
func staticStylesheet(w http.ResponseWriter) {
w.Header().Set("Content-Type", "text/css")
w.WriteHeader(http.StatusOK)
fmt.Fprint(
w,
`
/* http://paletton.com/#uid=63T0u0k7O9o3ouT6LjHih7ltq4c */
body {
font-family: sans-serif;
max-width: 40em;
background: #282a33;
color: #f6efdc;
}
a:any-link {
color: #8b969a;
}
h1 {
background: #5e576b;
color: #9e98a8;
}
.Fail, .Error {
background: #3a3119;
color: #ffcc98;
}
.Fail:before {
content: "Fail: ";
}
.Error:before {
content: "Error: ";
}
p {
margin: 1em 0em;
}
form, pre {
margin: 1em;
}
input {
padding: 0.6em;
margin: 0.2em;
}
nav {
border: solid black 2px;
}
nav ul, .category ul {
padding: 1em;
}
nav li, .category li {
display: inline;
margin: 1em;
}
iframe#body {
border: inherit;
width: 100%;
}
img {
max-width: 100%;
}
#scoreboard {
width: 100%;
position: relative;
}
#scoreboard span {
font-size: 75%;
display: inline-block;
overflow: hidden;
height: 1.7em;
}
#scoreboard span.teamname {
font-size: inherit;
color: white;
text-shadow: 0 0 3px black;
opacity: 0.8;
position: absolute;
right: 0.2em;
}
#scoreboard div * {white-space: nowrap;}
.cat0, .cat8, .cat16 {background-color: #a6cee3; color: black;}
.cat1, .cat9, .cat17 {background-color: #1f78b4; color: white;}
.cat2, .cat10, .cat18 {background-color: #b2df8a; color: black;}
.cat3, .cat11, .cat19 {background-color: #33a02c; color: white;}
.cat4, .cat12, .cat20 {background-color: #fb9a99; color: black;}
.cat5, .cat13, .cat21 {background-color: #e31a1c; color: white;}
.cat6, .cat14, .cat22 {background-color: #fdbf6f; color: black;}
.cat7, .cat15, .cat23 {background-color: #ff7f00; color: black;}
`,
)
}
// staticIndex serves up a basic landing page
func staticIndex(w http.ResponseWriter) {
ShowHtml(
w, Success,
"Welcome",
`
<h2>Register your team</h2>
<form action="register" action="post">
Team ID: <input name="id"> <br>
Team name: <input name="name">
<input type="submit" value="Register">
</form>
<p>
If someone on your team has already registered,
proceed to the
<a href="puzzles.html">puzzles overview</a>.
</p>
`,
)
}
func staticScoreboard(w http.ResponseWriter) {
ShowHtml(
w, Success,
"Scoreboard",
`
<div id="scoreboard"></div>
<script>
function loadJSON(url, callback) {
function loaded(e) {
callback(e.target.response);
}
var xhr = new XMLHttpRequest()
xhr.onload = loaded;
xhr.open("GET", url, true);
xhr.responseType = "json";
xhr.send();
}
function scoreboard(element, continuous) {
function update(state) {
var teamnames = state["teams"];
var pointslog = state["points"];
var pointshistory = JSON.parse(localStorage.getItem("pointshistory")) || [];
if (pointshistory.length >= 20){
pointshistory.shift();
}
pointshistory.push(pointslog);
localStorage.setItem("pointshistory", JSON.stringify(pointshistory));
var highscore = {};
var teams = {};
// Dole out points
for (var i in pointslog) {
var entry = pointslog[i];
var timestamp = entry[0];
var teamhash = entry[1];
var category = entry[2];
var points = entry[3];
var team = teams[teamhash] || {__hash__: teamhash};
// Add points to team's points for that category
team[category] = (team[category] || 0) + points;
// Record highest score in a category
highscore[category] = Math.max(highscore[category] || 0, team[category]);
teams[teamhash] = team;
}
// Sort by team score
function teamScore(t) {
var score = 0;
for (var category in highscore) {
score += (t[category] || 0) / highscore[category];
}
// XXX: This function really shouldn't have side effects.
t.__score__ = score;
return score;
}
function teamCompare(a, b) {
return teamScore(a) - teamScore(b);
}
var winners = [];
for (var i in teams) {
winners.push(teams[i]);
}
if (winners.length == 0) {
// No teams!
return;
}
winners.sort(teamCompare);
winners.reverse();
// Clear out the element we're about to populate
while (element.lastChild) {
element.removeChild(element.lastChild);
}
// Populate!
var topActualScore = winners[0].__score__;
// (100 / ncats) * (ncats / topActualScore);
var maxWidth = 100 / topActualScore;
for (var i in winners) {
var team = winners[i];
var row = document.createElement("div");
var ncat = 0;
for (var category in highscore) {
var catHigh = highscore[category];
var catTeam = team[category] || 0;
var catPct = catTeam / catHigh;
var width = maxWidth * catPct;
var bar = document.createElement("span");
bar.classList.add("cat" + ncat);
bar.style.width = width + "%";
bar.textContent = category + ": " + catTeam;
bar.title = bar.textContent;
row.appendChild(bar);
ncat += 1;
}
var te = document.createElement("span");
te.classList.add("teamname");
te.textContent = teamnames[team.__hash__];
row.appendChild(te);
element.appendChild(row);
}
}
function once() {
loadJSON("points.json", update);
}
if (continuous) {
setInterval(once, 60000);
}
once();
}
function init() {
var sb = document.getElementById("scoreboard");
scoreboard(sb, true);
}
document.addEventListener("DOMContentLoaded", init);
</script>
`,
)
}
func staticPuzzleList(w http.ResponseWriter) {
ShowHtml(
w, Success,
"Open Puzzles",
`
<section>
<div id="puzzles"></div>
</section>
<script>
function init() {
let params = new URLSearchParams(window.location.search);
let categoryName = params.get("cat");
let points = params.get("points");
let puzzleId = params.get("pid");
let base = "content/" + categoryName + "/" + puzzleId + "/";
let fn = base + "puzzle.json";
fetch(fn)
.then(function(resp) {
return resp.json();
}).then(function(obj) {
document.getElementById("puzzle").innerHTML = obj.body;
document.getElementById("authors").textContent = obj.authors.join(", ");
for (let fn of obj.files) {
let li = document.createElement("li");
let a = document.createElement("a");
a.href = base + fn;
a.innerText = fn;
li.appendChild(a);
document.getElementById("files").appendChild(li);
}
}).catch(function(err) {
console.log("Error", err);
});
document.querySelector("body > h1").innerText = categoryName + " " + points
document.querySelector("input[name=cat]").value = categoryName;
document.querySelector("input[name=points]").value = points;
function mutated(mutationsList, observer) {
for (let mutation of mutationsList) {
if (mutation.type == 'childList') {
for (let e of mutation.addedNodes) {
console.log(e);
for (let se of e.querySelectorAll("[src],[href]")) {
se.outerHTML = se.outerHTML.replace(/(src|href)="([^/]+)"/i, "$1=\"" + base + "$2\"")
console.log(se.outerHTML);
}
console.log(e.querySelectorAll("[src]"));
}
console.log(mutation.addedNodes);
} else {
console.log(mutation);
}
}
}
let puzzle = document.getElementById("puzzle");
let observerOptions = {
childList: true,
attributes: true,
subtree: true,
};
window.observer = new MutationObserver(mutated);
observer.observe(puzzle, observerOptions);
}
document.addEventListener("DOMContentLoaded", init);
</script>
`,
)
}
func staticPuzzle(w http.ResponseWriter) {
ShowHtml(
w, Success,
"Open Puzzles",
`
<section>
<div id="body">Loading...</div>
</section>
<form action="answer" method="post">
<input type="hidden" name="cat">
<input type="hidden" name="points">
Team ID: <input type="text" name="id"> <br>
Answer: <input type="text" name="answer"> <br>
<input type="submit" value="Submit">
</form>
<script>
function render(obj) {
let body = document.getElementById("body");
body.innerHTML = obj.body;
console.log("XXX: Munge relative URLs (src= and href=) in body")
}
function init() {
let params = new URLSearchParams(window.location.search);
let categoryName = params.get("cat");
let points = params.get("points");
let puzzleId = params.get("pid");
let fn = "content/" + categoryName + "/" + puzzleId + "/puzzle.json";
fetch(fn)
.then(function(resp) {
return resp.json();
}).then(function(obj) {
render(obj);
}).catch(function(err) {
console.log("Error", err);
});
document.querySelector("body > h1").innerText = categoryName + " " + points
document.querySelector("input[name=cat]").value = categoryName;
document.querySelector("input[name=points]").value = points;
}
document.addEventListener("DOMContentLoaded", init);
</script>
`,
)
}
func tryServeFile(w http.ResponseWriter, req *http.Request, path string) bool {
f, err := os.Open(path)
if err != nil {
return false
}
defer f.Close()
d, err := f.Stat()
if err != nil {
return false
}
http.ServeContent(w, req, path, d.ModTime(), f)
return true
}
func ServeStatic(w http.ResponseWriter, req *http.Request, resourcesDir string) {
path := req.URL.Path
if strings.Contains(path, "..") {
http.Error(w, "Invalid URL path", http.StatusBadRequest)
return
}
if path == "/" {
path = "/index.html"
}
fpath := filepath.Join(resourcesDir, path)
if tryServeFile(w, req, fpath) {
return
}
switch path {
case "/basic.css":
staticStylesheet(w)
case "/index.html":
staticIndex(w)
case "/scoreboard.html":
staticScoreboard(w)
case "/puzzle-list.html":
staticPuzzleList(w)
case "/puzzle.html":
staticPuzzle(w)
default:
http.NotFound(w, req)
}
}

View File

@ -39,29 +39,29 @@ function render(obj) {
l.appendChild(i);
if (points === 0) {
i.textContent = "✿";
i.textContent = "✿";
} else {
var a = document.createElement('a');
i.appendChild(a);
a.textContent = points;
var a = document.createElement('a');
i.appendChild(a);
a.textContent = points;
a.href = "puzzle.html?cat=" + cat + "&points=" + points + "&pid=" + id;
}
}
}
}
puzzlesElement.appendChild(pdiv);
document.getElementById("puzzles").appendChild(puzzlesElement);
puzzlesElement.appendChild(pdiv);
document.getElementById("puzzles").appendChild(puzzlesElement);
}
}
function init() {
fetch("puzzles.json")
.then(function(resp) {
return resp.json();
}).then(function(obj) {
render(obj);
}).catch(function(err) {
console.log("Error", err);
});
fetch("puzzles.json")
.then(function(resp) {
return resp.json();
}).then(function(obj) {
render(obj);
}).catch(function(err) {
console.log("Error", err);
});
}
document.addEventListener("DOMContentLoaded", init);

View File

@ -17,10 +17,10 @@ function init() {
let base = "content/" + categoryName + "/" + puzzleId + "/";
let fn = base + "puzzle.json";
fetch(fn)
.then(function(resp) {
return resp.json();
}).then(function(obj) {
fetch(fn)
.then(function(resp) {
return resp.json();
}).then(function(obj) {
document.getElementById("authors").textContent = obj.authors.join(", ");
for (let fn of obj.files) {
let li = document.createElement("li");
@ -31,14 +31,14 @@ function init() {
document.getElementById("files").appendChild(li);
}
document.getElementById("puzzle").innerHTML = obj.body;
}).catch(function(err) {
console.log("Error", err);
});
document.querySelector("body > h1").innerText = categoryName + " " + points
document.querySelector("input[name=cat]").value = categoryName;
document.querySelector("input[name=points]").value = points;
}).catch(function(err) {
console.log("Error", err);
});
document.querySelector("body > h1").innerText = categoryName + " " + points
document.querySelector("input[name=cat]").value = categoryName;
document.querySelector("input[name=points]").value = points;
function mutated(mutationsList, observer) {
for (let mutation of mutationsList) {
if (mutation.type == 'childList') {
@ -58,14 +58,14 @@ function init() {
}
}
let puzzle = document.getElementById("puzzle");
let observerOptions = {
childList: true,
attributes: true,
subtree: true,
};
window.observer = new MutationObserver(mutated);
observer.observe(puzzle, observerOptions);
let puzzle = document.getElementById("puzzle");
let observerOptions = {
childList: true,
attributes: true,
subtree: true,
};
window.observer = new MutationObserver(mutated);
observer.observe(puzzle, observerOptions);
}
document.addEventListener("DOMContentLoaded", init);
</script>
@ -77,13 +77,13 @@ document.addEventListener("DOMContentLoaded", init);
<ul id="files"></ul>
<p>Puzzle by <span id="authors"></span></p>
</section>
<form action="answer" method="post">
<input type="hidden" name="cat">
<input type="hidden" name="points">
Team ID: <input type="text" name="id"> <br>
Answer: <input type="text" name="answer"> <br>
<input type="submit" value="Submit">
</form>
<form action="answer" method="post">
<input type="hidden" name="cat">
<input type="hidden" name="points">
Team ID: <input type="text" name="id"> <br>
Answer: <input type="text" name="answer"> <br>
<input type="submit" value="Submit">
</form>
<nav>
<ul>
<li><a href="puzzle-list.html">Puzzles</a></li>

148
theme/scoreboard.html Normal file
View File

@ -0,0 +1,148 @@
<!DOCTYPE html>
<html>
<head>
<title>Scoreboard</title>
<link rel="stylesheet" href="basic.css">
<meta name="viewport" content="width=device-width">
<link rel="icon" href="res/icon.svg" type="image/svg+xml">
<link rel="icon" href="res/icon.png" type="image/png">
<script>
function loadJSON(url, callback) {
function loaded(e) {
callback(e.target.response);
}
var xhr = new XMLHttpRequest()
xhr.onload = loaded;
xhr.open("GET", url, true);
xhr.responseType = "json";
xhr.send();
}
function scoreboard(element, continuous) {
function update(state) {
var teamnames = state["teams"];
var pointslog = state["points"];
var pointshistory = JSON.parse(localStorage.getItem("pointshistory")) || [];
if (pointshistory.length >= 20){
pointshistory.shift();
}
pointshistory.push(pointslog);
localStorage.setItem("pointshistory", JSON.stringify(pointshistory));
var highscore = {};
var teams = {};
// Dole out points
for (var i in pointslog) {
var entry = pointslog[i];
var timestamp = entry[0];
var teamhash = entry[1];
var category = entry[2];
var points = entry[3];
var team = teams[teamhash] || {__hash__: teamhash};
// Add points to team's points for that category
team[category] = (team[category] || 0) + points;
// Record highest score in a category
highscore[category] = Math.max(highscore[category] || 0, team[category]);
teams[teamhash] = team;
}
// Sort by team score
function teamScore(t) {
var score = 0;
for (var category in highscore) {
score += (t[category] || 0) / highscore[category];
}
// XXX: This function really shouldn't have side effects.
t.__score__ = score;
return score;
}
function teamCompare(a, b) {
return teamScore(a) - teamScore(b);
}
var winners = [];
for (var i in teams) {
winners.push(teams[i]);
}
if (winners.length == 0) {
// No teams!
return;
}
winners.sort(teamCompare);
winners.reverse();
// Clear out the element we're about to populate
while (element.lastChild) {
element.removeChild(element.lastChild);
}
// Populate!
var topActualScore = winners[0].__score__;
// (100 / ncats) * (ncats / topActualScore);
var maxWidth = 100 / topActualScore;
for (var i in winners) {
var team = winners[i];
var row = document.createElement("div");
var ncat = 0;
for (var category in highscore) {
var catHigh = highscore[category];
var catTeam = team[category] || 0;
var catPct = catTeam / catHigh;
var width = maxWidth * catPct;
var bar = document.createElement("span");
bar.classList.add("category");
bar.classList.add("cat" + ncat);
bar.style.width = width + "%";
bar.textContent = category + ": " + catTeam;
bar.title = bar.textContent;
row.appendChild(bar);
ncat += 1;
}
var te = document.createElement("span");
te.classList.add("teamname");
te.textContent = teamnames[team.__hash__];
row.appendChild(te);
element.appendChild(row);
}
}
function once() {
loadJSON("points.json", update);
}
if (continuous) {
setInterval(once, 60000);
}
once();
}
function init() {
var sb = document.getElementById("scoreboard");
scoreboard(sb, true);
}
document.addEventListener("DOMContentLoaded", init);
</script>
</head>
<body>
<h1 class="Success">Scoreboard</h1>
<section>
<div id="scoreboard"></div>
</section>
<nav>
<ul>
<li><a href="puzzle-list.html">Puzzles</a></li>
<li><a href="scoreboard.html">Scoreboard</a></li>
</ul>
</nav>
</body>
</html>

View File

@ -14,7 +14,7 @@
}
</style>
<script src="d3.js" async></script>
<script src="scoreboard-llnl.js" async></script>
<script src="scoreboard.js" async></script>
<script>
var type = "original";

View File

@ -1,528 +0,0 @@
function loadJSON(url, callback) {
function loaded(e) {
callback(e.target.response);
}
var xhr = new XMLHttpRequest()
xhr.onload = loaded;
xhr.open("GET", url, true);
xhr.responseType = "json";
xhr.send();
}
function toObject(arr) {
var rv = {};
for (var i = 0; i < arr.length; ++i)
if (arr[i] !== undefined) rv[i] = arr[i];
return rv;
}
var updateInterval;
function scoreboard(element, continuous, mode, interval) {
if(updateInterval) {
clearInterval(updateInterval);
}
function update(state) {
//console.log("Updating");
var teamnames = state["teams"];
var pointslog = state["points"];
var highscore = {};
var teams = {};
function pointsCompare(a, b) {
return a[0] - b[0];
}
pointslog.sort(pointsCompare);
var minTime = pointslog[0][0];
var maxTime = pointslog[pointslog.length - 1][0];
var allQuestions = {};
for (var i in pointslog) {
var entry = pointslog[i];
var timestamp = entry[0];
var teamhash = entry[1];
var category = entry[2];
var points = entry[3];
var catPoints = {};
if(category in allQuestions) {
catPoints = allQuestions[category];
} else {
catPoints["total"] = 0;
}
if(!(points in catPoints)) {
catPoints[points] = 1;
catPoints["total"] = catPoints["total"] + points;
} else {
catPoints[points] = catPoints[points] + 1;
}
allQuestions[category] = catPoints;
}
// Dole out points
for (var i in pointslog) {
var entry = pointslog[i];
var timestamp = entry[0];
var teamhash = entry[1];
var category = entry[2];
var points = entry[3];
var team = teams[teamhash] || {__hash__: teamhash};
// Add points to team's points for that category
team[category] = (team[category] || 0) + points;
// Record highest score in a category
highscore[category] = Math.max(highscore[category] || 0, team[category]);
teams[teamhash] = team;
}
// Sort by team score
function teamScore(t) {
var score = 0;
for (var category in highscore) {
score += (t[category] || 0) / highscore[category];
}
// XXX: This function really shouldn't have side effects.
t.__score__ = score;
return score;
}
function pointScore(points, category) {
return points / highscore[category]
}
function teamCompare(a, b) {
return teamScore(a) - teamScore(b);
}
var winners = [];
for (var i in teams) {
winners.push(teams[i]);
}
if (winners.length == 0) {
// No teams!
return;
}
winners.sort(teamCompare);
winners.reverse();
// Clear out the element we're about to populate
while (element.lastChild) {
element.removeChild(element.lastChild);
}
// Populate!
var topActualScore = winners[0].__score__;
if(mode == "time") {
var colorScale = d3.schemeCategory20;
var teamLines = {};
var reverseTeam = {};
for(var i in pointslog) {
var entry = pointslog[i];
var timestamp = entry[0];
var teamhash = entry[1];
var category = entry[2];
var points = entry[3];
var teamname = teamnames[teamhash];
reverseTeam[teamname] = teamhash;
points = pointScore(points, category);
if(!(teamname in teamLines)) {
var teamHistory = [[timestamp, points, category, entry[3], [minTime, 0, category, 0]]];
teamLines[teamname] = teamHistory;
} else {
var teamHistory = teamLines[teamname];
teamHistory.push([timestamp, points + teamHistory[teamHistory.length - 1][1], category, entry[3], teamHistory[teamHistory.length - 1]]);
}
}
//console.log(teamLines);
var graph = document.createElement("svg");
graph.id = "graph";
graph.style.width="100%";
graph.style.height = "100vh";
var titleHeight = document.getElementById("title").clientHeight;
titleHeight += document.getElementById("title").offsetTop * 2;
graph.style.backgroundColor = "white";
graph.style.display = "table";
var holdingDiv = document.createElement("div");
holdingDiv.align="center";
holdingDiv.id="holding";
holdingDiv.style.height = "100%";
element.style.height = "100%";
element.appendChild(holdingDiv);
holdingDiv.appendChild(graph);
var margins = 40;
var marginsX = 120;
var width = graph.offsetWidth;
var height = graph.offsetHeight;
height = height - titleHeight - margins;
//var xScale = d3.scaleLinear().range([minTime, maxTime]);
//var yScale = d3.scaleLinear().range([0, topActualScore]);
var originTime = (maxTime - minTime) / 60;
var xScale = d3.scaleLinear().range([marginsX, width - margins]);
xScale.domain([0, originTime]);
var yScale = d3.scaleLinear().range([height - margins, margins]);
yScale.domain([0, topActualScore]);
graph = d3.select("#graph");
graph.remove();
graph = d3.select("#holding").append("svg")
.attr("width", width)
.attr("height", height);
//.attr("style", "background: white");
//graph.append("g")
// .attr("transform", "translate(" + margins + ", 0)")
// .call(d3.axisLeft(yScale))
// .style("stroke", "white");;
var maxNumEntry = 10;
//var curEntry = 0;
var winningTeams = [];
for(entry in winners) {
var curEntry = entry;
if(curEntry >= maxNumEntry) {
break;
}
entry = teamnames[winners[entry].__hash__];
winningTeams.push(entry);
//console.log(curEntry);
//console.log(entry);
//var isTop = false;
//for(var x=0; x < maxNumEntry; x++)
//{
// var teamhash = reverseTeam[entry];
// if(winners[x].__hash__ == teamhash)
// {
// curEntry = x;
// isTop = true;
// break;
// }
//}
//if(!isTop)
//{
// continue;
//}
var curTeam = teamLines[entry];
var lastEntry = curTeam[curTeam.length - 1];
//curTeam.append()
curTeam.push([maxTime, lastEntry[1], lastEntry[2], lastEntry[3], lastEntry]);
var curLayer = graph.append("g");
curLayer.selectAll("line")
.data(curTeam)
.enter()
.append("line")
.style("stroke", colorScale[curEntry * 2])
.attr("stroke-width", 4)
.attr("class", "team_" + entry)
.style("z-index", maxNumEntry - curEntry)
.attr("x1",
function(d) {
return xScale((d[4][0] - minTime) / 60);
})
.attr("x2",
function(d) {
return xScale((d[0] - minTime) / 60);
})
.attr("y1",
function(d) {
return yScale(d[4][1]);
})
.attr("y2",
function(d) {
return yScale(d[1]);
})
.on("mouseover", handleMouseover)
.on("mouseout", handleMouseout);
curLayer.selectAll("circle")
.data(curTeam)
.enter()
.append("circle")
.style("fill", colorScale[curEntry * 2])
.style("z-index", maxNumEntry - curEntry)
.attr("class", "team_" + entry)
.attr("r", 5)
.attr("cx",
function(d) {
return xScale((d[0] - minTime) / 60);
})
.attr("cy",
function(d) {
return yScale(d[1]);
})
.on("mouseover", handleMouseoverCircle)
.on("mouseout", handleMouseoutCircle);
curEntry++;
}
var axisG = graph.append("g");
axisG
.attr("transform", "translate(0," + (height - margins) + ")")
.call(d3.axisBottom(xScale));
//.style("stroke", "white");
axisG.selectAll("path").style("stroke", "white");
axisG.selectAll("line").style("stroke", "white");
axisG.selectAll("text").style("fill", "white");
graph.append("text")
.attr("text-anchor", "middle")
.attr("transform", "translate(" + (width / 2) + ", " + (height - margins / 8) + ")")
.style("fill", "white")
.text("Time (minutes)");
var legend = graph.append("g");
var legendRowHeight = (height - margins) / 10;
legend.selectAll("rect")
.data(winningTeams)
.enter()
.append("rect")
.attr("class", function(d){ return "team_" + d; })
.attr("fill", function(d, i){ return colorScale[i * 2]; })
.style("z-index", function(d, i){ return i; })
.attr("x", 0)
.attr("y", function(d, i){ return legendRowHeight * i; })
.attr("height", legendRowHeight)
.attr("width", marginsX)
.on("mouseover", handleMouseoverLegend)
.on("mouseout", handleMouseoutLegend);
legend.selectAll("text")
.data(winningTeams)
.enter()
.append("text")
//.attr("class", function(d){ return "team_" + d; })
.attr("fill", "black")
.style("z-index", function(d, i){ return i; })
.attr("dx", 0)
.attr("dy", function(d, i){ return legendRowHeight * (i + .5); })
.text(function(d, i){ return i + ": " + d; })
.attr("dominant-baseline", "central")
.style("pointer-events", "none");
//legend.append("g").selectAll("text")
// .data(winningTeams)
// .enter()
// .append("text")
// .attr("class", function(d){ return "team_" + d; })
// .attr("fill", function(d, i){ return colorScale[i]; })
// .style("z-index", function(d, i){ return i; })
// .attr("dx", margins)
// .attr("dy", function(d, i){ return margins + legendRowHeight * (i); })
// .text(function(d){ return d; });
//.attr("dominant-baseline", "central");
//.style("pointer-events", "none");
function handleMouseover(d, i) {
d3.select("body").selectAll(".tooltip").remove();
var curClass = d3.select(this).attr("class");
d3.select("body").selectAll("." + curClass)
.style("stroke", "white")
.style("fill", "white");
d3.select("body").selectAll("text")
.style("stroke-width", 0);
}
function handleMouseout(d, i) {
d3.select("body").selectAll(".tooltip").remove();
var curClass = d3.select(this).attr("class");
var zIndex = d3.select(this).style("z-index");
d3.select("body").selectAll("." + curClass)
.style("stroke", colorScale[(maxNumEntry - zIndex) * 2])
.style("fill", colorScale[(maxNumEntry - zIndex) * 2]);
legend.selectAll("." + curClass)
.style("stroke", colorScale[(maxNumEntry - zIndex) * 2])
.style("fill", colorScale[(maxNumEntry - zIndex) * 2]);
d3.select("body").selectAll("text")
.style("stroke-width", 0);
}
var tooltipPadding = 10;
function handleMouseoverCircle(d, i) {
d3.select("body").selectAll(".tooltip").remove();
var curClass = d3.select(this).attr("class");
d3.select("body").selectAll("." + curClass)
.style("stroke", "white")
.style("fill", "white");
d3.select("body").selectAll("text")
.style("stroke-width", 0);
graph.append("g").append("text")
.attr("class", "tooltip")
.attr("text-anchor", "middle")
.style("fill", "red")
.style("stroke-width", -4)
.style("stroke", "black")
.style("font-weight", "bolder")
.style("font-size", "large")
.attr("dx",
function() {
return xScale((d[0] - minTime) / 60);
})
.attr("dy",
function() {
return yScale(d[1]) - tooltipPadding;
})
.text(function(){ return d[2] + " " + d[3]; })
.style("pointer-events", "none");
}
function handleMouseoutCircle(d, i) {
d3.select("body").selectAll(".tooltip").remove();
var curClass = d3.select(this).attr("class");
var zIndex = d3.select(this).style("z-index");
d3.select("body").selectAll("." + curClass)
.style("stroke", colorScale[(maxNumEntry - zIndex) * 2])
.style("fill", colorScale[(maxNumEntry - zIndex) * 2]);
legend.selectAll("." + curClass)
.style("stroke", colorScale[(maxNumEntry - zIndex) * 2])
.style("fill", colorScale[(maxNumEntry - zIndex) * 2]);
d3.select("body").selectAll("text")
.style("stroke-width", 0);
}
function handleMouseoverLegend(d, i) {
d3.select("body").selectAll(".tooltip").remove();
var curClass = d3.select(this).attr("class");
d3.select("body").selectAll("." + curClass)
.style("stroke", "white")
.style("fill", "white");
d3.select("body").selectAll("text")
.style("stroke-width", 0);
}
function handleMouseoutLegend(d, i) {
d3.select("body").selectAll(".tooltip").remove();
var curClass = d3.select(this).attr("class");
var zIndex = d3.select(this).style("z-index");
d3.select("body").selectAll("." + curClass)
.style("stroke", colorScale[zIndex * 2])
.style("fill", colorScale[zIndex * 2]);
legend.selectAll("." + curClass)
.style("stroke", colorScale[(zIndex) * 2])
.style("fill", colorScale[(zIndex) * 2]);
d3.select("body").selectAll("text")
.style("stroke-width", 0);
}
} else if(mode == "original") {
// (100 / ncats) * (ncats / topActualScore);
var maxWidth = 100 / topActualScore;
for (var i in winners) {
var team = winners[i];
var row = document.createElement("div");
var ncat = 0;
for (var category in highscore) {
var catHigh = highscore[category];
var catTeam = team[category] || 0;
var catPct = catTeam / catHigh;
var width = maxWidth * catPct;
var bar = document.createElement("span");
bar.classList.add("cat" + ncat);
bar.style.width = width + "%";
bar.textContent = category + ": " + catTeam;
bar.title = bar.textContent;
row.appendChild(bar);
ncat += 1;
}
var te = document.createElement("span");
te.classList.add("teamname");
te.textContent = teamnames[team.__hash__];
row.appendChild(te);
element.appendChild(row);
}
}
if(mode == "total") {
var colorScale = d3.schemeCategory20;
var numCats = 0;
for(entry in allQuestions) {
numCats++;
}
var maxWidth = Math.floor(100 / (0.0 + numCats));
//console.log(maxWidth);
for (var i in winners) {
var team = winners[i];
var row = document.createElement("div");
var ncat = 0;
for (var category in allQuestions) {
var catHigh = highscore[category];
var catTeam = team[category] || 0;
var catPct = 0;
if (catHigh > 30000) {
catPct = (0.0 + Math.log(1+catTeam)) / (0.0 + Math.log(1+catHigh));
} else {
catPct = (0.0 + catTeam) / (0.0 + catHigh);
}
var width = maxWidth * catPct;
var bar = document.createElement("span");
var numLeft = catHigh - catTeam;
//bar.classList.add("cat" + ncat);
bar.style.backgroundColor = colorScale[ncat % 20];
bar.style.color = "white";
bar.style.width = width + "%";
bar.textContent = category + ": " + catTeam;
bar.title = bar.textContent;
row.appendChild(bar);
ncat++;
width = maxWidth * (1 - catPct);
if(width > 0) {
var noBar = document.createElement("span");
//noBar.classList.add("cat" + ncat);
noBar.style.backgroundColor = colorScale[ncat % 20];
noBar.style.width = width + "%";
noBar.textContent = numLeft;
noBar.title = bar.textContent;
row.appendChild(noBar);
}
ncat += 1;
}
var te = document.createElement("span");
te.classList.add("teamname");
te.textContent = teamnames[team.__hash__];
row.appendChild(te);
element.appendChild(row);
}
}
}
function once() {
loadJSON("points.json", update);
}
if (continuous) {
updateInterval = setInterval(once, interval);
}
once();
}

View File

@ -9,7 +9,7 @@
</div>
</body>
<script>
var cycle = ["scoreboard.html", "scoreboard-llnl-all.html", "scoreboard-llnl-timeline.html"];
var cycle = ["scoreboard.html", "scoreboard-all.html", "scoreboard-timeline.html"];
var current = 0;
var timeout = 25000;
var curTimeout;

View File

@ -14,7 +14,7 @@
}
</style>
<script src="d3.js" async></script>
<script src="scoreboard-llnl.js" async></script>
<script src="scoreboard.js" async></script>
<script>
var type = "original";

View File

@ -5,9 +5,12 @@
<link rel="stylesheet" href="style.css" type="text/css">
<script src="scoreboard.js" async></script>
<script>
var type = "original";
var interval = 60000;
function init() {
var sb = document.getElementById("scoreboard");
scoreboard(sb, true);
scoreboard(sb, true, type, interval);
}
window.addEventListener("load", init);

View File

@ -9,18 +9,58 @@ function loadJSON(url, callback) {
xhr.send();
}
function scoreboard(element, continuous) {
function toObject(arr) {
var rv = {};
for (var i = 0; i < arr.length; ++i)
if (arr[i] !== undefined) rv[i] = arr[i];
return rv;
}
var updateInterval;
function scoreboard(element, continuous, mode, interval) {
if(updateInterval) {
clearInterval(updateInterval);
}
function update(state) {
//console.log("Updating");
var teamnames = state["teams"];
var pointslog = state["points"];
var pointshistory = JSON.parse(localStorage.getItem("pointshistory")) || [];
if (pointshistory.length >= 20){
pointshistory.shift();
}
pointshistory.push(pointslog);
localStorage.setItem("pointshistory", JSON.stringify(pointshistory));
var highscore = {};
var teams = {};
function pointsCompare(a, b) {
return a[0] - b[0];
}
pointslog.sort(pointsCompare);
var minTime = pointslog[0][0];
var maxTime = pointslog[pointslog.length - 1][0];
var allQuestions = {};
for (var i in pointslog) {
var entry = pointslog[i];
var timestamp = entry[0];
var teamhash = entry[1];
var category = entry[2];
var points = entry[3];
var catPoints = {};
if(category in allQuestions) {
catPoints = allQuestions[category];
} else {
catPoints["total"] = 0;
}
if(!(points in catPoints)) {
catPoints[points] = 1;
catPoints["total"] = catPoints["total"] + points;
} else {
catPoints[points] = catPoints[points] + 1;
}
allQuestions[category] = catPoints;
}
// Dole out points
for (var i in pointslog) {
@ -29,18 +69,18 @@ function scoreboard(element, continuous) {
var teamhash = entry[1];
var category = entry[2];
var points = entry[3];
var team = teams[teamhash] || {__hash__: teamhash};
// Add points to team's points for that category
team[category] = (team[category] || 0) + points;
// Record highest score in a category
highscore[category] = Math.max(highscore[category] || 0, team[category]);
teams[teamhash] = team;
}
// Sort by team score
function teamScore(t) {
var score = 0;
@ -52,10 +92,13 @@ function scoreboard(element, continuous) {
t.__score__ = score;
return score;
}
function pointScore(points, category) {
return points / highscore[category]
}
function teamCompare(a, b) {
return teamScore(a) - teamScore(b);
}
var winners = [];
for (var i in teams) {
winners.push(teams[i]);
@ -66,51 +109,420 @@ function scoreboard(element, continuous) {
}
winners.sort(teamCompare);
winners.reverse();
// Clear out the element we're about to populate
while (element.lastChild) {
element.removeChild(element.lastChild);
}
// Populate!
var topActualScore = winners[0].__score__;
// (100 / ncats) * (ncats / topActualScore);
var maxWidth = 100 / topActualScore;
for (var i in winners) {
var team = winners[i];
var row = document.createElement("div");
var ncat = 0;
for (var category in highscore) {
var catHigh = highscore[category];
var catTeam = team[category] || 0;
var catPct = catTeam / catHigh;
var width = maxWidth * catPct;
if(mode == "time") {
var colorScale = d3.schemeCategory20;
var teamLines = {};
var reverseTeam = {};
for(var i in pointslog) {
var entry = pointslog[i];
var timestamp = entry[0];
var teamhash = entry[1];
var category = entry[2];
var points = entry[3];
var teamname = teamnames[teamhash];
reverseTeam[teamname] = teamhash;
points = pointScore(points, category);
var bar = document.createElement("span");
bar.classList.add("cat" + ncat);
bar.style.width = width + "%";
bar.textContent = category + ": " + catTeam;
bar.title = bar.textContent;
row.appendChild(bar);
ncat += 1;
if(!(teamname in teamLines)) {
var teamHistory = [[timestamp, points, category, entry[3], [minTime, 0, category, 0]]];
teamLines[teamname] = teamHistory;
} else {
var teamHistory = teamLines[teamname];
teamHistory.push([timestamp, points + teamHistory[teamHistory.length - 1][1], category, entry[3], teamHistory[teamHistory.length - 1]]);
}
}
var te = document.createElement("span");
te.classList.add("teamname");
te.textContent = teamnames[team.__hash__];
row.appendChild(te);
//console.log(teamLines);
var graph = document.createElement("svg");
graph.id = "graph";
graph.style.width="100%";
graph.style.height = "100vh";
var titleHeight = document.getElementById("title").clientHeight;
titleHeight += document.getElementById("title").offsetTop * 2;
graph.style.backgroundColor = "white";
graph.style.display = "table";
var holdingDiv = document.createElement("div");
holdingDiv.align="center";
holdingDiv.id="holding";
holdingDiv.style.height = "100%";
element.style.height = "100%";
element.appendChild(holdingDiv);
holdingDiv.appendChild(graph);
var margins = 40;
var marginsX = 120;
element.appendChild(row);
var width = graph.offsetWidth;
var height = graph.offsetHeight;
height = height - titleHeight - margins;
//var xScale = d3.scaleLinear().range([minTime, maxTime]);
//var yScale = d3.scaleLinear().range([0, topActualScore]);
var originTime = (maxTime - minTime) / 60;
var xScale = d3.scaleLinear().range([marginsX, width - margins]);
xScale.domain([0, originTime]);
var yScale = d3.scaleLinear().range([height - margins, margins]);
yScale.domain([0, topActualScore]);
graph = d3.select("#graph");
graph.remove();
graph = d3.select("#holding").append("svg")
.attr("width", width)
.attr("height", height);
//.attr("style", "background: white");
//graph.append("g")
// .attr("transform", "translate(" + margins + ", 0)")
// .call(d3.axisLeft(yScale))
// .style("stroke", "white");;
var maxNumEntry = 10;
//var curEntry = 0;
var winningTeams = [];
for(entry in winners) {
var curEntry = entry;
if(curEntry >= maxNumEntry) {
break;
}
entry = teamnames[winners[entry].__hash__];
winningTeams.push(entry);
//console.log(curEntry);
//console.log(entry);
//var isTop = false;
//for(var x=0; x < maxNumEntry; x++)
//{
// var teamhash = reverseTeam[entry];
// if(winners[x].__hash__ == teamhash)
// {
// curEntry = x;
// isTop = true;
// break;
// }
//}
//if(!isTop)
//{
// continue;
//}
var curTeam = teamLines[entry];
var lastEntry = curTeam[curTeam.length - 1];
//curTeam.append()
curTeam.push([maxTime, lastEntry[1], lastEntry[2], lastEntry[3], lastEntry]);
var curLayer = graph.append("g");
curLayer.selectAll("line")
.data(curTeam)
.enter()
.append("line")
.style("stroke", colorScale[curEntry * 2])
.attr("stroke-width", 4)
.attr("class", "team_" + entry)
.style("z-index", maxNumEntry - curEntry)
.attr("x1",
function(d) {
return xScale((d[4][0] - minTime) / 60);
})
.attr("x2",
function(d) {
return xScale((d[0] - minTime) / 60);
})
.attr("y1",
function(d) {
return yScale(d[4][1]);
})
.attr("y2",
function(d) {
return yScale(d[1]);
})
.on("mouseover", handleMouseover)
.on("mouseout", handleMouseout);
curLayer.selectAll("circle")
.data(curTeam)
.enter()
.append("circle")
.style("fill", colorScale[curEntry * 2])
.style("z-index", maxNumEntry - curEntry)
.attr("class", "team_" + entry)
.attr("r", 5)
.attr("cx",
function(d) {
return xScale((d[0] - minTime) / 60);
})
.attr("cy",
function(d) {
return yScale(d[1]);
})
.on("mouseover", handleMouseoverCircle)
.on("mouseout", handleMouseoutCircle);
curEntry++;
}
var axisG = graph.append("g");
axisG
.attr("transform", "translate(0," + (height - margins) + ")")
.call(d3.axisBottom(xScale));
//.style("stroke", "white");
axisG.selectAll("path").style("stroke", "white");
axisG.selectAll("line").style("stroke", "white");
axisG.selectAll("text").style("fill", "white");
graph.append("text")
.attr("text-anchor", "middle")
.attr("transform", "translate(" + (width / 2) + ", " + (height - margins / 8) + ")")
.style("fill", "white")
.text("Time (minutes)");
var legend = graph.append("g");
var legendRowHeight = (height - margins) / 10;
legend.selectAll("rect")
.data(winningTeams)
.enter()
.append("rect")
.attr("class", function(d){ return "team_" + d; })
.attr("fill", function(d, i){ return colorScale[i * 2]; })
.style("z-index", function(d, i){ return i; })
.attr("x", 0)
.attr("y", function(d, i){ return legendRowHeight * i; })
.attr("height", legendRowHeight)
.attr("width", marginsX)
.on("mouseover", handleMouseoverLegend)
.on("mouseout", handleMouseoutLegend);
legend.selectAll("text")
.data(winningTeams)
.enter()
.append("text")
//.attr("class", function(d){ return "team_" + d; })
.attr("fill", "black")
.style("z-index", function(d, i){ return i; })
.attr("dx", 0)
.attr("dy", function(d, i){ return legendRowHeight * (i + .5); })
.text(function(d, i){ return i + ": " + d; })
.attr("dominant-baseline", "central")
.style("pointer-events", "none");
//legend.append("g").selectAll("text")
// .data(winningTeams)
// .enter()
// .append("text")
// .attr("class", function(d){ return "team_" + d; })
// .attr("fill", function(d, i){ return colorScale[i]; })
// .style("z-index", function(d, i){ return i; })
// .attr("dx", margins)
// .attr("dy", function(d, i){ return margins + legendRowHeight * (i); })
// .text(function(d){ return d; });
//.attr("dominant-baseline", "central");
//.style("pointer-events", "none");
function handleMouseover(d, i) {
d3.select("body").selectAll(".tooltip").remove();
var curClass = d3.select(this).attr("class");
d3.select("body").selectAll("." + curClass)
.style("stroke", "white")
.style("fill", "white");
d3.select("body").selectAll("text")
.style("stroke-width", 0);
}
function handleMouseout(d, i) {
d3.select("body").selectAll(".tooltip").remove();
var curClass = d3.select(this).attr("class");
var zIndex = d3.select(this).style("z-index");
d3.select("body").selectAll("." + curClass)
.style("stroke", colorScale[(maxNumEntry - zIndex) * 2])
.style("fill", colorScale[(maxNumEntry - zIndex) * 2]);
legend.selectAll("." + curClass)
.style("stroke", colorScale[(maxNumEntry - zIndex) * 2])
.style("fill", colorScale[(maxNumEntry - zIndex) * 2]);
d3.select("body").selectAll("text")
.style("stroke-width", 0);
}
var tooltipPadding = 10;
function handleMouseoverCircle(d, i) {
d3.select("body").selectAll(".tooltip").remove();
var curClass = d3.select(this).attr("class");
d3.select("body").selectAll("." + curClass)
.style("stroke", "white")
.style("fill", "white");
d3.select("body").selectAll("text")
.style("stroke-width", 0);
graph.append("g").append("text")
.attr("class", "tooltip")
.attr("text-anchor", "middle")
.style("fill", "red")
.style("stroke-width", -4)
.style("stroke", "black")
.style("font-weight", "bolder")
.style("font-size", "large")
.attr("dx",
function() {
return xScale((d[0] - minTime) / 60);
})
.attr("dy",
function() {
return yScale(d[1]) - tooltipPadding;
})
.text(function(){ return d[2] + " " + d[3]; })
.style("pointer-events", "none");
}
function handleMouseoutCircle(d, i) {
d3.select("body").selectAll(".tooltip").remove();
var curClass = d3.select(this).attr("class");
var zIndex = d3.select(this).style("z-index");
d3.select("body").selectAll("." + curClass)
.style("stroke", colorScale[(maxNumEntry - zIndex) * 2])
.style("fill", colorScale[(maxNumEntry - zIndex) * 2]);
legend.selectAll("." + curClass)
.style("stroke", colorScale[(maxNumEntry - zIndex) * 2])
.style("fill", colorScale[(maxNumEntry - zIndex) * 2]);
d3.select("body").selectAll("text")
.style("stroke-width", 0);
}
function handleMouseoverLegend(d, i) {
d3.select("body").selectAll(".tooltip").remove();
var curClass = d3.select(this).attr("class");
d3.select("body").selectAll("." + curClass)
.style("stroke", "white")
.style("fill", "white");
d3.select("body").selectAll("text")
.style("stroke-width", 0);
}
function handleMouseoutLegend(d, i) {
d3.select("body").selectAll(".tooltip").remove();
var curClass = d3.select(this).attr("class");
var zIndex = d3.select(this).style("z-index");
d3.select("body").selectAll("." + curClass)
.style("stroke", colorScale[zIndex * 2])
.style("fill", colorScale[zIndex * 2]);
legend.selectAll("." + curClass)
.style("stroke", colorScale[(zIndex) * 2])
.style("fill", colorScale[(zIndex) * 2]);
d3.select("body").selectAll("text")
.style("stroke-width", 0);
}
} else if(mode == "original") {
// (100 / ncats) * (ncats / topActualScore);
var maxWidth = 100 / topActualScore;
for (var i in winners) {
var team = winners[i];
var row = document.createElement("div");
var ncat = 0;
for (var category in highscore) {
var catHigh = highscore[category];
var catTeam = team[category] || 0;
var catPct = catTeam / catHigh;
var width = maxWidth * catPct;
var bar = document.createElement("span");
bar.classList.add("cat" + ncat);
bar.style.width = width + "%";
bar.textContent = category + ": " + catTeam;
bar.title = bar.textContent;
row.appendChild(bar);
ncat += 1;
}
var te = document.createElement("span");
te.classList.add("teamname");
te.textContent = teamnames[team.__hash__];
row.appendChild(te);
element.appendChild(row);
}
}
if(mode == "total") {
var colorScale = d3.schemeCategory20;
var numCats = 0;
for(entry in allQuestions) {
numCats++;
}
var maxWidth = Math.floor(100 / (0.0 + numCats));
//console.log(maxWidth);
for (var i in winners) {
var team = winners[i];
var row = document.createElement("div");
var ncat = 0;
for (var category in allQuestions) {
var catHigh = highscore[category];
var catTeam = team[category] || 0;
var catPct = 0;
if (catHigh > 30000) {
catPct = (0.0 + Math.log(1+catTeam)) / (0.0 + Math.log(1+catHigh));
} else {
catPct = (0.0 + catTeam) / (0.0 + catHigh);
}
var width = maxWidth * catPct;
var bar = document.createElement("span");
var numLeft = catHigh - catTeam;
//bar.classList.add("cat" + ncat);
bar.style.backgroundColor = colorScale[ncat % 20];
bar.style.color = "white";
bar.style.width = width + "%";
bar.textContent = category + ": " + catTeam;
bar.title = bar.textContent;
row.appendChild(bar);
ncat++;
width = maxWidth * (1 - catPct);
if(width > 0) {
var noBar = document.createElement("span");
//noBar.classList.add("cat" + ncat);
noBar.style.backgroundColor = colorScale[ncat % 20];
noBar.style.width = width + "%";
noBar.textContent = numLeft;
noBar.title = bar.textContent;
row.appendChild(noBar);
}
ncat += 1;
}
var te = document.createElement("span");
te.classList.add("teamname");
te.textContent = teamnames[team.__hash__];
row.appendChild(te);
element.appendChild(row);
}
}
}
function once() {
loadJSON("points.json", update);
}
if (continuous) {
setInterval(once, 60000);
updateInterval = setInterval(once, interval);
}
once();
}