<commit_before>from pycket.cont import continuation
from pycket.error import SchemeException
from pycket.values import from_list, w_false, w_true, W_Object, W_Fixnum, W_SimplePrim, W_Symbol, w_null
from pycket.small_list import inline_small_list
from rpython.rlib import jit

#
# Structs are partially supported
#
# Not implemented:
# 1) prefab -- '#s(sprout bean): need update in expand.rkt
# 2) methods overriding (including equal) -- generic-interfaces.rkt
# 3) properties and super as an argument -- kw.rkt

# TODO: inspector currently does nothing
class W_StructInspector(W_Object):
    errorname = "struct-inspector"
    _immutable_fields_ = ["super"]

    @staticmethod
    def make(inspector, issibling = False):
        super = inspector
        if issibling:
            super = inspector.super if inspector is not None else None
        return W_StructInspector(super)

    def __init__(self, super):
        self.super = super

current_inspector = W_StructInspector(None)

class W_StructType(W_Object):
    all_structs = {}
    errorname = "struct-type"
    _immutable_fields_ = ["id", "super", "init_field_cnt", "auto_field_cnt", "auto_v", "inspector", "immutables", "guard", "constr_name"]
    @staticmethod
    def make(name, super_type, init_field_cnt, auto_field_cnt, auto_v, props, inspector, proc_spec, immutables, guard, constr_name):
        struct_id = W_StructTypeDescriptor(name.value)
        W_StructType.all_structs[struct_id] = w_result = W_StructType(struct_id, super_type, init_field_cnt, auto_field_cnt, auto_v, \
            props, inspector, proc_spec, immutables, guard, constr_name)
        return w_result

    @staticmethod
    def lookup_struct_type(struct_id):
        if struct_id in W_StructType.all_structs:
            return W_StructType.all_structs[struct_id]
        else:
            return w_false

    def __init__(self, struct_id, super_type, init_field_cnt, auto_field_cnt, \
            auto_v, props, inspector, proc_spec, immutables, guard, constr_name):
        self.super = W_StructType.lookup_struct_type(super_type) if super_type != w_false else None
        self.init_field_cnt = init_field_cnt.value
        self.auto_field_cnt = auto_field_cnt.value
        # Next arguments are optional
        self.auto_v = auto_v
        # self.props = props
        self.inspector = inspector
        # self.proc_spec = proc_spec
        self.immutables = immutables
        self.guard = guard
        if isinstance(constr_name, W_Symbol):
            self.constr_name = constr_name.value
        else:
            self.constr_name = "make-" + struct_id.value

        self.isopaque = True if self.inspector != w_false else False
        self.mutable_fields = []

        self.id = struct_id
        self.constr = W_StructConstructor(self.id, self.super, self.init_field_cnt, self.auto_field_cnt, self.auto_v, \
            self.mutable_fields, self.isopaque, self.guard, self.constr_name)
        self.pred = W_StructPredicate(self.id)
        self.acc = W_StructAccessor(self.id)
        self.mut = W_StructMutator(self.id)
    def constructor(self):
        return self.constr
    def set_mutable(self, field):
        assert isinstance(field, W_Fixnum)
        self.mutable_fields.append(field.value)
    def make_struct_tuple(self):
        return [self.id, self.constr, self.pred, self.acc, self.mut]

class W_StructTypeDescriptor(W_Object):
    errorname = "struct-type-descriptor"
    _immutable_fields_ = ["value"]
    def __init__(self, value):
        self.value = value
    def tostring(self):
        return "#<struct-type:%s>" % self.value

class W_StructConstructor(W_SimplePrim):
    _immutable_fields_ = ["struct_id", "super_type", "init_field_cnt", "auto_values", "isopaque", "guard", "name"]
    def __init__ (self, struct_id, super_type, init_field_cnt, auto_field_cnt, auto_v, mutable_fields, isopaque, guard, name):
        self.struct_id = struct_id
        self.super_type = super_type
        self.init_field_cnt = init_field_cnt
        self.auto_values = [auto_v] * auto_field_cnt
        self.mutable_fields = mutable_fields
        self.isopaque = isopaque
        self.guard = guard
        self.name = name
    def extcode(self, field_values, env, cont):
        if self.guard != w_false:
            cont = guard_check(self.guard, field_values, env, cont)
        super = None
        if isinstance(self.super_type, W_StructType):
            def split_list(list, num):
                assert num >= 0
                return list[:num], list[num:]
            split_position = len(field_values) - self.init_field_cnt
            super_field_values, field_values = split_list(field_values, split_position)
            super, env, cont = self.super_type.constructor().extcode(super_field_values, env, cont)
        vals = field_values + self.auto_values
        immutable_vals, mutable_vals = [], []
        for idx, val in enumerate(vals):
            if idx in self.mutable_fields: mutable_vals.append(val)
            else: immutable_vals.append(val)
        result = W_Struct.make(immutable_vals, self.mutable_fields, mutable_vals, self.struct_id, super, self.isopaque)
        return result, env, cont
    def call(self, args, env, cont):
        from pycket.interpreter import return_value
        result, env, cont = self.extcode(args, env, cont)
        return return_value(result, env, cont)
    def tostring(self):
        return "#<procedure:%s>" % self.name

@continuation
def guard_check(proc, field_values, env, cont, _vals):
    vals = _vals._get_full_list()
    struct = vals[0]
    assert isinstance(struct, W_Struct)
    args = [struct.type] + field_values
    return proc.call(args, env, cont)

class W_StructProperty(W_Object):
    errorname = "struct-type-property"
    _immutable_fields_ = ["name", "guard", "supers", "can_imp"]
    def __init__(self, name, guard, supers=w_null, can_imp=False):
        self.name = name
        self.guard = guard
        self.supers = supers
        self.can_imp = can_imp
    def tostring(self):
        return "#<struct-type-property:%s>"%self.name

class W_StructPropertyPredicate(W_SimplePrim):
    errorname = "struct-property-predicate"
    _immutable_fields_ = ["property"]
    def __init__(self, prop):
        self.property = prop
    def code(self, args):
        raise SchemeException("StructPropertyPredicate NYI")

class W_StructPropertyAccessor(W_SimplePrim):
    errorname = "struct-property-accessor"
    _immutable_fields_ = ["property"]
    def __init__(self, prop):
        self.property = prop
    def code(self, args):
        raise SchemeException("StructPropertyAccessor NYI")

class W_StructPredicate(W_SimplePrim):
    errorname = "struct-predicate"
    _immutable_fields_ = ["struct_id"]
    def __init__ (self, struct_id):
        self.struct_id = struct_id
    def code(self, args):
        struct = args[0]
        result = w_false
        if (isinstance(struct, W_Struct)):
            while True:
                if struct.type == self.struct_id:
                    result = w_true
                    break
                if struct.super is None: break
                else: struct = struct.super
        return result
    def tostring(self):
        return "#<procedure:%s?>" % self.struct_id.value

class W_StructFieldAccessor(W_SimplePrim):
    errorname = "struct-field-accessor"
    _immutable_fields_ = ["accessor", "field"]
    def __init__ (self, accessor, field):
        assert isinstance(accessor, W_StructAccessor)
        self.accessor = accessor
        self.field = field
    def code(self, args):
        struct = args[0]
        return self.accessor.code([struct, self.field])

class W_StructAccessor(W_SimplePrim):
    errorname = "struct-accessor"
    _immutable_fields_ = ["struct_id"]
    def __init__ (self, struct_id):
        self.struct_id = struct_id
    def code(self, args):
        struct, field = args
        assert isinstance(struct, W_Struct)
        assert isinstance(field, W_Fixnum)
        return struct.ref(self.struct_id, field.value)
    def tostring(self):
        return "#<procedure:%s-ref>" % self.struct_id.value

class W_StructFieldMutator(W_SimplePrim):
    errorname = "struct-field-mutator"
    _immutable_fields_ = ["mutator", "field"]
    def __init__ (self, mutator, field):
        assert isinstance(mutator, W_StructMutator)
        self.mutator = mutator
        self.field = field
        mutator.set_mutable(field)
    def code(self, args):
        struct = args[0]
        val = args[1]
        return self.mutator.code([struct, self.field, val])

class W_StructMutator(W_SimplePrim):
    errorname = "struct-mutator"
    _immutable_fields_ = ["struct_id"]
    def __init__ (self, struct_id):
        self.struct_id = struct_id
    def code(self, args):
        struct, field, val = args
        assert isinstance(struct, W_Struct)
        assert isinstance(field, W_Fixnum)
        struct.set(self.struct_id, field.value, val)
    def set_mutable(self, field):
        struct = W_StructType.lookup_struct_type(self.struct_id)
        struct.set_mutable(field)
    def tostring(self):
        return "#<procedure:%s-set!>" % self.struct_id.value

