<commit_before>from __future__ import absolute_import, division, print_function

import operator
from toolz import first
import numpy as np
from datashape import dshape, var, DataShape
from dateutil.parser import parse as dt_parse
from datashape.predicates import isscalar, isboolean, isnumeric
from datashape import coretypes as ct, discover, unsigned, promote, optionify

from .core import parenthesize, eval_str
from .expressions import Expr, shape, ElemWise
from ..dispatch import dispatch
from ..compatibility import _strtypes

__all__ = '''
BinOp
UnaryOp
Arithmetic
Add
Mult
Sub
Div
FloorDiv
Pow
Mod
USub
Relational
Eq
Ne
Ge
Lt
Le
Gt
Gt
And
Or
Not
'''.split()

def name(o):
    if hasattr(o, '_name'):
        return o._name
    else:
        return None

class BinOp(ElemWise):
    __slots__ = '_hash', 'lhs', 'rhs'
    __inputs__ = 'lhs', 'rhs'

    def __init__(self, lhs, rhs):
        self.lhs = lhs
        self.rhs = rhs

    def __str__(self):
        lhs = parenthesize(eval_str(self.lhs))
        rhs = parenthesize(eval_str(self.rhs))
        return '%s %s %s' % (lhs, self.symbol, rhs)

    @property
    def _name(self):
        if not isscalar(self.dshape.measure):
            return None
        l, r = name(self.lhs), name(self.rhs)
        if l and not r:
            return l
        if r and not l:
            return r
        if l == r:
            return l

    @property
    def _inputs(self):
        result = []
        if isinstance(self.lhs, Expr):
            result.append(self.lhs)
        if isinstance(self.rhs, Expr):
            result.append(self.rhs)
        return tuple(result)

def maxvar(L):
    """

    >>> maxvar([1, 2, var])
    Var()

    >>> maxvar([1, 2, 3])
    3
    """
    if var in L:
        return var
    else:
        return max(L)

def maxshape(shapes):
    """

    >>> maxshape([(10, 1), (1, 10), ()])
    (10, 10)

    >>> maxshape([(4, 5), (5,)])
    (4, 5)
    """
    shapes = [shape for shape in shapes if shape]
    if not shapes:
        return ()
    ndim = max(map(len, shapes))
    shapes = [(1,) * (ndim - len(shape)) + shape for shape in shapes]
    for dims in zip(*shapes):
        if len(set(dims) - set([1])) >= 2:
            raise ValueError("Shapes don't align, %s" % str(dims))
    return tuple(map(maxvar, zip(*shapes)))

class UnaryOp(ElemWise):
    __slots__ = '_hash', '_child',

    def __init__(self, child):
        self._child = child

    def __str__(self):
        return '%s(%s)' % (self.symbol, eval_str(self._child))

    @property
    def symbol(self):
        return type(self).__name__

    @property
    def dshape(self):
        return DataShape(*(shape(self._child) + (self._dtype,)))

    @property
    def _name(self):
        return self._child._name

class Arithmetic(BinOp):
    """ Super class for arithmetic operators like add or mul """

    @property
    def _dtype(self):
        # we can't simply use .schema or .datashape because we may have a bare
        # integer, for example
        lhs, rhs = discover(self.lhs).measure, discover(self.rhs).measure
        return promote(lhs, rhs)

    @property
    def dshape(self):
        # TODO: better inference.  e.g. int + int -> int
        return DataShape(*(maxshape([shape(self.lhs), shape(self.rhs)]) +
                           (self._dtype,)))

class Add(Arithmetic):
    symbol = '+'
    op = operator.add

class Mult(Arithmetic):
    symbol = '*'
    op = operator.mul

class Sub(Arithmetic):
    symbol = '-'
    op = operator.sub

class Div(Arithmetic):
    symbol = '/'
    op = operator.truediv

    @property
    def _dtype(self):
        lhs, rhs = discover(self.lhs).measure, discover(self.rhs).measure
        return optionify(lhs, rhs, ct.float64)

class FloorDiv(Arithmetic):
    symbol = '//'
    op = operator.floordiv

    @property
    def _dtype(self):
        lhs, rhs = discover(self.lhs).measure, discover(self.rhs).measure
        is_unsigned = lhs in unsigned and rhs in unsigned
        max_width = max(lhs.itemsize, rhs.itemsize)
        prefix = 'u' if is_unsigned else ''
        measure = getattr(ct, '%sint%d' % (prefix, max_width * 8))
        return optionify(lhs, rhs, measure)

class Pow(Arithmetic):
    symbol = '**'
    op = operator.pow

class Mod(Arithmetic):
    symbol = '%'
    op = operator.mod

class USub(UnaryOp):
    op = operator.neg
    symbol = '-'

    def __str__(self):
        return '-%s' % parenthesize(eval_str(self._child))

    @property
    def _dtype(self):
        # TODO: better inference.  -uint -> int
        return self._child.schema

@dispatch(ct.Option, object)
def scalar_coerce(ds, val):
    if val or val == 0:
        return scalar_coerce(ds.ty, val)
    else:
        return None

@dispatch((ct.Record, ct.Mono, ct.Option, DataShape), Expr)
def scalar_coerce(ds, val):
    return val

@dispatch(ct.Date, _strtypes)
def scalar_coerce(_, val):
    dt = dt_parse(val)
    if dt.time():
        raise ValueError("Can not coerce %s to type Date, "
                "contains time information")
    return dt.date()

@dispatch(ct.DateTime, _strtypes)
def scalar_coerce(_, val):
    return dt_parse(val)

@dispatch(ct.CType, _strtypes)
def scalar_coerce(dt, val):
    return np.asscalar(np.asarray(val, dtype=dt.to_numpy_dtype()))

@dispatch(ct.Record, object)
def scalar_coerce(rec, val):
    if len(rec.fields) == 1:
        return scalar_coerce(first(rec.types), val)
    else:
        raise TypeError("Trying to coerce complex datashape\n"
                "got dshape: %s\n"
                "scalar_coerce only intended for scalar values" % rec)

@dispatch(ct.DataShape, object)
def scalar_coerce(ds, val):
    return scalar_coerce(ds.measure, val)

@dispatch(object, object)
def scalar_coerce(dtype, val):
    return val

@dispatch(_strtypes, object)
def scalar_coerce(ds, val):
    return scalar_coerce(dshape(ds), val)

def _neg(self):
    return USub(self)

def _add(self, other):
    result = Add(self, scalar_coerce(self.dshape, other))
    result.dshape # Check that shapes and dtypes match up
    return result

def _radd(self, other):
    result = Add(scalar_coerce(self.dshape, other), self)
    result.dshape # Check that shapes and dtypes match up
    return result

def _mul(self, other):
    result = Mult(self, scalar_coerce(self.dshape, other))
    result.dshape # Check that shapes and dtypes match up
    return result

def _rmul(self, other):
    result = Mult(scalar_coerce(self.dshape, other), self)
    result.dshape # Check that shapes and dtypes match up
    return result

def _div(self, other):
    result = Div(self, scalar_coerce(self.dshape, other))
    result.dshape # Check that shapes and dtypes match up
    return result

def _rdiv(self, other):
    result = Div(scalar_coerce(self.dshape, other), self)
    result.dshape # Check that shapes and dtypes match up
    return result

def _floordiv(self, other):
    result = FloorDiv(self, scalar_coerce(self.dshape, other))
    result.dshape # Check that shapes and dtypes match up
    return result

def _rfloordiv(self, other):
    result = FloorDiv(scalar_coerce(self.dshape, other), self)
    result.dshape # Check that shapes and dtypes match up
    return result

def _sub(self, other):
    result = Sub(self, scalar_coerce(self.dshape, other))
    result.dshape # Check that shapes and dtypes match up
    return result

def _rsub(self, other):
    result = Sub(scalar_coerce(self.dshape, other), self)
    result.dshape # Check that shapes and dtypes match up
    return result

def _pow(self, other):
    result = Pow(self, scalar_coerce(self.dshape, other))
    result.dshape # Check that shapes and dtypes match up
    return result

def _rpow(self, other):
    result = Pow(scalar_coerce(self.dshape, other), self)
    result.dshape # Check that shapes and dtypes match up
    return result

def _mod(self, other):
    result = Mod(self, scalar_coerce(self.dshape, other))
    result.dshape # Check that shapes and dtypes match up
    return result

def _rmod(self, other):
    result = Mod(scalar_coerce(self.dshape, other), self)
    result.dshape # Check that shapes and dtypes match up
    return result

class Relational(Arithmetic):
    _dtype = ct.bool_

class Eq(Relational):
    symbol = '=='
    op = operator.eq

class Ne(Relational):
    symbol = '!='
    op = operator.ne

class Ge(Relational):
    symbol = '>='
    op = operator.ge

class Le(Relational):
    symbol = '<='
    op = operator.le

class Gt(Relational):
    symbol = '>'
    op = operator.gt

class Lt(Relational):
    symbol = '<'
    op = operator.lt

class And(Arithmetic):
    symbol = '&'
    op = operator.and_
    _dtype = ct.bool_

class Or(Arithmetic):
    symbol = '|'
    op = operator.or_
    _dtype = ct.bool_

