Number Systems

A tool that convert a number from one base to another written in Python and SUIT.

Input:

Base:

Which direction? To Decimal From Decimal

Copyright © 2010-2011 Brandon Evans. All Rights Reserved.

Debug with SLACKS

SUIT Python

index.py
#!/usr/local/bin/python2.6
# -*- coding: utf-8 -*-
# Copyright (C) 2010-2011 Brandon Evans and Chris Santiago.
# http://www.brandonevans.org/
from cgi import escape
import cgitb
import glob
import json
import os
import sys
from webob import Request, Response
from pygments import highlight
from pygments.lexers import get_lexer_by_name
from pygments.formatters import HtmlFormatter
print 'Content-Type: text/html\n'
cgitb.enable()
environ = dict(os.environ.items())
environ['wsgi.input'] = sys.stdin
environ['wsgi.errors'] = sys.stderr
environ['wsgi.version'] = (1,0)
environ['wsgi.multithread'] = False
environ['wsgi.multiprocess'] = True
environ['wsgi.run_once'] = True
environ['wsgi.url_scheme'] = 'http'

class Helpers:
    def pygments(self, lexer, string):
        return highlight(string, get_lexer_by_name(lexer), HtmlFormatter())

helpers = Helpers()
import suit
from rulebox import templating
rules = templating.rules
rules['[template]']['var']['list'] = []
rules['[call']['var']['var']['owner'] = helpers
rules['[transform]']['var']['var']['owner'] = helpers
request = Request(environ)
request.charset = 'utf8'
response = Response()
templating.var.source = open('index.py').read()

def fromdecimal(input, base):
    base = int(base)
    #A number system needs at least two digits, and Base 36 uses all
    #case insensitive alphanumeric characters 
    if base < 2 or base > 36:
        return False
    input = int(input)
    if input == 0:
        return 0
    converted = ''
    while input != 0:
        input, remainder = divmod(input, base)
        if remainder > 9:
            #Convert the decimal to an alphanumeric character if necessary
            remainder = chr(remainder + 55)
        #Add on the remainder to the string
        converted = unicode(remainder) + converted
    return converted

def todecimal(input, base):
    base = int(base)
    #A number system needs at least two digits, and Base 36 uses all
    #case insensitive alphanumeric characters 
    if base < 1 or base > 36:
        return False
    #Flip the string so that the program reads it from right to left
    input = unicode(input)[::-1]
    converted = 0
    for key, value in enumerate(input):
        try:
            int(value)
        except ValueError:
            #Convert the alphanumeric character to decimal if possible
            value = ord(value.upper())
            if value < 65 or (value > 90 and value < 97) or value > 122:
                return False
            value -= 55
        value = int(value)
        if value >= base:
            return False
        #Add the value times the base to the placeholder to the converted sum
        converted += value * pow(base, key)
    return converted

templating.var.base = ''
templating.var.converted = False
templating.var.result = ''
if 'submit' in request.POST:
    templating.var.converted = True
    templating.var.valid = False
    templating.var.to = (request.POST['decimal'] == 'To')
    try:
        templating.var.input = request.POST['input']
        templating.var.base = request.POST['base']
        function = fromdecimal
        if templating.var.to:
            function = todecimal
        result = function(
            templating.var.input,
            templating.var.base
        )
        if result != False:
            templating.var.result = result
            templating.var.valid = True
    except ValueError:
        pass
string = suit.execute(
    rules,
    open(
        'index.tpl'
    ).read()
)
# Check if POST or GET data have been sent for SLACKS.
if 'slacks' in request.params:
    # JSON encode the log.
    slacks = json.dumps(suit.log, separators=(',', ':'))
    # Set the headers to prompt a download of a .json file.
    response.headerlist = [
        ('Pragma', 'public'),
        ('Expires', '0'),
        (
            'Cache-Control',
            'must-revalidate, post-check=0, pre-check=0'
        ),
        ('Content-type', 'text/json'),
        ('Content-Disposition', 'attachment; filename=slacks.json'),
        ('Content-Length', len(slacks))
    ]
    # Print the log.
    print slacks
else:
    # Print the string normally.
    print string