class W_Struct(W_Object):
    errorname = "struct"
    _immutable_fields_ = ["mutable_fields", "mutable_vals", "type", "super", "isopaque"]
    def __init__(self, mutable_fields, mutable_vals, struct_id, super, isopaque):
        self.mutable_fields = mutable_fields
        self.mutable_vals = mutable_vals
        self.type = struct_id
        self.super = super
        self.isopaque = isopaque
    # FIXME: make me more beautiful
    @jit.elidable
    def map(self, field):
        """
        Example:
        original struct values: (a: mutable, b: mutable, c: immutable)
        stored data:
          immutable_vals: (0: c) -- saved inline
          mutable_vals: (0: a, 1: b)
          mutable_fields: (0, 1)

        1. field (int) is a mutable field (self.mutable_fields is an array of integers)
        strategy: find all immutable fields before and subtract this number from field index
        """
        if field in self.mutable_fields:
            for immutable_field in [item for item in xrange(field) if item not in self.mutable_fields]:
                if immutable_field < field: field -= 1
                else: break
        """
        2. field is an immutable field.
        stratege: do the same, but subtract the number of all mutable fields before
        """
        else:
            for mutable_field in self.mutable_fields:
                if mutable_field < field: field -= 1
                else: break
        return field
    def vals(self):
        result = self._get_full_list()
        if self.super is not None:
            return self.super.vals() + result
        else:
            return result
    def ref(self, struct_id, field):
        if self.type == struct_id:
            return self._get_list(self.map(field)) if field not in self.mutable_fields else self.mutable_vals[self.map(field)]
        elif self.type.value == struct_id.value:
            raise SchemeException("given value instantiates a different structure type with the same name")
        elif self.super is not None:
            return self.super.ref(struct_id, field)
        else:
            assert False
    def set(self, struct_id, field, val):
        type = jit.promote(self.type)
        if type == struct_id:
            self.mutable_vals[self.map(field)] = val
        else:
            assert isinstance(self.super, W_Struct)
            self.super.set(struct_id, field, val)
    def tostring(self):
        if self.isopaque:
            result =  "#<%s>" % self.type.value
        else:
            result = "(%s %s)" % (self.type.value, ' '.join([val.tostring() for val in self.vals()]))
        return result
inline_small_list(W_Struct, immutable=True, attrname="immutable_vals")
<commit_msg>replace temporally comment with docstring<commit_after>from pycket.cont import continuation
from pycket.error import SchemeException
from pycket.values import from_list, w_false, w_true, W_Object, W_Fixnum, W_SimplePrim, W_Symbol, w_null
from pycket.small_list import inline_small_list
from rpython.rlib import jit

#
# Structs are partially supported
#
# Not implemented:
# 1) prefab -- '#s(sprout bean): need update in expand.rkt
# 2) methods overriding (including equal) -- generic-interfaces.rkt
# 3) properties and super as an argument -- kw.rkt

# TODO: inspector currently does nothing
class W_StructInspector(W_Object):
    errorname = "struct-inspector"
    _immutable_fields_ = ["super"]

    @staticmethod
    def make(inspector, issibling = False):
        super = inspector
        if issibling:
            super = inspector.super if inspector is not None else None
        return W_StructInspector(super)

    def __init__(self, super):
        self.super = super

current_inspector = W_StructInspector(None)

class W_StructType(W_Object):
    all_structs = {}
    errorname = "struct-type"
    _immutable_fields_ = ["id", "super", "init_field_cnt", "auto_field_cnt", "auto_v", "inspector", "immutables", "guard", "constr_name"]
    @staticmethod
    def make(name, super_type, init_field_cnt, auto_field_cnt, auto_v, props, inspector, proc_spec, immutables, guard, constr_name):
        struct_id = W_StructTypeDescriptor(name.value)
        W_StructType.all_structs[struct_id] = w_result = W_StructType(struct_id, super_type, init_field_cnt, auto_field_cnt, auto_v, \
            props, inspector, proc_spec, immutables, guard, constr_name)
        return w_result

    @staticmethod
    def lookup_struct_type(struct_id):
        if struct_id in W_StructType.all_structs:
            return W_StructType.all_structs[struct_id]
        else:
            return w_false

    def __init__(self, struct_id, super_type, init_field_cnt, auto_field_cnt, \
            auto_v, props, inspector, proc_spec, immutables, guard, constr_name):
        self.super = W_StructType.lookup_struct_type(super_type) if super_type != w_false else None
        self.init_field_cnt = init_field_cnt.value
        self.auto_field_cnt = auto_field_cnt.value
        # Next arguments are optional
        self.auto_v = auto_v
        # self.props = props
        self.inspector = inspector
        # self.proc_spec = proc_spec
        self.immutables = immutables
        self.guard = guard
        if isinstance(constr_name, W_Symbol):
            self.constr_name = constr_name.value
        else:
            self.constr_name = "make-" + struct_id.value

        self.isopaque = True if self.inspector != w_false else False
        self.mutable_fields = []

        self.id = struct_id
        self.constr = W_StructConstructor(self.id, self.super, self.init_field_cnt, self.auto_field_cnt, self.auto_v, \
            self.mutable_fields, self.isopaque, self.guard, self.constr_name)
        self.pred = W_StructPredicate(self.id)
        self.acc = W_StructAccessor(self.id)
        self.mut = W_StructMutator(self.id)
    def constructor(self):
        return self.constr
    def set_mutable(self, field):
        assert isinstance(field, W_Fixnum)
        self.mutable_fields.append(field.value)
    def make_struct_tuple(self):
        return [self.id, self.constr, self.pred, self.acc, self.mut]

class W_StructTypeDescriptor(W_Object):
    errorname = "struct-type-descriptor"
    _immutable_fields_ = ["value"]
    def __init__(self, value):
        self.value = value
    def tostring(self):
        return "#<struct-type:%s>" % self.value

class W_StructConstructor(W_SimplePrim):
    _immutable_fields_ = ["struct_id", "super_type", "init_field_cnt", "auto_values", "isopaque", "guard", "name"]
    def __init__ (self, struct_id, super_type, init_field_cnt, auto_field_cnt, auto_v, mutable_fields, isopaque, guard, name):
        self.struct_id = struct_id
        self.super_type = super_type
        self.init_field_cnt = init_field_cnt
        self.auto_values = [auto_v] * auto_field_cnt
        self.mutable_fields = mutable_fields
        self.isopaque = isopaque
        self.guard = guard
        self.name = name
    def extcode(self, field_values, env, cont):
        if self.guard != w_false:
            cont = guard_check(self.guard, field_values, env, cont)
        super = None
        if isinstance(self.super_type, W_StructType):
            def split_list(list, num):
                assert num >= 0
                return list[:num], list[num:]
            split_position = len(field_values) - self.init_field_cnt
            super_field_values, field_values = split_list(field_values, split_position)
            super, env, cont = self.super_type.constructor().extcode(super_field_values, env, cont)
        vals = field_values + self.auto_values
        immutable_vals, mutable_vals = [], []
        for idx, val in enumerate(vals):
            if idx in self.mutable_fields: mutable_vals.append(val)
            else: immutable_vals.append(val)
        result = W_Struct.make(immutable_vals, self.mutable_fields, mutable_vals, self.struct_id, super, self.isopaque)
        return result, env, cont
    def call(self, args, env, cont):
        from pycket.interpreter import return_value
        result, env, cont = self.extcode(args, env, cont)
        return return_value(result, env, cont)
    def tostring(self):
        return "#<procedure:%s>" % self.name

@continuation
def guard_check(proc, field_values, env, cont, _vals):
    vals = _vals._get_full_list()
    struct = vals[0]
    assert isinstance(struct, W_Struct)
    args = [struct.type] + field_values
    return proc.call(args, env, cont)

class W_StructProperty(W_Object):
    errorname = "struct-type-property"
    _immutable_fields_ = ["name", "guard", "supers", "can_imp"]
    def __init__(self, name, guard, supers=w_null, can_imp=False):
        self.name = name
        self.guard = guard
        self.supers = supers
        self.can_imp = can_imp
    def tostring(self):
        return "#<struct-type-property:%s>"%self.name

class W_StructPropertyPredicate(W_SimplePrim):
    errorname = "struct-property-predicate"
    _immutable_fields_ = ["property"]
    def __init__(self, prop):
        self.property = prop
    def code(self, args):
        raise SchemeException("StructPropertyPredicate NYI")

class W_StructPropertyAccessor(W_SimplePrim):
    errorname = "struct-property-accessor"
    _immutable_fields_ = ["property"]
    def __init__(self, prop):
        self.property = prop
    def code(self, args):
        raise SchemeException("StructPropertyAccessor NYI")

class W_StructPredicate(W_SimplePrim):
    errorname = "struct-predicate"
    _immutable_fields_ = ["struct_id"]
    def __init__ (self, struct_id):
        self.struct_id = struct_id
    def code(self, args):
        struct = args[0]
        result = w_false
        if (isinstance(struct, W_Struct)):
            while True:
                if struct.type == self.struct_id:
                    result = w_true
                    break
                if struct.super is None: break
                else: struct = struct.super
        return result
    def tostring(self):
        return "#<procedure:%s?>" % self.struct_id.value

class W_StructFieldAccessor(W_SimplePrim):
    errorname = "struct-field-accessor"
    _immutable_fields_ = ["accessor", "field"]
    def __init__ (self, accessor, field):
        assert isinstance(accessor, W_StructAccessor)
        self.accessor = accessor
        self.field = field
    def code(self, args):
        struct = args[0]
        return self.accessor.code([struct, self.field])

class W_StructAccessor(W_SimplePrim):
    errorname = "struct-accessor"
    _immutable_fields_ = ["struct_id"]
    def __init__ (self, struct_id):
        self.struct_id = struct_id
    def code(self, args):
        struct, field = args
        assert isinstance(struct, W_Struct)
        assert isinstance(field, W_Fixnum)
        return struct.ref(self.struct_id, field.value)
    def tostring(self):
        return "#<procedure:%s-ref>" % self.struct_id.value