class Not(UnaryOp):
    symbol = '~'
    op = operator.invert
    _dtype = ct.bool_
    def __str__(self):
        return '~%s' % parenthesize(eval_str(self._child))

def _eq(self, other):
    result = Eq(self, scalar_coerce(self.dshape, other))
    result.dshape # Check that shapes and dtypes match up
    return result

def _ne(self, other):
    result = Ne(self, scalar_coerce(self.dshape, other))
    result.dshape # Check that shapes and dtypes match up
    return result

def _lt(self, other):
    result = Lt(self, scalar_coerce(self.dshape, other))
    result.dshape # Check that shapes and dtypes match up
    return result

def _le(self, other):
    result = Le(self, scalar_coerce(self.dshape, other))
    result.dshape # Check that shapes and dtypes match up
    return result

def _gt(self, other):
    result = Gt(self, scalar_coerce(self.dshape, other))
    result.dshape # Check that shapes and dtypes match up
    return result

def _ge(self, other):
    result = Ge(self, scalar_coerce(self.dshape, other))
    result.dshape # Check that shapes and dtypes match up
    return result

def _invert(self):
    result = Invert(self)
    result.dshape # Check that shapes and dtypes match up
    return result

def _and(self, other):
    result = And(self, other)
    result.dshape # Check that shapes and dtypes match up
    return result

def _rand(self, other):
    result = And(other, self)
    result.dshape # Check that shapes and dtypes match up
    return result

def _or(self, other):
    result = Or(self, other)
    result.dshape # Check that shapes and dtypes match up
    return result

def _ror(self, other):
    result = Or(other, self)
    result.dshape # Check that shapes and dtypes match up
    return result

def _invert(self):
    result = Not(self)
    result.dshape # Check that shapes and dtypes match up
    return result

Invert = Not
BitAnd = And
BitOr = Or

from .expressions import schema_method_list

schema_method_list.extend([
    (isnumeric,
     set([_add, _radd, _mul, _rmul, _div, _rdiv, _floordiv, _rfloordiv, _sub,
          _rsub, _pow, _rpow, _mod, _rmod,  _neg])),
    (isscalar, set([_eq, _ne, _lt, _le, _gt, _ge])),
    (isboolean, set([_or, _ror, _and, _rand, _invert])),
    (lambda t: isinstance(t, ct.String),
     set([_add, _radd, _mul, _rmul, _mod, _rmod])),
    ])
<commit_msg>MAINT: Factor the binary function creation into a factory function.<commit_after>from __future__ import absolute_import, division, print_function

import operator
from toolz import first
import numpy as np
from datashape import dshape, var, DataShape
from dateutil.parser import parse as dt_parse
from datashape.predicates import isscalar, isboolean, isnumeric
from datashape import coretypes as ct, discover, unsigned, promote, optionify

from .core import parenthesize, eval_str
from .expressions import Expr, shape, ElemWise
from ..dispatch import dispatch
from ..compatibility import _strtypes

__all__ = '''
BinOp
UnaryOp
Arithmetic
Add
Mult
Sub
Div
FloorDiv
Pow
Mod
USub
Relational
Eq
Ne
Ge
Lt
Le
Gt
Gt
And
Or
Not
'''.split()

def name(o):
    if hasattr(o, '_name'):
        return o._name
    else:
        return None

class BinOp(ElemWise):
    __slots__ = '_hash', 'lhs', 'rhs'
    __inputs__ = 'lhs', 'rhs'

    def __init__(self, lhs, rhs):
        self.lhs = lhs
        self.rhs = rhs

    def __str__(self):
        lhs = parenthesize(eval_str(self.lhs))
        rhs = parenthesize(eval_str(self.rhs))
        return '%s %s %s' % (lhs, self.symbol, rhs)

    @property
    def _name(self):
        if not isscalar(self.dshape.measure):
            return None
        l, r = name(self.lhs), name(self.rhs)
        if l and not r:
            return l
        if r and not l:
            return r
        if l == r:
            return l

    @property
    def _inputs(self):
        result = []
        if isinstance(self.lhs, Expr):
            result.append(self.lhs)
        if isinstance(self.rhs, Expr):
            result.append(self.rhs)
        return tuple(result)

def maxvar(L):
    """

    >>> maxvar([1, 2, var])
    Var()

    >>> maxvar([1, 2, 3])
    3
    """
    if var in L:
        return var
    else:
        return max(L)

def maxshape(shapes):
    """

    >>> maxshape([(10, 1), (1, 10), ()])
    (10, 10)

    >>> maxshape([(4, 5), (5,)])
    (4, 5)
    """
    shapes = [shape for shape in shapes if shape]
    if not shapes:
        return ()
    ndim = max(map(len, shapes))
    shapes = [(1,) * (ndim - len(shape)) + shape for shape in shapes]
    for dims in zip(*shapes):
        if len(set(dims) - set([1])) >= 2:
            raise ValueError("Shapes don't align, %s" % str(dims))
    return tuple(map(maxvar, zip(*shapes)))

class UnaryOp(ElemWise):
    __slots__ = '_hash', '_child',

    def __init__(self, child):
        self._child = child

    def __str__(self):
        return '%s(%s)' % (self.symbol, eval_str(self._child))

    @property
    def symbol(self):
        return type(self).__name__

    @property
    def dshape(self):
        return DataShape(*(shape(self._child) + (self._dtype,)))

    @property
    def _name(self):
        return self._child._name

class Arithmetic(BinOp):
    """ Super class for arithmetic operators like add or mul """

    @property
    def _dtype(self):
        # we can't simply use .schema or .datashape because we may have a bare
        # integer, for example
        lhs, rhs = discover(self.lhs).measure, discover(self.rhs).measure
        return promote(lhs, rhs)

    @property
    def dshape(self):
        # TODO: better inference.  e.g. int + int -> int
        return DataShape(*(maxshape([shape(self.lhs), shape(self.rhs)]) +
                           (self._dtype,)))

class Add(Arithmetic):
    symbol = '+'
    op = operator.add

class Mult(Arithmetic):
    symbol = '*'
    op = operator.mul

class Sub(Arithmetic):
    symbol = '-'
    op = operator.sub

class Div(Arithmetic):
    symbol = '/'
    op = operator.truediv

    @property
    def _dtype(self):
        lhs, rhs = discover(self.lhs).measure, discover(self.rhs).measure
        return optionify(lhs, rhs, ct.float64)

class FloorDiv(Arithmetic):
    symbol = '//'
    op = operator.floordiv

    @property
    def _dtype(self):
        lhs, rhs = discover(self.lhs).measure, discover(self.rhs).measure
        is_unsigned = lhs in unsigned and rhs in unsigned
        max_width = max(lhs.itemsize, rhs.itemsize)
        prefix = 'u' if is_unsigned else ''
        measure = getattr(ct, '%sint%d' % (prefix, max_width * 8))
        return optionify(lhs, rhs, measure)

class Pow(Arithmetic):
    symbol = '**'
    op = operator.pow

class Mod(Arithmetic):
    symbol = '%'
    op = operator.mod

class USub(UnaryOp):
    op = operator.neg
    symbol = '-'

    def __str__(self):
        return '-%s' % parenthesize(eval_str(self._child))

    @property
    def _dtype(self):
        # TODO: better inference.  -uint -> int
        return self._child.schema

@dispatch(ct.Option, object)
def scalar_coerce(ds, val):
    if val or val == 0:
        return scalar_coerce(ds.ty, val)
    else:
        return None

@dispatch((ct.Record, ct.Mono, ct.Option, DataShape), Expr)
def scalar_coerce(ds, val):
    return val

@dispatch(ct.Date, _strtypes)
def scalar_coerce(_, val):
    dt = dt_parse(val)
    if dt.time():
        raise ValueError("Can not coerce %s to type Date, "
                "contains time information")
    return dt.date()

@dispatch(ct.DateTime, _strtypes)
def scalar_coerce(_, val):
    return dt_parse(val)

@dispatch(ct.CType, _strtypes)
def scalar_coerce(dt, val):
    return np.asscalar(np.asarray(val, dtype=dt.to_numpy_dtype()))

@dispatch(ct.Record, object)
def scalar_coerce(rec, val):
    if len(rec.fields) == 1:
        return scalar_coerce(first(rec.types), val)
    else:
        raise TypeError("Trying to coerce complex datashape\n"
                "got dshape: %s\n"
                "scalar_coerce only intended for scalar values" % rec)

@dispatch(ct.DataShape, object)
def scalar_coerce(ds, val):
    return scalar_coerce(ds.measure, val)

@dispatch(object, object)
def scalar_coerce(dtype, val):
    return val

@dispatch(_strtypes, object)
def scalar_coerce(ds, val):
    return scalar_coerce(dshape(ds), val)

def _neg(self):
    return USub(self)

def _mkbin(name, cons, reflected=True):
    def _bin(self, other):
        result = cons(self, scalar_coerce(self.dshape, other))
        result.dshape  # Check that shapes and dtypes match up
        return result
    _bin.__name__ = '_' + name

    if reflected:
        def _rbin(self, other):
            result = cons(scalar_coerce(self.dshape, other), self)
            result.dshape  # Check that shapes and dtypes match up
            return result
        _rbin.__name__ = '_r' + name

        return _bin, _rbin

    return _bin