class W_StructFieldMutator(W_SimplePrim):
    errorname = "struct-field-mutator"
    _immutable_fields_ = ["mutator", "field"]
    def __init__ (self, mutator, field):
        assert isinstance(mutator, W_StructMutator)
        self.mutator = mutator
        self.field = field
        mutator.set_mutable(field)
    def code(self, args):
        struct = args[0]
        val = args[1]
        return self.mutator.code([struct, self.field, val])

class W_StructMutator(W_SimplePrim):
    errorname = "struct-mutator"
    _immutable_fields_ = ["struct_id"]
    def __init__ (self, struct_id):
        self.struct_id = struct_id
    def code(self, args):
        struct, field, val = args
        assert isinstance(struct, W_Struct)
        assert isinstance(field, W_Fixnum)
        struct.set(self.struct_id, field.value, val)
    def set_mutable(self, field):
        struct = W_StructType.lookup_struct_type(self.struct_id)
        struct.set_mutable(field)
    def tostring(self):
        return "#<procedure:%s-set!>" % self.struct_id.value

class W_Struct(W_Object):
    errorname = "struct"
    _immutable_fields_ = ["mutable_fields", "mutable_vals", "type", "super", "isopaque"]
    def __init__(self, mutable_fields, mutable_vals, struct_id, super, isopaque):
        self.mutable_fields = mutable_fields
        self.mutable_vals = mutable_vals
        self.type = struct_id
        self.super = super
        self.isopaque = isopaque
    # FIXME: make me more beautiful
    @jit.elidable
    def map(self, field):
        """
        Example:
        original struct values: (a: mutable, b: mutable, c: immutable)
        stored data:
          immutable_vals: (0: c) -- saved inline
          mutable_vals: (0: a, 1: b)
          mutable_fields: (0, 1)

        1. field (int) is a mutable field (self.mutable_fields is an array of integers)
        strategy: find all immutable fields before and subtract this number from field index
        2. field is an immutable field.
        stratege: do the same, but subtract the number of all mutable fields before
        """
        if field in self.mutable_fields:
            for immutable_field in [item for item in xrange(field) if item not in self.mutable_fields]:
                if immutable_field < field: field -= 1
                else: break
        else:
            for mutable_field in self.mutable_fields:
                if mutable_field < field: field -= 1
                else: break
        return field
    def vals(self):
        result = self._get_full_list()
        if self.super is not None:
            return self.super.vals() + result
        else:
            return result
    def ref(self, struct_id, field):
        if self.type == struct_id:
            return self._get_list(self.map(field)) if field not in self.mutable_fields else self.mutable_vals[self.map(field)]
        elif self.type.value == struct_id.value:
            raise SchemeException("given value instantiates a different structure type with the same name")
        elif self.super is not None:
            return self.super.ref(struct_id, field)
        else:
            assert False
    def set(self, struct_id, field, val):
        type = jit.promote(self.type)
        if type == struct_id:
            self.mutable_vals[self.map(field)] = val
        else:
            assert isinstance(self.super, W_Struct)
            self.super.set(struct_id, field, val)
    def tostring(self):
        if self.isopaque:
            result =  "#<%s>" % self.type.value
        else:
            result = "(%s %s)" % (self.type.value, ' '.join([val.tostring() for val in self.vals()]))
        return result
inline_small_list(W_Struct, immutable=True, attrname="immutable_vals")
<|endoftext|>


<commit_before>import os
import shutil
import requests
from requests.auth import HTTPDigestAuth
from collections import namedtuple
import string

SERVER = 'http://localhost:8000'
DOMAIN = 'uth-rhd'
URL = "%s/a/%s" % (SERVER, DOMAIN)

# SCANNER_DIR = '/Users/tyler/code/dimagi/uth-rhd-code/vscan/'
# SCANNER_DIR = '/Volumes/NO NAME'
# SCANNER_DIR = '/Users/tyler/Desktop'
# SCANNER_DIR = '/Volumes/PENDRIVE'

try:
    # find first windows drive with the special scanner file present
    SCANNER_DIR = ['%s:' % d for d in string.uppercase if os.path.exists(
        os.path.join('%s:' % d, 'Archive', 'ScannerID.GEUSHH')
    )][0]
except IndexError:
    SCANNER_DIR = None

ARCHIVE_PATH = os.path.join(SCANNER_DIR or '', 'Archive')

class Exam(object):
    def __init__(self, directory, serial, scan_id, date):
        self.serial = serial
        self.scan_id = scan_id
        self.date = date
        self.directory = directory

        self.files = self.collect_files()

    def collect_files(self):
        files = os.listdir(self.directory)
        for f in files:
            if f not in ['.', '..']:
                yield f

def parse_archive():
    exams = os.listdir(ARCHIVE_PATH)
    for exam in exams:
        exam_dir = os.path.join(ARCHIVE_PATH, exam)
        if exam not in ['.', '..'] and os.path.isdir(exam_dir):
            yield Exam(exam_dir, *exam.split('_'))

def pack_directory(directory):
    # name of the test directory we're packing
    test_dir_name = os.path.split(directory)[1]

    packed_directory = {}

    for root, dirs, files in os.walk(directory):
        for f in files:
            relative_path = os.path.join(test_dir_name, f)
            packed_directory[relative_path] = open(os.path.join(root, f), 'rb')

    return packed_directory

def upload_exam(exam, index, total_count, retry_count=0):
    print ""
    print "Uploading exam %s of %s." % (index + 1, total_count)
    files = pack_directory(exam.directory)

    r = requests.post(
        url=URL + '/vscan_upload',
        auth=HTTPDigestAuth('t@w.com', 'asdf'),
        files=files,
        data={
            'scanner_serial': exam.serial,
            'scan_id': exam.scan_id,
            'scan_time': exam.date
        },
    )
    print "Processed exam: %s" % os.path.split(exam.directory)[-1]
    print "Result code: %s" % r.status_code

    if r.status_code == 200:
        print "Result: %s" % r.json()['result']
        print "Message: %s" % r.json()['message']

        #current_dir = os.path.dirname(os.path.realpath(__file__))
        #shutil.move(
            #exam.directory,
            #os.path.join(current_dir, 'complete')
        #)

    else:
        print "Result: Failed"

    return r

def upload():
    print "Checking exams"
    exams = list(parse_archive())
    print "Done checking exams"

    failed_uploads = []
    FailedUpload = namedtuple(
        'FailedUpload', 'exam exam_index failure_count'
    )

    for i, exam in enumerate(exams):
        result = upload_exam(exam, i, len(exams))

        if result.status_code != 200:
            failed_uploads.append(FailedUpload(
                exam,
                i,
                1
            ))

    while len(failed_uploads):
        current_upload = failed_uploads.pop()
        print "\nRetrying exam %s, attempt %s" % (
            current_upload.exam_index + 1,
            current_upload.failure_count
        )

        result = upload_exam(
            current_upload.exam,
            current_upload.exam_index,
            current_upload.failure_count
        )

        if result.status_code != 200 and current_upload.failure_count < 3:
            failed_uploads.append(FailedUpload(
                current_upload.exam,
                current_upload.exam_index,
                current_upload.failure_count + 1
            ))

if __name__ == '__main__':
    if SCANNER_DIR:
        try:
            upload()
        except Exception as e:
            print e
        print('\nUploading complete. Press enter to exit.')
        raw_input()
    else:
        print "Vscan not found"
<commit_msg>Ignore bad directories<commit_after>import os
import shutil
import requests
from requests.auth import HTTPDigestAuth
from collections import namedtuple
import string

SERVER = 'http://localhost:8000'
DOMAIN = 'uth-rhd'
URL = "%s/a/%s" % (SERVER, DOMAIN)

# SCANNER_DIR = '/Users/tyler/code/dimagi/uth-rhd-code/vscan/'
# SCANNER_DIR = '/Volumes/NO NAME'
# SCANNER_DIR = '/Users/tyler/Desktop'
# SCANNER_DIR = '/Volumes/PENDRIVE'

try:
    # find first windows drive with the special scanner file present
    SCANNER_DIR = ['%s:' % d for d in string.uppercase if os.path.exists(
        os.path.join('%s:' % d, 'Archive', 'ScannerID.GEUSHH')
    )][0]
except IndexError:
    SCANNER_DIR = None

ARCHIVE_PATH = os.path.join(SCANNER_DIR or '', 'Archive')

class Exam(object):
    def __init__(self, directory, serial, scan_id, date):
        self.serial = serial
        self.scan_id = scan_id
        self.date = date
        self.directory = directory

        self.files = self.collect_files()

    def collect_files(self):
        files = os.listdir(self.directory)
        for f in files:
            if f not in ['.', '..']:
                yield f

def parse_archive():
    exams = os.listdir(ARCHIVE_PATH)
    for exam in exams:
        exam_dir = os.path.join(ARCHIVE_PATH, exam)
        if exam not in ['.', '..'] and os.path.isdir(exam_dir):
            try:
                yield Exam(exam_dir, *exam.split('_'))
            except Exception:
                # if the directory doesn't resemble an exam, we don't
                # care about the error or the directory
                continue

def pack_directory(directory):
    # name of the test directory we're packing
    test_dir_name = os.path.split(directory)[1]

    packed_directory = {}

    for root, dirs, files in os.walk(directory):
        for f in files:
            relative_path = os.path.join(test_dir_name, f)
            packed_directory[relative_path] = open(os.path.join(root, f), 'rb')

    return packed_directory

def upload_exam(exam, index, total_count, retry_count=0):
    print ""
    print "Uploading exam %s of %s." % (index + 1, total_count)
    files = pack_directory(exam.directory)

    r = requests.post(
        url=URL + '/vscan_upload',
        auth=HTTPDigestAuth('t@w.com', 'asdf'),
        files=files,
        data={
            'scanner_serial': exam.serial,
            'scan_id': exam.scan_id,
            'scan_time': exam.date
        },
    )
    print "Processed exam: %s" % os.path.split(exam.directory)[-1]
    print "Result code: %s" % r.status_code

    if r.status_code == 200:
        print "Result: %s" % r.json()['result']
        print "Message: %s" % r.json()['message']

        #current_dir = os.path.dirname(os.path.realpath(__file__))
        #shutil.move(
            #exam.directory,
            #os.path.join(current_dir, 'complete')
        #)

    else:
        print "Result: Failed"

    return r

def upload():
    print "Checking exams"
    exams = list(parse_archive())
    print "Done checking exams"

    failed_uploads = []
    FailedUpload = namedtuple(
        'FailedUpload', 'exam exam_index failure_count'
    )

    for i, exam in enumerate(exams):
        result = upload_exam(exam, i, len(exams))

        if result.status_code != 200:
            failed_uploads.append(FailedUpload(
                exam,
                i,
                1
            ))

    while len(failed_uploads):
        current_upload = failed_uploads.pop()
        print "\nRetrying exam %s, attempt %s" % (
            current_upload.exam_index + 1,
            current_upload.failure_count
        )

        result = upload_exam(
            current_upload.exam,
            current_upload.exam_index,
            current_upload.failure_count
        )

        if result.status_code != 200 and current_upload.failure_count < 3:
            failed_uploads.append(FailedUpload(
                current_upload.exam,
                current_upload.exam_index,
                current_upload.failure_count + 1
            ))

if __name__ == '__main__':
    if SCANNER_DIR:
        try:
            upload()
        except Exception as e:
            print e
        print('\nUploading complete. Press enter to exit.')
        raw_input()
    else:
        print "Vscan not found"
<|endoftext|>


<commit_before>import unreal_engine as ue
from unreal_engine.classes import K2Node_InputKey, K2Node_SpawnActorFromClass, Actor, Character, KismetMathLibrary

# create  a new blueprint
new_blueprint = ue.create_blueprint(Actor, '/Game/StrangeBlueprint')

# add a member float variable
ue.blueprint_add_member_variable(new_blueprint, 'Speed', 'float')

# get a reference to the first graph page
uber_page = new_blueprint.UberGraphPages[0]

# get good coordinates for a new node
x, y = uber_page.graph_get_good_place_for_new_node()
# add the Speed variable to the graph
uber_page.graph_add_node_variable_get('Speed', None, x, y)

x, y = uber_page.graph_get_good_place_for_new_node()
# add a custom event to the graph
hello_world = uber_page.graph_add_node_custom_event('Hello World', x, y)

# get a reference to the 'then' pin
hello_world_then = hello_world.node_find_pin('then')

x, y = uber_page.graph_get_good_place_for_new_node()
# add a 'Spawn Actor From Class' node
spawn_actor_node = uber_page.graph_add_node(K2Node_SpawnActorFromClass, x, y)

# set its Class pin
pin_class = spawn_actor_node.node_find_pin('Class')
pin_class.default_object = Character

# get a reference to its 'exec' pin
spawn_actor_node_exec = spawn_actor_node.node_find_pin('execute')

# link the hello world event to the spawn actor node
hello_world_then.make_link_to(spawn_actor_node_exec)

x, y = uber_page.graph_get_good_place_for_new_node()
# create a 'make transform' node
make_transform = uber_page.graph_add_node_call_function(KismetMathLibrary.MakeTransform, x, y)

# link the return value of 'make transform' to the 'SpawnTransform' pin of the spawn actor node
make_transform.node_find_pin('ReturnValue').make_link_to(spawn_actor_node.node_find_pin('SpawnTransform'))

input_key = K2Node_InputKey()
# TODO implement the FKey struct
#input_key.InputKey = ???
input_key_node = uber_page.graph_add_node(input_key, 400, 400)

# compile the blueprint
ue.compile_blueprint(new_blueprint)

# save it
ue.editor_save_all()
<commit_msg>Update graphs_creator.py<commit_after>import unreal_engine as ue
from unreal_engine.classes import K2Node_InputKey, K2Node_SpawnActorFromClass, Actor, Character, KismetMathLibrary
from unreal_engine.structs import Key

# create  a new blueprint
new_blueprint = ue.create_blueprint(Actor, '/Game/StrangeBlueprint')

# add a member float variable
ue.blueprint_add_member_variable(new_blueprint, 'Speed', 'float')

# get a reference to the first graph page
uber_page = new_blueprint.UberGraphPages[0]

# get good coordinates for a new node
x, y = uber_page.graph_get_good_place_for_new_node()
# add the Speed variable to the graph
uber_page.graph_add_node_variable_get('Speed', None, x, y)

x, y = uber_page.graph_get_good_place_for_new_node()
# add a custom event to the graph
hello_world = uber_page.graph_add_node_custom_event('Hello World', x, y)

# get a reference to the 'then' pin
hello_world_then = hello_world.node_find_pin('then')

x, y = uber_page.graph_get_good_place_for_new_node()
# add a 'Spawn Actor From Class' node
spawn_actor_node = uber_page.graph_add_node(K2Node_SpawnActorFromClass, x, y)

# set its Class pin
pin_class = spawn_actor_node.node_find_pin('Class')
pin_class.default_object = Character

# get a reference to its 'exec' pin
spawn_actor_node_exec = spawn_actor_node.node_find_pin('execute')

# link the hello world event to the spawn actor node
hello_world_then.make_link_to(spawn_actor_node_exec)

x, y = uber_page.graph_get_good_place_for_new_node()
# create a 'make transform' node
make_transform = uber_page.graph_add_node_call_function(KismetMathLibrary.MakeTransform, x, y)

# link the return value of 'make transform' to the 'SpawnTransform' pin of the spawn actor node
make_transform.node_find_pin('ReturnValue').make_link_to(spawn_actor_node.node_find_pin('SpawnTransform'))

input_key = K2Node_InputKey()
input_key.InputKey = Key(KeyName='SpaceBar')
input_key_node = uber_page.graph_add_node(input_key, 400, 400)

# compile the blueprint
ue.compile_blueprint(new_blueprint)

# save it
ue.editor_save_all()
<|endoftext|>


<commit_before>#!/usr/bin/env python3
# Copyright (c) 2019 The PIVX developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.

from test_framework.authproxy import JSONRPCException
from test_framework.test_framework import PivxTestFramework
from test_framework.util import (
    sync_blocks,
    assert_equal,
    assert_raises_rpc_error,
    connect_nodes_bi,
    connect_nodes_clique,
    disconnect_nodes,
    set_node_times,
    DecimalAmt,
)