_add, _radd = _mkbin('add', Add)
_div, _rdiv = _mkbin('div', Div)
_floordiv, _rfloordiv = _mkbin('floordiv', FloorDiv)
_mod, _rmod = _mkbin('mod', Mod)
_mul, _rmul = _mkbin('mul', Mult)
_pow, _rpow = _mkbin('pow', Pow)
_sub, _rsub = _mkbin('sub', Sub)

class Relational(Arithmetic):
    _dtype = ct.bool_

class Eq(Relational):
    symbol = '=='
    op = operator.eq

class Ne(Relational):
    symbol = '!='
    op = operator.ne

class Ge(Relational):
    symbol = '>='
    op = operator.ge

class Le(Relational):
    symbol = '<='
    op = operator.le

class Gt(Relational):
    symbol = '>'
    op = operator.gt

class Lt(Relational):
    symbol = '<'
    op = operator.lt

class And(Arithmetic):
    symbol = '&'
    op = operator.and_
    _dtype = ct.bool_

class Or(Arithmetic):
    symbol = '|'
    op = operator.or_
    _dtype = ct.bool_

class Not(UnaryOp):
    symbol = '~'
    op = operator.invert
    _dtype = ct.bool_
    def __str__(self):
        return '~%s' % parenthesize(eval_str(self._child))

_and, _rand = _mkbin('and', And)
_eq = _mkbin('eq', Eq, reflected=False)
_ge = _mkbin('ge', Ge, reflected=False)
_gt = _mkbin('gt', Gt, reflected=False)
_le = _mkbin('le', Le, reflected=False)
_lt = _mkbin('lt', Lt, reflected=False)
_ne = _mkbin('ne', Ne, reflected=False)
_or, _ror = _mkbin('or', Or)

def _invert(self):
    result = Invert(self)
    result.dshape  # Check that shapes and dtypes match up
    return result

Invert = Not
BitAnd = And
BitOr = Or

from .expressions import schema_method_list

schema_method_list.extend([
    (isnumeric,
     set([_add, _radd, _mul, _rmul, _div, _rdiv, _floordiv, _rfloordiv, _sub,
          _rsub, _pow, _rpow, _mod, _rmod,  _neg])),
    (isscalar, set([_eq, _ne, _lt, _le, _gt, _ge])),
    (isboolean, set([_or, _ror, _and, _rand, _invert])),
    (lambda t: isinstance(t, ct.String),
     set([_add, _radd, _mul, _rmul, _mod, _rmod])),
    ])
<|endoftext|>


<commit_before>import pandas as pd
import sys
from pathlib import Path
from treelib import Node, Tree
from math import log2
from collections import defaultdict

usage = 'TreeMaker.py /path/to/training/dataset /path/to/validation/dataset /path/to/testing/dataset pruning_factor'

if len(sys.argv) < 5:
    print('not enough arguments\n')
    print(usage)
    sys.exit(1)
if len(sys.argv) > 5:
    print('too many arguments\n')
    print(usage)
    sys.exit(1)

training_data_path = Path(sys.argv[1])
validation_data_path = Path(sys.argv[2])
test_data_path = Path(sys.argv[3])
pruning_factor = sys.argv[4]

training_set = pd.read_csv(training_data_path)
validation_set = pd.read_csv(validation_data_path)
test_set = pd.read_csv(test_data_path)

header = list(training_set.columns.values)
print(header)

num_tuples = len(training_set[header[-1]])
num_label = {}

for val in training_set[header[-1]]:
    if val in num_label:
        num_label[val] += 1
    else:
        num_label[val] = 1

probability_label = {}
for key in num_label:
    probability_label[key] = num_label[key] / num_tuples

previous_entropy = 0
for key in probability_label:
    previous_entropy += -1 * probability_label[key] * log2(probability_label[key])
print(previous_entropy)

class NodeData:
    def __init__(self, entropy, header):
        self.entropy = entropy
        self.header = header

tree = Tree()

tree.create_node('Root', 'root', data = NodeData(previous_entropy, None))

def make_branch(set, headers, tree, parent_node):
    #base cases: out of header OR labeles are pure
    for dim in headers[0:-1]: #TODO: 0:-2?
        value_label_counts = getValueLabelCounts(set, dim)
        header_entropy = 0
        for value, label_count in value_label_counts:
            header_entropy += calcEntropy(label_count)
        pass

def calcEntropy(label_count):
    entropy = 0
    total_instances = 0
    for label, count in label_count:
        total_instances += count
    for label, count in label_count:
        entropy += -1 * count / total_instances * log2(count / total_instances)
    return entropy

def getValueLabelCounts(set, header):
    label_counts = defaultdict(defaultdict(lambda: 0))
    #get count of instances for each label
    for tuple in set.itertuples():
        label_counts[tuple[header]][getLabel(tuple)] += 1
    return label_counts

def getLabel(tuple):
    return tuple[-1]

testEntropy(training_set, 'XB')

# print(training_set)

<commit_msg>fixed bug in calcEntropy<commit_after>import pandas as pd
import sys
import pprint as pp
from pathlib import Path
from treelib import Node, Tree
from math import log2
from collections import defaultdict

usage = 'TreeMaker.py /path/to/training/dataset /path/to/validation/dataset /path/to/testing/dataset pruning_factor'

if len(sys.argv) < 5:
    print('not enough arguments\n')
    print(usage)
    sys.exit(1)
if len(sys.argv) > 5:
    print('too many arguments\n')
    print(usage)
    sys.exit(1)

training_data_path = Path(sys.argv[1])
validation_data_path = Path(sys.argv[2])
test_data_path = Path(sys.argv[3])
pruning_factor = sys.argv[4]

training_set = pd.read_csv(training_data_path)
validation_set = pd.read_csv(validation_data_path)
test_set = pd.read_csv(test_data_path)

header = list(training_set.columns.values)

num_tuples = len(training_set[header[-1]])
num_label = {}

for val in training_set[header[-1]]:
    if val in num_label:
        num_label[val] += 1
    else:
        num_label[val] = 1

probability_label = {}
for key in num_label:
    probability_label[key] = num_label[key] / num_tuples

previous_entropy = 0
for key in probability_label:
    previous_entropy += -1 * probability_label[key] * log2(probability_label[key])
print(previous_entropy)

class NodeData:
    def __init__(self, entropy, header):
        self.entropy = entropy
        self.header = header

tree = Tree()

tree.create_node('Root', 'root', data = NodeData(previous_entropy, None))

def make_branch(set, headers, tree, parent_node):
    #base cases: out of header OR labeles are pure
    for dim in headers[0:-1]: #TODO: 0:-2?
        value_label_counts = getValueLabelCounts(set, dim)
        header_entropy = 0
        for value, label_count in value_label_counts:
            header_entropy += calcEntropy(label_count) #TODO *weight_factor
        pass

def calcEntropy(label_count):
    entropy = 0
    total_instances = 0
    for label, count in label_count.items():
        total_instances += count
    for label, count in label_count.items():
        entropy += -1 * count / total_instances * log2(count / total_instances)
    return entropy

def getValueLabelCounts(set, header):
    label_counts = defaultdict(lambda: defaultdict(lambda: 0))
    #get count of instances for each label
    for tuple in set.itertuples(index=True):
        value = getattr(tuple, header)
        label = getLabel(tuple)
        label_counts[value][label] += 1
    return label_counts

def getLabel(tuple):
    return tuple[-1]

value_label_counts = getValueLabelCounts(training_set, 'XB')
print(calcEntropy(value_label_counts[0]))

# print(training_set)

<|endoftext|>


<commit_before>"""
mbed SDK
Copyright (c) 2011-2015 ARM Limited

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 re
import os
import sys
import string

from .lstools_base import MbedLsToolsBase

import logging

if sys.version_info[0] < 3:
    import _winreg as winreg
else:
    import winreg

logger = logging.getLogger("mbedls.lstools_win7")

class MbedLsToolsWin7(MbedLsToolsBase):
    """ mbed-enabled platform detection for Windows
    """
    def __init__(self, **kwargs):
        MbedLsToolsBase.__init__(self, **kwargs)
        self.os_supported.append('Windows7')

    def find_candidates(self):
        return [
            {
                'mount_point': mnt,
                'target_id_usb_id': id,
                'serial_port': self._com_port(id)
            }
            for mnt, id in self.get_mbeds()
        ]

    def _com_port(self, tid):
        """! Function checks mbed serial port in Windows registry entries
        @param tid TargetID
        @return Returns None if port is not found. In normal circumstances it should never return None
        @details This goes through a whole new loop, but this assures that even if serial port (COM)
                 is not detected, we still get the rest of info like mount point etc.
        """
        winreg.Enum = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE,
                                     r'SYSTEM\CurrentControlSet\Enum')
        usb_devs = winreg.OpenKey(winreg.Enum, 'USB')
        logger.debug("_com_port usb_devs %r",
                     list(self.iter_keys_as_str(usb_devs)))

        logger.debug('_com_port ID: %s', tid)

        # first try to find all devs keys (by tid)
        dev_keys = []
        for vid in self.iter_keys(usb_devs):
            try:
                dev_keys += [winreg.OpenKey(vid, tid)]
            except:
                pass
        logger.debug("_com_port dev_keys %r",
                     [list(self.iter_keys_as_str(k)) for k in dev_keys])

        # then try to get port directly from "Device Parameters"
        for key in dev_keys:
            try:
                param = winreg.OpenKey(key, "Device Parameters")
                port = winreg.QueryValueEx(param, 'PortName')[0]
                logger.debug('_com_port param %r port %r',
                             list(self.iter_keys_as_str(param)), port)
                return port
            except:
                pass

        # else follow symbolic dev links in registry
        for key in dev_keys:
            try:
                ports = []
                parent_id = winreg.QueryValueEx(key, 'ParentIdPrefix')[0]
                for VID in self.iter_keys(usb_devs):
                    for dev in self.iter_keys_as_str(VID):
                        if parent_id in dev:
                            ports += [self._com_port(dev)]
                logger.debug("_com_port ports %r", ports)
                for port in ports:
                    if port:
                        return port
            except:
                pass

        # If everything fails, return None
        return None

    def get_mbeds(self):
        """! Function filters devices' mount points for valid TargetID
        @return Returns [(<mbed_mount_point>, <mbed_id>), ..]
        @details TargetID should be a hex string with 10-48 chars
        """
        mbeds = []
        for mbed in self.get_mbed_devices():
            mountpoint = re.match('.*\\\\(.:)$', mbed[0]).group(1)
            # TargetID is a hex string with 10-48 chars
            m = re.search('[&#]([0-9A-Za-z]{10,48})[&#]', mbed[1])
            if not m:
                continue
            tid = m.group(1)
            mbeds += [(mountpoint, tid)]
            logger.debug("get_mbeds mount_point %s usb_id %s", mountpoint, tid)
        return mbeds

    # =============================== Registry ====================================

    def iter_keys_as_str(self, key):
        """! Iterate over subkeys of a key returning subkey as string
        """
        for i in range(winreg.QueryInfoKey(key)[0]):
            yield winreg.EnumKey(key, i)

    def iter_keys(self, key):
        """! Iterate over subkeys of a key
        """
        for i in range(winreg.QueryInfoKey(key)[0]):
            yield winreg.OpenKey(key, winreg.EnumKey(key, i))

    def iter_vals(self, key):
        """! Iterate over values of a key
        """
        logger.debug("iter_vals %r", key)
        for i in range(winreg.QueryInfoKey(key)[1]):
            yield winreg.EnumValue(key, i)

    def get_mbed_devices(self):
        """! Get MBED devices (connected or not)
        @return List of devices
        @details Note: We will detect also non-standard MBED devices mentioned on 'usb_vendor_list' list.
                 This will help to detect boards like EFM boards.
        """
        upper_ven = [ven.upper() for ven in self.usb_vendor_list]
        mounts_key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, 'SYSTEM\MountedDevices')
        for point, label in self.iter_vals(mounts_key):
            if ('DosDevices' in point and
                any(v in label.upper() for v in upper_ven)):
                printable_label = self.regbin2str(label)
                logger.debug("Found Mount point %s with usb ID %s",point,
                             printable_label)
                yield (point, printable_label)

    @staticmethod
    def regbin2str(regbin):
        """! Decode registry binary to readable string
        """
        return ''.join(filter(lambda ch: ch in string.printable,
                              regbin.decode('ascii', errors='ignore')))
<commit_msg>Dump more things in win7<commit_after>"""
mbed SDK
Copyright (c) 2011-2015 ARM Limited

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 re
import os
import sys
import string

from .lstools_base import MbedLsToolsBase

import logging

if sys.version_info[0] < 3:
    import _winreg as winreg
else:
    import winreg

logger = logging.getLogger("mbedls.lstools_win7")

class MbedLsToolsWin7(MbedLsToolsBase):
    """ mbed-enabled platform detection for Windows
    """
    def __init__(self, **kwargs):
        MbedLsToolsBase.__init__(self, **kwargs)
        self.os_supported.append('Windows7')

    def find_candidates(self):
        return [
            {
                'mount_point': mnt,
                'target_id_usb_id': id,
                'serial_port': self._com_port(id)
            }
            for mnt, id in self.get_mbeds()
        ]

    def _com_port(self, tid):
        """! Function checks mbed serial port in Windows registry entries
        @param tid TargetID
        @return Returns None if port is not found. In normal circumstances it should never return None
        @details This goes through a whole new loop, but this assures that even if serial port (COM)
                 is not detected, we still get the rest of info like mount point etc.
        """
        winreg.Enum = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE,
                                     r'SYSTEM\CurrentControlSet\Enum')
        usb_devs = winreg.OpenKey(winreg.Enum, 'USB')
        logger.debug("_com_port usb_devs %r",
                     list(self.iter_keys_as_str(usb_devs)))

        logger.debug('_com_port ID: %s', tid)

        # first try to find all devs keys (by tid)
        dev_keys = []
        for vid in self.iter_keys(usb_devs):
            try:
                dev_keys += [winreg.OpenKey(vid, tid)]
            except Exception as e:
                logger.debug("Exception %r %s", vid, str(e))
                pass
        logger.debug("_com_port dev_keys %r",
                     [list(self.iter_keys_as_str(k)) for k in dev_keys])

        logger.debug("_com_port Detecting port with Device Parameter")
        for key in dev_keys:
            try:
                param = winreg.OpenKey(key, "Device Parameters")
                logger.debug('_com_port param %r',
                             list(self.iter_keys_as_str(param)))
                port, regtype = winreg.QueryValueEx(param, 'PortName')
                logger.debug('_com_port port %r regtype %r', port, regtype)
                return port
            except Exception as e:
                logger.debug("Exception %r %s", key, str(e))
                pass

        logger.debug("_com_port Detecting port By following symlinks")
        for key in dev_keys:
            try:
                ports = []
                parent_id, regtype = winreg.QueryValueEx(key, 'ParentIdPrefix')
                logger.debug("_com_port parent_id %r regtype %r")
                for VID in self.iter_keys(usb_devs):
                    candidate_keys = [k for k in self.iter_keys_as_str(VID)
                                      if parent_id in k]
                    for dev in candidate_keys:
                        logger.debug(
                            "_com_port recursive port detection with %r", dev)
                        maybe_port = self._com_port(dev)
                        if maybe_port:
                            return maybe_port
            except Exception as e:
                logger.debug("Exception %r %s", key, str(e))
                pass

        # If everything fails, return None
        return None

    def get_mbeds(self):
        """! Function filters devices' mount points for valid TargetID
        @return Returns [(<mbed_mount_point>, <mbed_id>), ..]
        @details TargetID should be a hex string with 10-48 chars
        """
        mbeds = []
        for mbed in self.get_mbed_devices():
            mountpoint = re.match('.*\\\\(.:)$', mbed[0]).group(1)
            # TargetID is a hex string with 10-48 chars
            m = re.search('[&#]([0-9A-Za-z]{10,48})[&#]', mbed[1])
            if not m:
                continue
            tid = m.group(1)
            mbeds += [(mountpoint, tid)]
            logger.debug("get_mbeds mount_point %s usb_id %s", mountpoint, tid)
        return mbeds

    # =============================== Registry ====================================

    def iter_keys_as_str(self, key):
        """! Iterate over subkeys of a key returning subkey as string
        """
        for i in range(winreg.QueryInfoKey(key)[0]):
            yield winreg.EnumKey(key, i)

    def iter_keys(self, key):
        """! Iterate over subkeys of a key
        """
        for i in range(winreg.QueryInfoKey(key)[0]):
            yield winreg.OpenKey(key, winreg.EnumKey(key, i))

    def iter_vals(self, key):
        """! Iterate over values of a key
        """
        logger.debug("iter_vals %r", key)
        for i in range(winreg.QueryInfoKey(key)[1]):
            yield winreg.EnumValue(key, i)

    def get_mbed_devices(self):
        """! Get MBED devices (connected or not)
        @return List of devices
        @details Note: We will detect also non-standard MBED devices mentioned on 'usb_vendor_list' list.
                 This will help to detect boards like EFM boards.
        """
        upper_ven = [ven.upper() for ven in self.usb_vendor_list]
        mounts_key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, 'SYSTEM\MountedDevices')
        for point, label in self.iter_vals(mounts_key):
            if ('DosDevices' in point and
                any(v in label.upper() for v in upper_ven)):
                printable_label = self.regbin2str(label)
                logger.debug("Found Mount point %s with usb ID %s",point,
                             printable_label)
                yield (point, printable_label)

    @staticmethod
    def regbin2str(regbin):
        """! Decode registry binary to readable string
        """
        return ''.join(filter(lambda ch: ch in string.printable,
                              regbin.decode('ascii', errors='ignore')))
<|endoftext|>


<commit_before>"""
picture.py
Author: <your name here>
Credit: <list sources used, if any>

Assignment:

Use the ggame library to "paint" a graphical picture of something (e.g. a house, a face or landscape).

Use at least:
1. Three different Color objects.
2. Ten different Sprite objects.
3. One (or more) RectangleAsset objects.
4. One (or more) CircleAsset objects.
5. One (or more) EllipseAsset objects.
6. One (or more) PolygonAsset objects.

See:
https://github.com/HHS-IntroProgramming/Standards-and-Syllabus/wiki/Displaying-Graphics
for general information on how to use ggame.

See:
http://brythonserver.github.io/ggame/
for detailed information on ggame.

"""
from ggame import App, Color, LineStyle, Sprite, RectangleAsset, CircleAsset, EllipseAsset, PolygonAsset