class ReorgStakeTest(PivxTestFramework):

    def set_test_params(self):
        self.num_nodes = 3
        # node 0 and 1 stake the blocks, node 2 makes the zerocoin spends

    def setup_chain(self):
        # Start with PoS cache: 330 blocks
        self._initialize_chain(toPosPhase=True)
        self.enable_mocktime()

    def setup_network(self):
        # connect all nodes between each other
        self.setup_nodes()
        connect_nodes_clique(self.nodes)
        self.sync_all()

    def log_title(self):
        title = "*** Starting %s ***" % self.__class__.__name__
        underline = "-" * len(title)
        description = "Tests reorganisation for PoS blocks."
        self.log.info("\n\n%s\n%s\n%s\n", title, underline, description)

    def disconnect_all(self):
        self.log.info("Disconnecting nodes...")
        for i in range(self.num_nodes):
            for j in range(self.num_nodes):
                if j != i:
                    disconnect_nodes(self.nodes[i], j)
        self.log.info("Nodes disconnected")

    def get_tot_balance(self, nodeid):
        wi = self.nodes[nodeid].getwalletinfo()
        return wi['balance'] + wi['immature_balance']

    def run_test(self):

        def findUtxoInList(txid, vout, utxo_list):
            for x in utxo_list:
                if x["txid"] == txid and x["vout"] == vout:
                    return True, x
            return False, None

        # Stake with node 0 and node 1 up to public spend activation (400)
        # 70 blocks: 5 blocks each (x7)
        self.log.info("Staking 70 blocks to reach public spends activation...")
        set_node_times(self.nodes, self.mocktime)
        for i in range(7):
            for peer in range(2):
                for nblock in range(5):
                    self.mocktime = self.generate_pos(peer, self.mocktime)
                sync_blocks(self.nodes)
        block_time_0 = block_time_1 = self.mocktime
        self.log.info("Blocks staked.")

        # Check balances
        self.log.info("Checking balances...")
        initial_balance = [self.get_tot_balance(i) for i in range(self.num_nodes)]
        # --nodes 0, 1: 62 pow blocks + 55 pos blocks
        assert_equal(initial_balance[0], DecimalAmt(250.0 * (62 + 55)))
        assert_equal(initial_balance[1], DecimalAmt(250.0 * (62 + 55)))
        # --node 2: 62 pow blocks + 20 pos blocks - zc minted - zcfee
        assert_equal(initial_balance[2], DecimalAmt(250.0 * (62 + 20) - 6666 - 0.08))
        assert_equal(self.nodes[2].getzerocoinbalance()['Total'], DecimalAmt(6666))
        self.log.info("Balances ok.")

        # create the raw zerocoin spend txes
        addy = self.nodes[2].getnewaddress()
        self.log.info("Creating the raw zerocoin public spends...")
        mints = self.nodes[2].listmintedzerocoins(True, True)
        tx_A0 = self.nodes[2].createrawzerocoinspend(mints[0]["serial hash"], addy)
        tx_A1 = self.nodes[2].createrawzerocoinspend(mints[1]["serial hash"], addy)
        # Spending same coins to different recipients to get different txids
        new_addy = "yAVWM5urwaTyhiuFQHP2aP47rdZsLUG5PH"
        tx_B0 = self.nodes[2].createrawzerocoinspend(mints[0]["serial hash"], new_addy)
        tx_B1 = self.nodes[2].createrawzerocoinspend(mints[1]["serial hash"], new_addy)

        # Disconnect nodes
        minted_amount = mints[0]["denomination"] + mints[1]["denomination"]
        self.disconnect_all()

        # Stake one block with node-0 and save the stake input
        self.log.info("Staking 1 block with node 0...")
        initial_unspent_0 = self.nodes[0].listunspent()
        self.nodes[0].generate(1)
        block_time_0 += 60
        set_node_times(self.nodes, block_time_0)
        last_block = self.nodes[0].getblock(self.nodes[0].getbestblockhash())
        assert(len(last_block["tx"]) > 1)                                       # a PoS block has at least two txes
        coinstake_txid = last_block["tx"][1]
        coinstake_tx = self.nodes[0].getrawtransaction(coinstake_txid, True)
        assert(coinstake_tx["vout"][0]["scriptPubKey"]["hex"] == "")            # first output of coinstake is empty
        stakeinput = coinstake_tx["vin"][0]

        # The stake input was unspent 1 block ago, now it's not
        res, utxo = findUtxoInList(stakeinput["txid"], stakeinput["vout"], initial_unspent_0)
        assert (res and utxo["spendable"])
        res, utxo = findUtxoInList(stakeinput["txid"], stakeinput["vout"], self.nodes[0].listunspent())
        assert (not res or not utxo["spendable"])
        self.log.info("Coinstake input %s...%s-%d is no longer spendable." % (
            stakeinput["txid"][:9], stakeinput["txid"][-4:], stakeinput["vout"]))

        # Relay zerocoin spends
        self.nodes[0].sendrawtransaction(tx_A0)
        self.nodes[0].sendrawtransaction(tx_A1)

        # Stake 10 more blocks with node-0 and check balances
        self.log.info("Staking 10 more blocks with node 0...")
        for i in range(10):
            block_time_0 = self.generate_pos(0, block_time_0)
        expected_balance_0 = initial_balance[0] + DecimalAmt(11 * 250.0)
        assert_equal(self.get_tot_balance(0), expected_balance_0)
        self.log.info("Balance for node 0 checks out.")

        # Connect with node 2, sync and check zerocoin balance
        self.log.info("Reconnecting node 0 and node 2")
        connect_nodes_bi(self.nodes, 0, 2)
        sync_blocks([self.nodes[i] for i in [0, 2]])
        self.log.info("Resetting zerocoin mints on node 2")
        self.nodes[2].resetmintzerocoin(True)
        assert_equal(self.get_tot_balance(2), initial_balance[2] + DecimalAmt(minted_amount))
        assert_equal(self.nodes[2].getzerocoinbalance()['Total'], DecimalAmt(6666-minted_amount))
        self.log.info("Balance for node 2 checks out.")

        # Double spending txes not possible
        assert_raises_rpc_error(-26, "bad-txns-invalid-zpiv",
                                self.nodes[0].sendrawtransaction, tx_B0)
        assert_raises_rpc_error(-26, "bad-txns-invalid-zpiv",
                                self.nodes[0].sendrawtransaction, tx_B1)

        # verify that the stakeinput can't be spent
        stakeinput_tx_json = self.nodes[0].getrawtransaction(stakeinput["txid"], True)
        stakeinput_amount = float(stakeinput_tx_json["vout"][int(stakeinput["vout"])]["value"])
        rawtx_unsigned = self.nodes[0].createrawtransaction(
            [{"txid": stakeinput["txid"], "vout": int(stakeinput["vout"])}],
            {"xxncEuJK27ygNh7imNfaX8JV6ZQUnoBqzN": (stakeinput_amount-0.01)})
        rawtx = self.nodes[0].signrawtransaction(rawtx_unsigned)
        assert(rawtx["complete"])
        try:
            self.nodes[0].sendrawtransaction(rawtx["hex"])
        except JSONRPCException as e:
            # JSONRPCException was thrown as expected. Check the code and message values are correct.
            if e.error["code"] not in [-26, -25]:
                raise AssertionError("Unexpected JSONRPC error code %i" % e.error["code"])
            if ([x for x in ["bad-txns-inputs-spent", "Missing inputs"] if x in e.error['message']] == []):
                raise e
        except Exception as e:
            raise AssertionError("Unexpected exception raised: " + type(e).__name__)
        self.log.info("GOOD: v2 spend was not possible.")

        # Spend tx_B0 and tx_B1 on the other chain
        self.nodes[1].sendrawtransaction(tx_B0)
        self.nodes[1].sendrawtransaction(tx_B1)

        # Stake 12 blocks with node-1
        set_node_times(self.nodes, block_time_1)
        self.log.info("Staking 12 blocks with node 1...")
        for i in range(12):
            block_time_1 = self.generate_pos(1, block_time_1)
        expected_balance_1 = initial_balance[1] + DecimalAmt(12 * 250.0)
        assert_equal(self.get_tot_balance(1), expected_balance_1)
        self.log.info("Balance for node 1 checks out.")

        # re-connect and sync nodes and check that node-0 and node-2 get on the other chain
        new_best_hash = self.nodes[1].getbestblockhash()
        self.log.info("Connecting and syncing nodes...")
        set_node_times(self.nodes, block_time_1)
        connect_nodes_clique(self.nodes)
        sync_blocks(self.nodes)
        for i in [0, 2]:
            assert_equal(self.nodes[i].getbestblockhash(), new_best_hash)

        # check balance of node-0
        assert_equal(self.get_tot_balance(0), initial_balance[0])
        self.log.info("Balance for node 0 checks out.")

        # check that NOW the original stakeinput is present and spendable
        res, utxo = findUtxoInList(stakeinput["txid"], stakeinput["vout"], self.nodes[0].listunspent())
        assert (res and utxo["spendable"])
        self.log.info("Coinstake input %s...%s-%d is spendable again." % (
            stakeinput["txid"][:9], stakeinput["txid"][-4:], stakeinput["vout"]))
        self.nodes[0].sendrawtransaction(rawtx["hex"])
        self.nodes[1].generate(1)
        sync_blocks(self.nodes)
        res, utxo = findUtxoInList(stakeinput["txid"], stakeinput["vout"], self.nodes[0].listunspent())
        assert (not res or not utxo["spendable"])

if __name__ == '__main__':
    ReorgStakeTest().main()<commit_msg>[Tests] Fix mining_pos_reorg (coinstake first output not empty now)<commit_after>#!/usr/bin/env python3
# Copyright (c) 2019 The PIVX developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.

from test_framework.authproxy import JSONRPCException
from test_framework.test_framework import PivxTestFramework
from test_framework.util import (
    sync_blocks,
    assert_equal,
    assert_raises_rpc_error,
    connect_nodes_bi,
    connect_nodes_clique,
    disconnect_nodes,
    set_node_times,
    DecimalAmt,
)