# add your code here \/  \/  \/

# add your code here /\  /\  /\

myapp = App()
myapp.run()
<commit_msg>Updated from Brython Server: 1/22/2016 2:41:37 PM<commit_after>"""
picture.py
Author: Avery Wallis
Credit: <list sources used, if any>

Assignment:

Use the ggame library to "paint" a graphical picture of something (e.g. a house, a face or landscape).

Use at least:
1. Three different Color objects.
2. Ten different Sprite objects.
3. One (or more) RectangleAsset objects.
4. One (or more) CircleAsset objects.
5. One (or more) EllipseAsset objects.
6. One (or more) PolygonAsset objects.

See:
https://github.com/HHS-IntroProgramming/Standards-and-Syllabus/wiki/Displaying-Graphics
for general information on how to use ggame.

See:
http://brythonserver.github.io/ggame/
for detailed information on ggame.

"""
from ggame import App, Color, LineStyle, Sprite, RectangleAsset, CircleAsset, EllipseAsset, PolygonAsset

# add your code here \/  \/  \/

# add your code here /\  /\  /\

myapp = App()
myapp.run()
<|endoftext|>


<commit_before>import pygame
from pygame.locals import *

from config import WIDTH, HEIGHT, FPS
from repository.image_loader import ImageLoader

class Bird(pygame.sprite.Sprite):
    state = ""
    sprite_index = 0

    GRAVITY_ACC = 1

    y_vel = -6
    max_y_vel = 10
    jump_acc = -10

    jumping = False

    sprite_rate_index = 0

    def __init__(self, base_y, name=None):
        pygame.sprite.Sprite.__init__(self)

        self.base_y = base_y

        mid_flap = ImageLoader().get_image("redbird-midflap.png")
        up_flap = ImageLoader().get_image("redbird-upflap.png")
        down_flap = ImageLoader().get_image("redbird-downflap.png")

        self.clock = pygame.time.Clock()

        self.flap_sprites = [mid_flap, down_flap, mid_flap, up_flap]

        self.image = mid_flap

        self.rect = self.image.get_rect()
        self.x = WIDTH / 2 - self.image.get_width()
        self.y = HEIGHT / 2 - self.image.get_height()
        self.name = name

    def change_flap_sprite(self):
        self.sprite_rate_index += 1
        if self.sprite_rate_index % 5 == 0:
            self.sprite_index += 1
            self.image = self.flap_sprites[self.sprite_index % len(self.flap_sprites)]

    def refresh(self):
        self.change_flap_sprite()
        time = self.clock.tick(FPS)

        if self.y_vel < self.max_y_vel and not self.jumping:
            self.y_vel += self.GRAVITY_ACC
        if self.jumping:
            self.jumping = False
        self.y += min(self.y_vel, self.base_y - self.y - self.image.get_height())

    def down(self):
        pass

    def jump(self):
        self.jumping = True
        self.y_vel = self.jump_acc
<commit_msg>Implemented floor colision<commit_after>import pygame
from pygame.locals import *

from config import WIDTH, HEIGHT, FPS
from repository.image_loader import ImageLoader

class Bird(pygame.sprite.Sprite):
    state = ""
    sprite_index = 0

    GRAVITY_ACC = 1

    y_vel = -6
    max_y_vel = 10
    jump_acc = -10

    jumping = False
    dead = False
    sprite_rate_index = 0

    def __init__(self, base_y, name=None):
        pygame.sprite.Sprite.__init__(self)

        self.base_y = base_y

        mid_flap = ImageLoader().get_image("redbird-midflap.png")
        up_flap = ImageLoader().get_image("redbird-upflap.png")
        down_flap = ImageLoader().get_image("redbird-downflap.png")

        self.clock = pygame.time.Clock()

        self.flap_sprites = [mid_flap, down_flap, mid_flap, up_flap]

        self.image = mid_flap

        self.rect = self.image.get_rect()
        self.x = WIDTH / 2 - self.image.get_width()
        self.y = HEIGHT / 2 - self.image.get_height()
        self.name = name

    def change_flap_sprite(self):
        self.sprite_rate_index += 1
        if self.sprite_rate_index % 5 == 0:
            self.sprite_index += 1
            self.image = self.flap_sprites[self.sprite_index % len(self.flap_sprites)]

    def refresh(self):
        self.change_flap_sprite()

        if self.y_vel < self.max_y_vel and not self.jumping:
            self.y_vel += self.GRAVITY_ACC
        if self.jumping:
            self.jumping = False

        self.y += min(self.y_vel, self.base_y - self.y - self.image.get_height())
        if self.y >= self.base_y - self.image.get_height():
            self.dead = True

    def down(self):
        pass

    def jump(self):
        self.jumping = True
        self.y_vel = self.jump_acc
<|endoftext|>


<commit_before># have it add to a second list instead of making a duplicate of the first list (possibly faster)
# have it skip over staff
# fix for loop in the removing dashes and spaces
# have it add to a second file instead of making a duplicate of the first
# create default settings for the data file columns instead of using numbers
# create an 'error file', have different sections fail 'gracefully'
# format output file to include the date to make it more obvious, also so it doesnt overwrite previous data
# split up some sections into seperate functions
# new task to find duplicates in a file
# perhaps an 'opening' section or help section

import re

#default coloumn locations
google_user_name = 0; google_first_name = 1; google_last_name = 2
sis_first_name = 0; sis_last_name = 1; sis_ID = 2; sis_grade = 3

#ask for source and destination csv's
ahandle = raw_input('Enter source A file (press enter for google_test_data.csv):')
bhandle = raw_input('Enter source B file (press enter for ic_test_data.csv):')

try:
	if len(ahandle) < 1 : ahandle = 'google_test_data.csv'
	afile = open(ahandle).read().split('\n')
	if len(bhandle) < 1 : bhandle = 'ic_test_data.csv'
	bfile = open(bhandle).read().split('\n')
except:
	print 'one of those files was no good'
	exit()

#load both csv's into lists
google_accounts = [each for each in [line.split(',') for line in afile] if len(each) > 3]  #google coloumns are:  email, First Name, Last Name
ic_accounts = [each for each in [line.split(',') for line in bfile] if len(each) > 3]  #IC columns:   first name, lastname, ID#, grade

print 'sis accounts'
print ic_accounts
#remove header rows
google_accounts.pop(0)
ic_accounts.pop(0)

#to make the matching possibly quicker
google_accounts.sort()
ic_accounts.sort()

#remove staff to make matching more accurate
temp_list = []
for each in google_accounts:
	at_pos = each[google_user_name].find('@')
	user_name = each[google_user_name][0:at_pos]
	if re.search('[0-9]' , user_name) : temp_list.append(each)
google_accounts = temp_list

#remove dashes from both lists since IC doesnt include them consistently
temp_list = list()
for line in google_accounts:
	l = [each.replace('-', '') for each in line ]
	temp_list.append(l)
	# line[2] = line[2].replace('-', '')
	# line[2] = line[2].replace(' ', '')
google_accounts = temp_list
for each in ic_accounts:
	each[sis_last_name] = each[sis_last_name].replace('-', '')
	each[sis_last_name] = each[sis_last_name].replace(' ', '')

#remove double quotes from google
for line in google_accounts:
	line[google_user_name] = line[google_user_name].replace('"', '')
	line[google_first_name] = line[google_first_name].replace('"', '')
	line[google_last_name] = line[google_last_name].replace('"', '')

#to prevent the for loop getting screwy when removing items
unique_google = list()
unique_sis = list()

print 'Before comparison {lista} had {alength} students, {listb} had {blength} students'.format(lista = ahandle[:-4], listb = bhandle[:-4], alength=len(google_accounts), blength =len(ic_accounts))

# check google for unique accounts
for each_google in google_accounts:
	match = False
	for each_ic in ic_accounts:
		if each_google[google_first_name] == each_ic[sis_first_name] and each_google[google_last_name] == each_ic[sis_last_name]:
			match = True
			break
	if match == False : unique_google.append(each_google)

# check sis for unique accounts
for each_ic in ic_accounts:
	match = False
	for each_google in google_accounts:
		if each_google[google_first_name] == each_ic[sis_first_name] and each_google[google_last_name] == each_ic[sis_last_name]:
			match = True
			break
	if match == False : unique_sis.append(each_ic)

print '\n{lista} had {alength} unique students, {listb} had {blength} unique students'.format(lista = ahandle[:-4], listb = bhandle[:-4], alength=len(unique_google), blength =len(unique_sis))
print '\n'

#open a new file to write unique accounts on both sides to
file_out = open('unique_accounts.txt', 'w')
line = "-----------------------\nUnique to {0}\n".format(ahandle[:-4])
file_out.write(line)
file_out.write(str(unique_google))
file_out.write('\n\n')
line = "-----------------------\nUnique to {0}\n".format(bhandle[:-4])
file_out.write(line)
file_out.write(str(unique_sis))
file_out.write('\n')
file_out.close()