class ReorgStakeTest(PivxTestFramework):

    def set_test_params(self):
        self.num_nodes = 3
        # node 0 and 1 stake the blocks, node 2 makes the zerocoin spends

    def setup_chain(self):
        # Start with PoS cache: 330 blocks
        self._initialize_chain(toPosPhase=True)
        self.enable_mocktime()

    def setup_network(self):
        # connect all nodes between each other
        self.setup_nodes()
        connect_nodes_clique(self.nodes)
        self.sync_all()

    def log_title(self):
        title = "*** Starting %s ***" % self.__class__.__name__
        underline = "-" * len(title)
        description = "Tests reorganisation for PoS blocks."
        self.log.info("\n\n%s\n%s\n%s\n", title, underline, description)

    def disconnect_all(self):
        self.log.info("Disconnecting nodes...")
        for i in range(self.num_nodes):
            for j in range(self.num_nodes):
                if j != i:
                    disconnect_nodes(self.nodes[i], j)
        self.log.info("Nodes disconnected")

    def get_tot_balance(self, nodeid):
        wi = self.nodes[nodeid].getwalletinfo()
        return wi['balance'] + wi['immature_balance']

    def run_test(self):

        def findUtxoInList(txid, vout, utxo_list):
            for x in utxo_list:
                if x["txid"] == txid and x["vout"] == vout:
                    return True, x
            return False, None

        # Stake with node 0 and node 1 up to public spend activation (400)
        # 70 blocks: 5 blocks each (x7)
        self.log.info("Staking 70 blocks to reach public spends activation...")
        set_node_times(self.nodes, self.mocktime)
        for i in range(7):
            for peer in range(2):
                for nblock in range(5):
                    self.mocktime = self.generate_pos(peer, self.mocktime)
                sync_blocks(self.nodes)
        block_time_0 = block_time_1 = self.mocktime
        self.log.info("Blocks staked.")

        # Check balances
        self.log.info("Checking balances...")
        initial_balance = [self.get_tot_balance(i) for i in range(self.num_nodes)]
        # --nodes 0, 1: 62 pow blocks + 55 pos blocks
        assert_equal(initial_balance[0], DecimalAmt(250.0 * (62 + 55)))
        assert_equal(initial_balance[1], DecimalAmt(250.0 * (62 + 55)))
        # --node 2: 62 pow blocks + 20 pos blocks - zc minted - zcfee
        assert_equal(initial_balance[2], DecimalAmt(250.0 * (62 + 20) - 6666 - 0.08))
        assert_equal(self.nodes[2].getzerocoinbalance()['Total'], DecimalAmt(6666))
        self.log.info("Balances ok.")

        # create the raw zerocoin spend txes
        addy = self.nodes[2].getnewaddress()
        self.log.info("Creating the raw zerocoin public spends...")
        mints = self.nodes[2].listmintedzerocoins(True, True)
        tx_A0 = self.nodes[2].createrawzerocoinspend(mints[0]["serial hash"], addy)
        tx_A1 = self.nodes[2].createrawzerocoinspend(mints[1]["serial hash"], addy)
        # Spending same coins to different recipients to get different txids
        new_addy = "yAVWM5urwaTyhiuFQHP2aP47rdZsLUG5PH"
        tx_B0 = self.nodes[2].createrawzerocoinspend(mints[0]["serial hash"], new_addy)
        tx_B1 = self.nodes[2].createrawzerocoinspend(mints[1]["serial hash"], new_addy)

        # Disconnect nodes
        minted_amount = mints[0]["denomination"] + mints[1]["denomination"]
        self.disconnect_all()

        # Stake one block with node-0 and save the stake input
        self.log.info("Staking 1 block with node 0...")
        initial_unspent_0 = self.nodes[0].listunspent()
        self.nodes[0].generate(1)
        block_time_0 += 60
        set_node_times(self.nodes, block_time_0)
        last_block = self.nodes[0].getblock(self.nodes[0].getbestblockhash())
        assert(len(last_block["tx"]) > 1)                                       # a PoS block has at least two txes
        stakeinput = self.nodes[0].getrawtransaction(last_block["tx"][1], True)["vin"][0]

        # The stake input was unspent 1 block ago, now it's not
        res, utxo = findUtxoInList(stakeinput["txid"], stakeinput["vout"], initial_unspent_0)
        assert (res and utxo["spendable"])
        res, utxo = findUtxoInList(stakeinput["txid"], stakeinput["vout"], self.nodes[0].listunspent())
        assert (not res or not utxo["spendable"])
        self.log.info("Coinstake input %s...%s-%d is no longer spendable." % (
            stakeinput["txid"][:9], stakeinput["txid"][-4:], stakeinput["vout"]))

        # Relay zerocoin spends
        self.nodes[0].sendrawtransaction(tx_A0)
        self.nodes[0].sendrawtransaction(tx_A1)

        # Stake 10 more blocks with node-0 and check balances
        self.log.info("Staking 10 more blocks with node 0...")
        for i in range(10):
            block_time_0 = self.generate_pos(0, block_time_0)
        expected_balance_0 = initial_balance[0] + DecimalAmt(11 * 250.0)
        assert_equal(self.get_tot_balance(0), expected_balance_0)
        self.log.info("Balance for node 0 checks out.")

        # Connect with node 2, sync and check zerocoin balance
        self.log.info("Reconnecting node 0 and node 2")
        connect_nodes_bi(self.nodes, 0, 2)
        sync_blocks([self.nodes[i] for i in [0, 2]])
        self.log.info("Resetting zerocoin mints on node 2")
        self.nodes[2].resetmintzerocoin(True)
        assert_equal(self.get_tot_balance(2), initial_balance[2] + DecimalAmt(minted_amount))
        assert_equal(self.nodes[2].getzerocoinbalance()['Total'], DecimalAmt(6666-minted_amount))
        self.log.info("Balance for node 2 checks out.")

        # Double spending txes not possible
        assert_raises_rpc_error(-26, "bad-txns-invalid-zpiv",
                                self.nodes[0].sendrawtransaction, tx_B0)
        assert_raises_rpc_error(-26, "bad-txns-invalid-zpiv",
                                self.nodes[0].sendrawtransaction, tx_B1)

        # verify that the stakeinput can't be spent
        stakeinput_tx_json = self.nodes[0].getrawtransaction(stakeinput["txid"], True)
        stakeinput_amount = float(stakeinput_tx_json["vout"][int(stakeinput["vout"])]["value"])
        rawtx_unsigned = self.nodes[0].createrawtransaction(
            [{"txid": stakeinput["txid"], "vout": int(stakeinput["vout"])}],
            {"xxncEuJK27ygNh7imNfaX8JV6ZQUnoBqzN": (stakeinput_amount-0.01)})
        rawtx = self.nodes[0].signrawtransaction(rawtx_unsigned)
        assert(rawtx["complete"])
        try:
            self.nodes[0].sendrawtransaction(rawtx["hex"])
        except JSONRPCException as e:
            # JSONRPCException was thrown as expected. Check the code and message values are correct.
            if e.error["code"] not in [-26, -25]:
                raise AssertionError("Unexpected JSONRPC error code %i" % e.error["code"])
            if ([x for x in ["bad-txns-inputs-spent", "Missing inputs"] if x in e.error['message']] == []):
                raise e
        except Exception as e:
            raise AssertionError("Unexpected exception raised: " + type(e).__name__)
        self.log.info("GOOD: v2 spend was not possible.")

        # Spend tx_B0 and tx_B1 on the other chain
        self.nodes[1].sendrawtransaction(tx_B0)
        self.nodes[1].sendrawtransaction(tx_B1)

        # Stake 12 blocks with node-1
        set_node_times(self.nodes, block_time_1)
        self.log.info("Staking 12 blocks with node 1...")
        for i in range(12):
            block_time_1 = self.generate_pos(1, block_time_1)
        expected_balance_1 = initial_balance[1] + DecimalAmt(12 * 250.0)
        assert_equal(self.get_tot_balance(1), expected_balance_1)
        self.log.info("Balance for node 1 checks out.")

        # re-connect and sync nodes and check that node-0 and node-2 get on the other chain
        new_best_hash = self.nodes[1].getbestblockhash()
        self.log.info("Connecting and syncing nodes...")
        set_node_times(self.nodes, block_time_1)
        connect_nodes_clique(self.nodes)
        sync_blocks(self.nodes)
        for i in [0, 2]:
            assert_equal(self.nodes[i].getbestblockhash(), new_best_hash)

        # check balance of node-0
        assert_equal(self.get_tot_balance(0), initial_balance[0])
        self.log.info("Balance for node 0 checks out.")

        # check that NOW the original stakeinput is present and spendable
        res, utxo = findUtxoInList(stakeinput["txid"], stakeinput["vout"], self.nodes[0].listunspent())
        assert (res and utxo["spendable"])
        self.log.info("Coinstake input %s...%s-%d is spendable again." % (
            stakeinput["txid"][:9], stakeinput["txid"][-4:], stakeinput["vout"]))
        self.nodes[0].sendrawtransaction(rawtx["hex"])
        self.nodes[1].generate(1)
        sync_blocks(self.nodes)
        res, utxo = findUtxoInList(stakeinput["txid"], stakeinput["vout"], self.nodes[0].listunspent())
        assert (not res or not utxo["spendable"])

if __name__ == '__main__':
    ReorgStakeTest().main()<|endoftext|>


<commit_before>#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.

import uuid

from openstackclient.tests.functional.volume.v1 import common

class VolumeTests(common.BaseVolumeTests):
    """Functional tests for volume. """

    NAME = uuid.uuid4().hex
    OTHER_NAME = uuid.uuid4().hex
    HEADERS = ['"Display Name"']
    FIELDS = ['display_name']

    @classmethod
    def setUpClass(cls):
        super(VolumeTests, cls).setUpClass()
        opts = cls.get_opts(cls.FIELDS)
        raw_output = cls.openstack('volume create --size 1 ' + cls.NAME + opts)
        expected = cls.NAME + '\n'
        cls.assertOutput(expected, raw_output)

    @classmethod
    def tearDownClass(cls):
        # Rename test
        raw_output = cls.openstack(
            'volume set --name ' + cls.OTHER_NAME + ' ' + cls.NAME)
        cls.assertOutput('', raw_output)
        # Delete test
        raw_output = cls.openstack('volume delete ' + cls.OTHER_NAME)
        cls.assertOutput('', raw_output)

    def test_volume_list(self):
        opts = self.get_opts(self.HEADERS)
        raw_output = self.openstack('volume list' + opts)
        self.assertIn(self.NAME, raw_output)

    def test_volume_show(self):
        opts = self.get_opts(self.FIELDS)
        raw_output = self.openstack('volume show ' + self.NAME + opts)
        self.assertEqual(self.NAME + "\n", raw_output)

    def test_volume_properties(self):
        raw_output = self.openstack(
            'volume set --property a=b --property c=d ' + self.NAME)
        self.assertEqual("", raw_output)
        opts = self.get_opts(["properties"])
        raw_output = self.openstack('volume show ' + self.NAME + opts)
        self.assertEqual("a='b', c='d'\n", raw_output)

        raw_output = self.openstack('volume unset --property a ' + self.NAME)
        self.assertEqual("", raw_output)
        raw_output = self.openstack('volume show ' + self.NAME + opts)
        self.assertEqual("c='d'\n", raw_output)

    def test_volume_set(self):
        self.openstack('volume set --description RAMAC ' + self.NAME)
        opts = self.get_opts(["display_description", "display_name"])
        raw_output = self.openstack('volume show ' + self.NAME + opts)
        self.assertEqual("RAMAC\n" + self.NAME + "\n", raw_output)

    def test_volume_set_size(self):
        self.openstack('volume set --size 2 ' + self.NAME)
        opts = self.get_opts(["display_name", "size"])
        raw_output = self.openstack('volume show ' + self.NAME + opts)
        self.assertEqual(self.NAME + "\n2\n", raw_output)

    def test_volume_set_bootable(self):
        self.openstack('volume set --bootable ' + self.NAME)
        opts = self.get_opts(["bootable"])
        raw_output = self.openstack('volume show ' + self.NAME + opts)
        self.assertEqual("true\n", raw_output)

        self.openstack('volume set --non-bootable ' + self.NAME)
        opts = self.get_opts(["bootable"])
        raw_output = self.openstack('volume show ' + self.NAME + opts)
        self.assertEqual("false\n", raw_output)
<commit_msg>Refactor volume functional test in volume v1<commit_after>#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.

import json
import time
import uuid

from openstackclient.tests.functional.volume.v1 import common

class VolumeTests(common.BaseVolumeTests):
    """Functional tests for volume. """

    def test_volume_create_and_delete(self):
        """Test create, delete multiple"""
        name1 = uuid.uuid4().hex
        cmd_output = json.loads(self.openstack(
            'volume create -f json ' +
            '--size 1 ' +
            name1
        ))
        self.assertEqual(
            1,
            cmd_output["size"],
        )

        name2 = uuid.uuid4().hex
        cmd_output = json.loads(self.openstack(
            'volume create -f json ' +
            '--size 2 ' +
            name2
        ))
        self.assertEqual(
            2,
            cmd_output["size"],
        )

        self.wait_for("volume", name1, "available")
        self.wait_for("volume", name2, "available")
        del_output = self.openstack('volume delete ' + name1 + ' ' + name2)
        self.assertOutput('', del_output)

    def test_volume_list(self):
        """Test create, list filter"""
        name1 = uuid.uuid4().hex
        cmd_output = json.loads(self.openstack(
            'volume create -f json ' +
            '--size 1 ' +
            name1
        ))
        self.addCleanup(self.openstack, 'volume delete ' + name1)
        self.assertEqual(
            1,
            cmd_output["size"],
        )
        self.wait_for("volume", name1, "available")

        name2 = uuid.uuid4().hex
        cmd_output = json.loads(self.openstack(
            'volume create -f json ' +
            '--size 2 ' +
            name2
        ))
        self.addCleanup(self.openstack, 'volume delete ' + name2)
        self.assertEqual(
            2,
            cmd_output["size"],
        )
        self.wait_for("volume", name2, "available")

        # Test list
        cmd_output = json.loads(self.openstack(
            'volume list -f json '
        ))
        names = [x["Display Name"] for x in cmd_output]
        self.assertIn(name1, names)
        self.assertIn(name2, names)

        # Test list --long
        cmd_output = json.loads(self.openstack(
            'volume list -f json --long'
        ))
        bootable = [x["Bootable"] for x in cmd_output]
        self.assertIn('false', bootable)

        # Test list --name
        cmd_output = json.loads(self.openstack(
            'volume list -f json ' +
            '--name ' + name1
        ))
        names = [x["Display Name"] for x in cmd_output]
        self.assertIn(name1, names)
        self.assertNotIn(name2, names)

    def test_volume_set_and_unset(self):
        """Tests create volume, set, unset, show, delete"""
        name = uuid.uuid4().hex
        cmd_output = json.loads(self.openstack(
            'volume create -f json ' +
            '--size 1 ' +
            '--description aaaa ' +
            '--property Alpha=a ' +
            name
        ))
        self.assertEqual(
            name,
            cmd_output["display_name"],
        )
        self.assertEqual(
            1,
            cmd_output["size"],
        )
        self.assertEqual(
            'aaaa',
            cmd_output["display_description"],
        )
        self.assertEqual(
            "Alpha='a'",
            cmd_output["properties"],
        )
        self.assertEqual(
            'false',
            cmd_output["bootable"],
        )
        self.wait_for("volume", name, "available")

        # Test volume set
        new_name = uuid.uuid4().hex
        self.addCleanup(self.openstack, 'volume delete ' + new_name)
        raw_output = self.openstack(
            'volume set ' +
            '--name ' + new_name +
            ' --size 2 ' +
            '--description bbbb ' +
            '--property Alpha=c ' +
            '--property Beta=b ' +
            '--bootable ' +
            name,
        )
        self.assertOutput('', raw_output)

        cmd_output = json.loads(self.openstack(
            'volume show -f json ' +
            new_name
        ))
        self.assertEqual(
            new_name,
            cmd_output["display_name"],
        )
        self.assertEqual(
            2,
            cmd_output["size"],
        )
        self.assertEqual(
            'bbbb',
            cmd_output["display_description"],
        )
        self.assertEqual(
            "Alpha='c', Beta='b'",
            cmd_output["properties"],
        )
        self.assertEqual(
            'true',
            cmd_output["bootable"],
        )

        # Test volume unset
        raw_output = self.openstack(
            'volume unset ' +
            '--property Alpha ' +
            new_name,
        )
        self.assertOutput('', raw_output)

        cmd_output = json.loads(self.openstack(
            'volume show -f json ' +
            new_name
        ))
        self.assertEqual(
            "Beta='b'",
            cmd_output["properties"],
        )

    def wait_for(self, check_type, check_name, desired_status, wait=120,
                 interval=5, failures=['ERROR']):
        status = "notset"
        total_sleep = 0
        opts = self.get_opts(['status'])
        while total_sleep < wait:
            status = self.openstack(check_type + ' show ' + check_name + opts)
            status = status.rstrip()
            print('Checking {} {} Waiting for {} current status: {}'
                  .format(check_type, check_name, desired_status, status))
            if status == desired_status:
                break
            self.assertNotIn(status, failures)
            time.sleep(interval)
            total_sleep += interval
        self.assertEqual(desired_status, status)
<|endoftext|>


<commit_before># encoding=UTF-8

# Copyright © 2011-2017 Jakub Wilk <jwilk@jwilk.net>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the “Software”), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

'''
pydiatra CLI
'''

from __future__ import print_function

import argparse
import io
import multiprocessing
import os
import sys

try:
    import concurrent.futures
except ImportError as concurrent_exc:
    concurrent = False
else:
    concurrent_exc = None  # hi, pyflakes!

from . import __version__
from . import checks

def check_file(path, file=sys.stdout):
    for t in checks.check_file(path):
        print(t, file=file)

def check_file_s(path):
    if str is bytes:
        file = io.BytesIO()
    else:
        file = io.StringIO()
    check_file(path, file=file)
    return file.getvalue()

def parse_jobs(s):
    if s == 'auto':
        try:
            return multiprocessing.cpu_count()
        except NotImplementedError:
            return 1
    n = int(s)
    if n <= 0:
        raise ValueError
    return n
parse_jobs.__name__ = 'jobs'

def maybe_reexec(argv0=None):
    if sys.version_info >= (3,):
        return
    required_flags = dict(
        tabcheck=2,
        py3k_warning=1,
    )
    # https://docs.python.org/2/library/sys.html#sys.flags
    flag_to_option = dict(
        debug='d',
        py3k_warning='3',
        division_warning='Qwarn',
        division_new='Qnew',
        inspect='i',
        optimize='O',
        dont_write_bytecode='B',
        no_user_site='s',
        no_site='S',
        ignore_environment='E',
        tabcheck='t',
        verbose='v',
        unicode='U',
        bytes_warning='b',
        hash_randomization='R'
    )
    assert set(required_flags.keys()).issubset(flag_to_option.keys())
    argv = [sys.executable]
    reexec_needed = False
    for flag, option in flag_to_option.items():
        n = getattr(sys.flags, flag, 0)
        m = required_flags.get(flag, 0)
        if m > n:
            n = m
            reexec_needed = True
        if n > 0:
            if len(option) == 1:
                argv += ['-' + option * n]
            else:
                argv += ['-' + option] * n
    argv += argv0
    argv += sys.argv[1:]
    if reexec_needed:
        os.execv(argv[0], argv)