#output ready for google

gfile_out = open('google_upload_formatted.csv', 'w')
grades = {'8':'17', '7':'18', '6':'19'}

blank_google = open("blank_google_upload.csv")
line = blank_google.readline()
gfile_out.write(line)

#google upload columns -->  First Name,Last Name,Email Address,Password(ID#)
for each in unique_sis:
	formatted_email_address = each[sis_first_name][0] + each[sis_last_name] + grades[each[sis_grade]]

	line = each[sis_first_name] + ',' + each[sis_last_name] + ',' + formatted_email_address + ',' + each[sis_ID] + '\n'
	gfile_out.write(line)
gfile_out.close()

<commit_msg>Add replacements for both dashes and spaces in names for both csv's to better normailize the data instead of only replacing whats expected.<commit_after># have it add to a second list instead of making a duplicate of the first list (possibly faster)
# have it skip over staff
# fix for loop in the removing dashes and spaces
# have it add to a second file instead of making a duplicate of the first
# create default settings for the data file columns instead of using numbers
# create an 'error file', have different sections fail 'gracefully'
# format output file to include the date to make it more obvious, also so it doesnt overwrite previous data
# split up some sections into seperate functions
# new task to find duplicates in a file
# perhaps an 'opening' section or help section
print 'v 0.0.2a'

import re

#default coloumn locations
google_user_name = 0; google_first_name = 1; google_last_name = 2
sis_first_name = 0; sis_last_name = 1; sis_ID = 2; sis_grade = 3

#ask for source and destination csv's
ahandle = raw_input('Enter source A file (press enter for google_test_data.csv):')
bhandle = raw_input('Enter source B file (press enter for ic_test_data.csv):')

try:
	if len(ahandle) < 1 : ahandle = 'google_test_data.csv'
	afile = open(ahandle).read().split('\n')
	if len(bhandle) < 1 : bhandle = 'ic_test_data.csv'
	bfile = open(bhandle).read().split('\n')
except:
	print 'one of those files was no good'
	exit()

#load both csv's into lists
google_accounts = [each for each in [line.split(',') for line in afile] if len(each) > 3]  #google coloumns are:  email, First Name, Last Name
ic_accounts = [each for each in [line.split(',') for line in bfile] if len(each) > 3]  #IC columns:   first name, lastname, ID#, grade

#remove header rows
google_accounts.pop(0)
ic_accounts.pop(0)

#to make the matching possibly quicker
google_accounts.sort()
ic_accounts.sort()

#remove staff to make matching more accurate
temp_list = []
for each in google_accounts:
	at_pos = each[google_user_name].find('@')
	user_name = each[google_user_name][0:at_pos]
	if re.search('[0-9]' , user_name) : temp_list.append(each)
google_accounts = temp_list

#remove dashes and spaces from google to normalize data
temp_list = list()
for each in google_accounts:
	each[google_last_name] = each[google_last_name].replace('-', '')
	each[google_last_name] = each[google_last_name].replace(' ', '')
	each[google_first_name] = each[google_first_name].replace('-', '')
	each[google_first_name] = each[google_first_name].replace(' ', '')
	temp_list.append(each)
	# line[2] = line[2].replace('-', '')
	# line[2] = line[2].replace(' ', '')
google_accounts = temp_list

#remove dashes and spaces from SIS to normalize data
temp_list = list()
for each in ic_accounts:
	each[sis_last_name] = each[sis_last_name].replace('-', '')
	each[sis_last_name] = each[sis_last_name].replace(' ', '')
	each[sis_first_name] = each[sis_first_name].replace('-', '')
	each[sis_first_name] = each[sis_first_name].replace(' ', '')
	temp_list.append(each)
ic_accounts = temp_list

#remove double quotes from google
temp_list = list()
for line in google_accounts:
	line[google_user_name] = line[google_user_name].replace('"', '')
	line[google_first_name] = line[google_first_name].replace('"', '')
	line[google_last_name] = line[google_last_name].replace('"', '')
	temp_list.append(line)
google_accounts = temp_list

#to prevent the for loop getting screwy when removing items
unique_google = list()
unique_sis = list()

print 'Before comparison {lista} had {alength} students, {listb} had {blength} students'.format(lista = ahandle[:-4], listb = bhandle[:-4], alength=len(google_accounts), blength =len(ic_accounts))

# check google for unique accounts
for each_google in google_accounts:
	match = False
	for each_ic in ic_accounts:
		if each_google[google_first_name] == each_ic[sis_first_name] and each_google[google_last_name] == each_ic[sis_last_name]:
			match = True
			break
	if match == False : unique_google.append(each_google)

# check sis for unique accounts
for each_ic in ic_accounts:
	match = False
	for each_google in google_accounts:
		if each_google[google_first_name] == each_ic[sis_first_name] and each_google[google_last_name] == each_ic[sis_last_name]:
			match = True
			break
	if match == False : unique_sis.append(each_ic)

print '\n{lista} had {alength} unique students, {listb} had {blength} unique students'.format(lista = ahandle[:-4], listb = bhandle[:-4], alength=len(unique_google), blength =len(unique_sis))
print '\n'

#open a new file to write unique accounts on both sides to
file_out = open('unique_accounts.txt', 'w')
line = "-----------------------\nUnique to {0}\n".format(ahandle[:-4])
file_out.write(line)
file_out.write(str(unique_google))
file_out.write('\n\n')
line = "-----------------------\nUnique to {0}\n".format(bhandle[:-4])
file_out.write(line)
file_out.write(str(unique_sis))
file_out.write('\n')
file_out.close()

#output ready for google

gfile_out = open('google_upload_formatted.csv', 'w')
grades = {'08':'17', '07':'18', '06':'19', '8':'17', '7':'18', '6':'19'}

blank_google = open("blank_google_upload.csv")
line = blank_google.readline()
gfile_out.write(line)

#google upload columns -->  First Name,Last Name,Email Address,Password(ID#)
for each in unique_sis:
	formatted_email_address = each[sis_first_name][0] + each[sis_last_name] + grades[each[sis_grade]]

	line = each[sis_first_name] + ',' + each[sis_last_name] + ',' + formatted_email_address + ',' + each[sis_ID] + '\n'
	gfile_out.write(line)
gfile_out.close()

<|endoftext|>


<commit_before># Copyright 2015 Mirantis Inc.
#
#    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.

from oslo_config import cfg

help_for_backdoor_port = (
    "Acceptable values are 0, <port>, and <start>:<end>, where 0 results "
    "in listening on a random tcp port number; <port> results in listening "
    "on the specified port number (and not enabling backdoor if that port "
    "is in use); and <start>:<end> results in listening on the smallest "
    "unused port number within the specified range of port numbers.  The "
    "chosen port is displayed in the service's log file.")
eventlet_backdoor_opts = [
    cfg.StrOpt('backdoor_port',
               help="Enable eventlet backdoor.  %s" % help_for_backdoor_port)
]

periodic_opts = [
    cfg.BoolOpt('run_external_periodic_tasks',
                default=True,
                help='Some periodic tasks can be run in a separate process. '
                     'Should we run them here?'),
]

service_opts = [
    cfg.BoolOpt('log_options',
                default=True,
                help='Enables or disables logging values of all registered '
                     'options when starting a service (at DEBUG level).'),
    cfg.IntOpt('graceful_shutdown_timeout',
               default=0,
               help='Specify a timeout after which a gracefully shutdown '
                    'server will exit. Zero value means endless wait.'),
]

wsgi_opts = [
    cfg.StrOpt('api_paste_config',
               default="api-paste.ini",
               help='File name for the paste.deploy config for api service'),
    cfg.StrOpt('wsgi_log_format',
               default='%(client_ip)s "%(request_line)s" status: '
                       '%(status_code)s  len: %(body_length)s time:'
                       ' %(wall_seconds).7f',
               help='A python format string that is used as the template to '
                    'generate log lines. The following values can be'
                    'formatted into it: client_ip, date_time, request_line, '
                    'status_code, body_length, wall_seconds.'),
    cfg.IntOpt('tcp_keepidle',
               default=600,
               help="Sets the value of TCP_KEEPIDLE in seconds for each "
                    "server socket. Not supported on OS X."),
    cfg.IntOpt('wsgi_default_pool_size',
               default=1000,
               help="Size of the pool of greenthreads used by wsgi"),
    cfg.IntOpt('max_header_line',
               default=16384,
               help="Maximum line size of message headers to be accepted. "
                    "max_header_line may need to be increased when using "
                    "large tokens (typically those generated by the "
                    "Keystone v3 API with big service catalogs)."),
    cfg.BoolOpt('wsgi_keep_alive',
                default=True,
                help="If False, closes the client socket connection "
                     "explicitly."),
    cfg.IntOpt('client_socket_timeout', default=900,
               help="Timeout for client connections' socket operations. "
                    "If an incoming connection is idle for this number of "
                    "seconds it will be closed. A value of '0' means "
                    "wait forever."),
    ]