def main(runpy=False, script=None):
    if runpy:
        mod_head, _, mod_tail = __name__.partition('.')
        assert mod_tail == 'main'
        maybe_reexec(argv0=['-m', mod_head])
    elif script is not None:
        maybe_reexec(argv0=[script])
    ap = argparse.ArgumentParser()
    ap.add_argument('paths', metavar='<file>', nargs='+')
    ap.add_argument('--version', action='version', version='%(prog)s {0}'.format(__version__))
    ap.add_argument('-j', '--jobs', metavar='<n>', type=parse_jobs, default=1,
        help=('use <n> processes' if concurrent else argparse.SUPPRESS)
    )
    options = ap.parse_args()
    if len(options.paths) <= 1:
        options.jobs = 1
    if options.jobs > 1 and not concurrent:
        print('{prog}: warning: cannot import concurrent.futures: {msg}'.format(prog=ap.prog, msg=concurrent_exc), file=sys.stderr)
        options.jobs = 1
    checks.load_data()
    if options.jobs <= 1:
        for path in options.paths:
            check_file(path)
    else:
        executor = concurrent.futures.ProcessPoolExecutor(max_workers=options.jobs)
        with executor:
            for s in executor.map(check_file_s, options.paths):
                sys.stdout.write(s)
    sys.exit(0)

__all__ = ['main']

# vim:ts=4 sts=4 sw=4 et
<commit_msg>Make bad usage exit status 1.<commit_after># encoding=UTF-8

# Copyright © 2011-2017 Jakub Wilk <jwilk@jwilk.net>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the “Software”), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

'''
pydiatra CLI
'''

from __future__ import print_function

import argparse
import io
import multiprocessing
import os
import sys

try:
    import concurrent.futures
except ImportError as concurrent_exc:
    concurrent = False
else:
    concurrent_exc = None  # hi, pyflakes!

from . import __version__
from . import checks

def check_file(path, file=sys.stdout):
    for t in checks.check_file(path):
        print(t, file=file)

def check_file_s(path):
    if str is bytes:
        file = io.BytesIO()
    else:
        file = io.StringIO()
    check_file(path, file=file)
    return file.getvalue()

def parse_jobs(s):
    if s == 'auto':
        try:
            return multiprocessing.cpu_count()
        except NotImplementedError:
            return 1
    n = int(s)
    if n <= 0:
        raise ValueError
    return n
parse_jobs.__name__ = 'jobs'

def maybe_reexec(argv0=None):
    if sys.version_info >= (3,):
        return
    required_flags = dict(
        tabcheck=2,
        py3k_warning=1,
    )
    # https://docs.python.org/2/library/sys.html#sys.flags
    flag_to_option = dict(
        debug='d',
        py3k_warning='3',
        division_warning='Qwarn',
        division_new='Qnew',
        inspect='i',
        optimize='O',
        dont_write_bytecode='B',
        no_user_site='s',
        no_site='S',
        ignore_environment='E',
        tabcheck='t',
        verbose='v',
        unicode='U',
        bytes_warning='b',
        hash_randomization='R'
    )
    assert set(required_flags.keys()).issubset(flag_to_option.keys())
    argv = [sys.executable]
    reexec_needed = False
    for flag, option in flag_to_option.items():
        n = getattr(sys.flags, flag, 0)
        m = required_flags.get(flag, 0)
        if m > n:
            n = m
            reexec_needed = True
        if n > 0:
            if len(option) == 1:
                argv += ['-' + option * n]
            else:
                argv += ['-' + option] * n
    argv += argv0
    argv += sys.argv[1:]
    if reexec_needed:
        os.execv(argv[0], argv)

class ArgumentParser(argparse.ArgumentParser):

    def exit(self, status=0, message=None):
        if status:
            status = 1
        argparse.ArgumentParser.exit(self, status=status, message=message)

def main(runpy=False, script=None):
    if runpy:
        mod_head, _, mod_tail = __name__.partition('.')
        assert mod_tail == 'main'
        maybe_reexec(argv0=['-m', mod_head])
    elif script is not None:
        maybe_reexec(argv0=[script])
    ap = ArgumentParser()
    ap.add_argument('paths', metavar='<file>', nargs='+')
    ap.add_argument('--version', action='version', version='%(prog)s {0}'.format(__version__))
    ap.add_argument('-j', '--jobs', metavar='<n>', type=parse_jobs, default=1,
        help=('use <n> processes' if concurrent else argparse.SUPPRESS)
    )
    options = ap.parse_args()
    if len(options.paths) <= 1:
        options.jobs = 1
    if options.jobs > 1 and not concurrent:
        print('{prog}: warning: cannot import concurrent.futures: {msg}'.format(prog=ap.prog, msg=concurrent_exc), file=sys.stderr)
        options.jobs = 1
    checks.load_data()
    if options.jobs <= 1:
        for path in options.paths:
            check_file(path)
    else:
        executor = concurrent.futures.ProcessPoolExecutor(max_workers=options.jobs)
        with executor:
            for s in executor.map(check_file_s, options.paths):
                sys.stdout.write(s)
    sys.exit(0)

__all__ = ['main']

# vim:ts=4 sts=4 sw=4 et
<|endoftext|>


<commit_before>from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.views.generic.base import TemplateView

admin.autodiscover()

urlpatterns = patterns('',
    # homepage
    url(r'^$', TemplateView.as_view(template_name="python/index.html"), name='home'),

    # python section landing pages
    url(r'^about/$', TemplateView.as_view(template_name="python/about.html"), name='about'),
    url(r'^download/$', TemplateView.as_view(template_name="python/download.html"), name='download'),
    url(r'^documentation/$', TemplateView.as_view(template_name="python/documentation.html"), name='documentation'),
    #url(r'^community/$', TemplateView.as_view(template_name="python/community.html"), name='community'),
    url(r'^blog/$', TemplateView.as_view(template_name="python/blog.html"), name='blog'),
    url(r'^inner/$', TemplateView.as_view(template_name="python/inner.html"), name='inner'),

    # other section landing pages
    url(r'^psf-landing/$', TemplateView.as_view(template_name="psf/index.html"), name='psf-landing'),
    url(r'^docs-landing/$', TemplateView.as_view(template_name="docs/index.html"), name='docs-landing'),
    url(r'^pypl-landing/$', TemplateView.as_view(template_name="pypl/index.html"), name='pypl-landing'),
    url(r'^shop-landing/$', TemplateView.as_view(template_name="shop/index.html"), name='shop-landing'),

    url(r'^accounts/', include('allauth.urls')),
    url(r'^box/', include('boxes.urls')),
    url(r'^comments/', include('django_comments_xtd.urls')),
    url(r'^community/', include('community.urls', namespace='community')),
    url(r'^events/', include('events.urls', namespace='events')),
    url(r'^feedbacks/', include('feedbacks.urls')),
    url(r'^jobs/', include('jobs.urls', namespace='jobs')),
    url(r'^sponsors/', include('sponsors.urls')),
    url(r'^success-stories/', include('successstories.urls')),
    url(r'^users/', include('users.urls', namespace='users')),

    url(r'^psf/board/records/minutes/', include('minutes.urls')),
    url(r'^peps/', include('peps.urls')),

    # admin
    url(r'^admin/', include(admin.site.urls)),

    # it's a secret to everyone
    url(r'^__secret/devfixture/$', 'pydotorg.views.get_dev_fixture', name='pydotorg-devfixture'),

    # Fall back on CMS'd pages as the last resort.
    url(r'', include('pages.urls')),
)

urlpatterns += staticfiles_urlpatterns()
<commit_msg>URL typo<commit_after>from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.views.generic.base import TemplateView

admin.autodiscover()

urlpatterns = patterns('',
    # homepage
    url(r'^$', TemplateView.as_view(template_name="python/index.html"), name='home'),

    # python section landing pages
    url(r'^about/$', TemplateView.as_view(template_name="python/about.html"), name='about'),
    url(r'^download/$', TemplateView.as_view(template_name="python/download.html"), name='download'),
    url(r'^documentation/$', TemplateView.as_view(template_name="python/documentation.html"), name='documentation'),
    #url(r'^community/$', TemplateView.as_view(template_name="python/community.html"), name='community'),
    url(r'^blog/$', TemplateView.as_view(template_name="python/blog.html"), name='blog'),
    url(r'^inner/$', TemplateView.as_view(template_name="python/inner.html"), name='inner'),

    # other section landing pages
    url(r'^psf-landing/$', TemplateView.as_view(template_name="psf/index.html"), name='psf-landing'),
    url(r'^docs-landing/$', TemplateView.as_view(template_name="docs/index.html"), name='docs-landing'),
    url(r'^pypl-landing/$', TemplateView.as_view(template_name="pypl/index.html"), name='pypl-landing'),
    url(r'^shop-landing/$', TemplateView.as_view(template_name="shop/index.html"), name='shop-landing'),

    url(r'^accounts/', include('allauth.urls')),
    url(r'^box/', include('boxes.urls')),
    url(r'^comments/', include('django_comments_xtd.urls')),
    url(r'^community/', include('community.urls', namespace='community')),
    url(r'^events/', include('events.urls', namespace='events')),
    url(r'^feedbacks/', include('feedbacks.urls')),
    url(r'^jobs/', include('jobs.urls', namespace='jobs')),
    url(r'^sponsors/', include('sponsors.urls')),
    url(r'^success-stories/', include('successstories.urls')),
    url(r'^users/', include('users.urls', namespace='users')),

    url(r'^psf/records/board/minutes/', include('minutes.urls')),
    url(r'^peps/', include('peps.urls')),

    # admin
    url(r'^admin/', include(admin.site.urls)),

    # it's a secret to everyone
    url(r'^__secret/devfixture/$', 'pydotorg.views.get_dev_fixture', name='pydotorg-devfixture'),

    # Fall back on CMS'd pages as the last resort.
    url(r'', include('pages.urls')),
)

urlpatterns += staticfiles_urlpatterns()
<|endoftext|>