ssl_opts = [
    cfg.StrOpt('ca_file',
               help="CA certificate file to use to verify "
                    "connecting clients.",
               deprecated_group='DEFAULT',
               deprecated_name='ssl_ca_file'),
    cfg.StrOpt('cert_file',
               help="Certificate file to use when starting "
                    "the server securely.",
               deprecated_group='DEFAULT',
               deprecated_name='ssl_cert_file'),
    cfg.StrOpt('key_file',
               help="Private key file to use when starting "
                    "the server securely.",
               deprecated_group='DEFAULT',
               deprecated_name='ssl_key_file'),
    cfg.StrOpt('version',
               help='SSL version to use (valid only if SSL enabled). '
                    'Valid values are TLSv1 and SSLv23. SSLv2, SSLv3, '
                    'TLSv1_1, and TLSv1_2 may be available on some '
                    'distributions.'
               ),
    cfg.StrOpt('ciphers',
               help='Sets the list of available ciphers. value should be a '
                    'string in the OpenSSL cipher list format.'
               ),
]
<commit_msg>Default value of graceful_shutdown_timeout is set to 60sec<commit_after># Copyright 2015 Mirantis Inc.
#
#    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.

from oslo_config import cfg

help_for_backdoor_port = (
    "Acceptable values are 0, <port>, and <start>:<end>, where 0 results "
    "in listening on a random tcp port number; <port> results in listening "
    "on the specified port number (and not enabling backdoor if that port "
    "is in use); and <start>:<end> results in listening on the smallest "
    "unused port number within the specified range of port numbers.  The "
    "chosen port is displayed in the service's log file.")
eventlet_backdoor_opts = [
    cfg.StrOpt('backdoor_port',
               help="Enable eventlet backdoor.  %s" % help_for_backdoor_port)
]

periodic_opts = [
    cfg.BoolOpt('run_external_periodic_tasks',
                default=True,
                help='Some periodic tasks can be run in a separate process. '
                     'Should we run them here?'),
]

service_opts = [
    cfg.BoolOpt('log_options',
                default=True,
                help='Enables or disables logging values of all registered '
                     'options when starting a service (at DEBUG level).'),
    cfg.IntOpt('graceful_shutdown_timeout',
               default=60,
               help='Specify a timeout after which a gracefully shutdown '
                    'server will exit. Zero value means endless wait.'),
]

wsgi_opts = [
    cfg.StrOpt('api_paste_config',
               default="api-paste.ini",
               help='File name for the paste.deploy config for api service'),
    cfg.StrOpt('wsgi_log_format',
               default='%(client_ip)s "%(request_line)s" status: '
                       '%(status_code)s  len: %(body_length)s time:'
                       ' %(wall_seconds).7f',
               help='A python format string that is used as the template to '
                    'generate log lines. The following values can be'
                    'formatted into it: client_ip, date_time, request_line, '
                    'status_code, body_length, wall_seconds.'),
    cfg.IntOpt('tcp_keepidle',
               default=600,
               help="Sets the value of TCP_KEEPIDLE in seconds for each "
                    "server socket. Not supported on OS X."),
    cfg.IntOpt('wsgi_default_pool_size',
               default=1000,
               help="Size of the pool of greenthreads used by wsgi"),
    cfg.IntOpt('max_header_line',
               default=16384,
               help="Maximum line size of message headers to be accepted. "
                    "max_header_line may need to be increased when using "
                    "large tokens (typically those generated by the "
                    "Keystone v3 API with big service catalogs)."),
    cfg.BoolOpt('wsgi_keep_alive',
                default=True,
                help="If False, closes the client socket connection "
                     "explicitly."),
    cfg.IntOpt('client_socket_timeout', default=900,
               help="Timeout for client connections' socket operations. "
                    "If an incoming connection is idle for this number of "
                    "seconds it will be closed. A value of '0' means "
                    "wait forever."),
    ]

ssl_opts = [
    cfg.StrOpt('ca_file',
               help="CA certificate file to use to verify "
                    "connecting clients.",
               deprecated_group='DEFAULT',
               deprecated_name='ssl_ca_file'),
    cfg.StrOpt('cert_file',
               help="Certificate file to use when starting "
                    "the server securely.",
               deprecated_group='DEFAULT',
               deprecated_name='ssl_cert_file'),
    cfg.StrOpt('key_file',
               help="Private key file to use when starting "
                    "the server securely.",
               deprecated_group='DEFAULT',
               deprecated_name='ssl_key_file'),
    cfg.StrOpt('version',
               help='SSL version to use (valid only if SSL enabled). '
                    'Valid values are TLSv1 and SSLv23. SSLv2, SSLv3, '
                    'TLSv1_1, and TLSv1_2 may be available on some '
                    'distributions.'
               ),
    cfg.StrOpt('ciphers',
               help='Sets the list of available ciphers. value should be a '
                    'string in the OpenSSL cipher list format.'
               ),
]
<|endoftext|>


<commit_before># coding=utf-8

# Copyright 2017 JOSÉ JOAQUÍN ESCOBAR GÓMEZ
# File: test_oidc.py
# Description:
#
# 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 keystoneauth1.tests.unit.identity import test_identity_v3_oidc
from keystoneauth1.tests.unit import oidc_fixtures
from keystoneauth1.tests.unit import utils

# from keystoneauth_oidc_refreshtoken.tests.unit import oidc_fixtures
from keystoneauth_oidc_refreshtoken import plugin as oidc

class OIDCRefreshTokenTests(test_identity_v3_oidc.BaseOIDCTests,
                            utils.TestCase):
    def setUp(self):
        super(OIDCRefreshTokenTests, self).setUp()

        self.GRANT_TYPE = 'refresh_token'

        self.ACCESS_TOKEN_ENDPOINT = 'https://localhost:8020/oidc/token'

        self.plugin = oidc.OidcRefreshToken(
            self.AUTH_URL,
            self.IDENTITY_PROVIDER,
            self.PROTOCOL,
            client_id=self.CLIENT_ID,
            client_secret=self.CLIENT_SECRET,
            project_name=self.PROJECT_NAME)

    # def test_wrong_grant_type(self):
    #     self.requests_mock.get(self.DISCOVERY_URL,
    #                            json={"grant_types_supported": ["foo", "bar"]})
    #
    #     plugin = self.plugin.__class__(self.AUTH_URL,
    #                                    self.IDENTITY_PROVIDER,
    #                                    self.PROTOCOL,
    #                                    client_id=self.CLIENT_ID,
    #                                    client_secret=self.CLIENT_SECRET,
    #                                    discovery_endpoint=self.DISCOVERY_URL)
    #
    #     self.assertRaises(exceptions.OidcPluginNotSupported,
    #                       plugin.get_unscoped_auth_ref,
    #                       self.session)
<commit_msg>discovery url provided<commit_after># coding=utf-8

# Copyright 2017 JOSÉ JOAQUÍN ESCOBAR GÓMEZ
# File: test_oidc.py
# Description:
#
# 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 keystoneauth1.tests.unit.identity import test_identity_v3_oidc
from keystoneauth1.tests.unit import oidc_fixtures
from keystoneauth1.tests.unit import utils

# from keystoneauth_oidc_refreshtoken.tests.unit import oidc_fixtures
from keystoneauth_oidc_refreshtoken import plugin as oidc

class OIDCRefreshTokenTests(test_identity_v3_oidc.BaseOIDCTests,
                            utils.TestCase):
    def setUp(self):
        super(OIDCRefreshTokenTests, self).setUp()

        self.GRANT_TYPE = 'refresh_token'

        self.DISCOVERY_URL = 'https://localhost:8020/oidc/token'

        self.plugin = oidc.OidcRefreshToken(
            self.AUTH_URL,
            self.IDENTITY_PROVIDER,
            self.PROTOCOL,
            client_id=self.CLIENT_ID,
            client_secret=self.CLIENT_SECRET,
            access_token_endpoint=self.ACCESS_TOKEN_ENDPOINT,
            project_name=self.PROJECT_NAME)

    # def test_wrong_grant_type(self):
    #     self.requests_mock.get(self.DISCOVERY_URL,
    #                            json={"grant_types_supported": ["foo", "bar"]})
    #
    #     plugin = self.plugin.__class__(self.AUTH_URL,
    #                                    self.IDENTITY_PROVIDER,
    #                                    self.PROTOCOL,
    #                                    client_id=self.CLIENT_ID,
    #                                    client_secret=self.CLIENT_SECRET,
    #                                    discovery_endpoint=self.DISCOVERY_URL)
    #
    #     self.assertRaises(exceptions.OidcPluginNotSupported,
    #                       plugin.get_unscoped_auth_ref,
    #                       self.session)
<|endoftext|>


<commit_before>import sys
import errno
import re

from ampy.pyboard import Pyboard

from fuse import FUSE, FuseOSError, Operations

class AmpyFuse(Operations):
    def __init__(self, device):
        self.board = Pyboard(device)
        self.board.enter_raw_repl()
        self.exec('import os')

    #
    # Ampy methods
    #

    def exec(self, command):
        self.board.exec(command)

    def eval(self, command):
        return self.board.eval(command).decode('utf-8')

    #
    # Filesystem methods
    #

    def access(self, path, mode):
        pass

    def chmod(self, path, mode):
        raise FuseOSError(201)

    def chown(self, path, uid, gid):
        raise FuseOSError(202)

    def getattr(self, path, fh=None):
        raise FuseOSError(203)

    def readdir(self, path, fh):
        raise FuseOSError(204)

    def readlink(self, path):
        raise FuseOSError(205)

    def mknod(self, path, mode, dev):
        raise FuseOSError(206)

    def rmdir(self, path):
        raise FuseOSError(207)

    def mkdir(self, path, mode):
        raise FuseOSError(208)

    def statfs(self, path):
        pattern = r'\((?P<f_bsize>\d+), (?P<f_frsize>\d+), (?P<f_blocks>\d+), (?P<f_bfree>\d+), (?P<f_bavail>\d+), (?P<f_files>\d+), (?P<f_ffree>\d+), (?P<f_avail>\d+), (?P<f_flag>\d+), (?P<f_namemax>\d+)\)'
        ret = self.eval("os.statvfs('{}')".format(path))
        stats = re.match(pattern, ret).groupdict()
        return {k: int(v) for k, v in stats.items()}

    def unlink(self, path):
        raise FuseOSError(200)

    def symlink(self, name, target):
        raise FuseOSError(210)

    def rename(self, old, new):
        raise FuseOSError(211)

    def link(self, target, name):
        raise FuseOSError(212)

    def utimens(self, path, times=None):
        raise FuseOSError(213)

    def destroy(self, path):
        self.board.exit_raw_repl()
        self.board.close()

    #
    # File methods
    #

    def open(self, path, flags):
        raise FuseOSError(errno.EPERM)

    def create(self, path, mode, fi=None):
        raise FuseOSError(errno.EPERM)

    def read(self, path, length, offset, fh):
        raise FuseOSError(errno.EPERM)

    def write(self, path, buf, offset, fh):
        raise FuseOSError(errno.EPERM)

    def truncate(self, path, length, fh=None):
        raise FuseOSError(errno.EPERM)

    def flush(self, path, fh):
        raise FuseOSError(errno.EPERM)

    def release(self, path, fh):
        raise FuseOSError(errno.EPERM)

    def fsync(self, path, fdatasync, fh):
        raise FuseOSError(errno.EPERM)

def main(device, mntpoint):
    FUSE(AmpyFuse(device), mntpoint, nothreads=True, foreground=True)

if __name__ == '__main__':
    main(sys.argv[1], sys.argv[2])<commit_msg>getattr implementation<commit_after>import sys
import errno
import re

from ampy.pyboard import Pyboard

from fuse import FUSE, FuseOSError, Operations

class AmpyFuse(Operations):
    def __init__(self, device):
        self.board = Pyboard(device)
        self.board.enter_raw_repl()
        self.exec('import os')

    #
    # Ampy methods
    #

    def exec(self, command):
        self.board.exec(command)

    def eval(self, command):
        return self.board.eval(command).decode('utf-8')

    #
    # Filesystem methods
    #

    def access(self, path, mode):
        pass

    def chmod(self, path, mode):
        raise FuseOSError(201)

    def chown(self, path, uid, gid):
        raise FuseOSError(202)

    def getattr(self, path, fh=None):
        pattern = r'\((?P<st_mode>\d+), (?P<st_ino>\d+), (?P<st_dev>\d+), (?P<st_nlink>\d+), (?P<st_uid>\d+), (?P<st_gid>\d+), (?P<st_size>\d+), (?P<st_atime>\d+), (?P<st_mtime>\d+), (?P<st_ctime>\d+)\)'
        ret = self.eval("os.stat('{}')".format(path))
        stats = re.match(pattern, ret).groupdict()
        return {k: int(v) for k, v in stats.items()}

    def readdir(self, path, fh):
        raise FuseOSError(204)

    def readlink(self, path):
        raise FuseOSError(205)

    def mknod(self, path, mode, dev):
        raise FuseOSError(206)

    def rmdir(self, path):
        raise FuseOSError(207)

    def mkdir(self, path, mode):
        raise FuseOSError(208)

    def statfs(self, path):
        pattern = r'\((?P<f_bsize>\d+), (?P<f_frsize>\d+), (?P<f_blocks>\d+), (?P<f_bfree>\d+), (?P<f_bavail>\d+), (?P<f_files>\d+), (?P<f_ffree>\d+), (?P<f_avail>\d+), (?P<f_flag>\d+), (?P<f_namemax>\d+)\)'
        ret = self.eval("os.statvfs('{}')".format(path))
        stats = re.match(pattern, ret).groupdict()
        return {k: int(v) for k, v in stats.items()}

    def unlink(self, path):
        raise FuseOSError(200)

    def symlink(self, name, target):
        raise FuseOSError(210)

    def rename(self, old, new):
        raise FuseOSError(211)

    def link(self, target, name):
        raise FuseOSError(212)

    def utimens(self, path, times=None):
        raise FuseOSError(213)

    def destroy(self, path):
        self.board.exit_raw_repl()
        self.board.close()

    #
    # File methods
    #

    def open(self, path, flags):
        raise FuseOSError(errno.EPERM)

    def create(self, path, mode, fi=None):
        raise FuseOSError(errno.EPERM)

    def read(self, path, length, offset, fh):
        raise FuseOSError(errno.EPERM)

    def write(self, path, buf, offset, fh):
        raise FuseOSError(errno.EPERM)

    def truncate(self, path, length, fh=None):
        raise FuseOSError(errno.EPERM)

    def flush(self, path, fh):
        raise FuseOSError(errno.EPERM)

    def release(self, path, fh):
        raise FuseOSError(errno.EPERM)

    def fsync(self, path, fdatasync, fh):
        raise FuseOSError(errno.EPERM)

def main(device, mntpoint):
    FUSE(AmpyFuse(device), mntpoint, nothreads=True, foreground=True)

if __name__ == '__main__':
    main(sys.argv[1], sys.argv[2])<|endoftext|>


<commit_before>"""
picture.py
Author: <your name here>
Credit: <list sources used, if any>

Assignment:

Use the ggame library to "paint" a graphical picture of something (e.g. a house, a face or landscape).

Use at least:
1. Three different Color objects.
2. Ten different Sprite objects.
3. One (or more) RectangleAsset objects.
4. One (or more) CircleAsset objects.
5. One (or more) EllipseAsset objects.
6. One (or more) PolygonAsset objects.

See:
https://github.com/HHS-IntroProgramming/Standards-and-Syllabus/wiki/TUTORIAL:-Displaying-Graphics
for general information on how to use ggame.

See:
http://brythonserver.github.io/ggame/
for detailed information on ggame.

"""
from ggame import App, Color, LineStyle, Sprite, RectangleAsset, CircleAsset, EllipseAsset, PolygonAsset

# add your code here \/  \/  \/

# add your code here /\  /\  /\

myapp = App()
myapp.run()
<commit_msg>Updated from Brython Server: 9/14/2015 2:16:07 PM<commit_after>"""
picture.py
Author: Sam Supattapone
Credit: none

Assignment:

Use the ggame library to "paint" a graphical picture of something (e.g. a house, a face or landscape).

Use at least:
1. Three different Color objects.
2. Ten different Sprite objects.
3. One (or more) RectangleAsset objects.
4. One (or more) CircleAsset objects.
5. One (or more) EllipseAsset objects.
6. One (or more) PolygonAsset objects.

See:
https://github.com/HHS-IntroProgramming/Standards-and-Syllabus/wiki/TUTORIAL:-Displaying-Graphics
for general information on how to use ggame.

See:
http://brythonserver.github.io/ggame/
for detailed information on ggame.

"""
from ggame import App, Color, LineStyle, Sprite, RectangleAsset, CircleAsset, EllipseAsset, PolygonAsset

myapp = App()
myapp.run()
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
#
##################################################################################
#
#    Copyright 2014-2017 Félix Brezo and Yaiza Rubio (i3visio, contacto@i3visio.com)
#
#	OSRFramework is free software: you can redistribute it and/or modify
#	it under the terms of the GNU Affero General Public License as published by
#	the Free Software Foundation, either version 3 of the License, or
#	(at your option) any later version.
#
#	This program is distributed in the hope that it will be useful,
#	but WITHOUT ANY WARRANTY; without even the implied warranty of
#	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#	GNU Affero General Public License for more details.
#
#	You should have received a copy of the GNU Affero General Public License
#	along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
##################################################################################

import osrframework.utils.logger

# Calling the logger when being imported
osrframework.utils.logger.setupLogger(loggerName="osrframework")
__version__="0.16.4"
<commit_msg>Prepare OSRFramework 0.16.5<commit_after># -*- coding: utf-8 -*-
#
##################################################################################
#
#    Copyright 2014-2017 Félix Brezo and Yaiza Rubio (i3visio, contacto@i3visio.com)
#
#	OSRFramework is free software: you can redistribute it and/or modify
#	it under the terms of the GNU Affero General Public License as published by
#	the Free Software Foundation, either version 3 of the License, or
#	(at your option) any later version.
#
#	This program is distributed in the hope that it will be useful,
#	but WITHOUT ANY WARRANTY; without even the implied warranty of
#	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#	GNU Affero General Public License for more details.
#
#	You should have received a copy of the GNU Affero General Public License
#	along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
##################################################################################

import osrframework.utils.logger

# Calling the logger when being imported
osrframework.utils.logger.setupLogger(loggerName="osrframework")
__version__="0.16.5"
<|endoftext|>