<commit_before># -*- coding: utf-8 -*-
from rest_framework.authentication import BasicAuthentication, \
    SessionAuthentication
from rest_framework import generics
from rest_framework.permissions import IsAdminUser

from .serializers import ExportSerializer
from .models import Export

class ExportListView(generics.ListAPIView):
    serializer_class = ExportSerializer
    model = Export
    permission_classes = (IsAdminUser, )
    authentication_classes = (BasicAuthentication, SessionAuthentication)

    def get_queryset(self):
        return super(ExportListView, self).get_queryset().filter(
            user=self.request.user
        )
<commit_msg>paginate reports api<commit_after># -*- coding: utf-8 -*-
from rest_framework.authentication import BasicAuthentication, \
    SessionAuthentication
from rest_framework import generics
from rest_framework.permissions import IsAdminUser

from .serializers import ExportSerializer
from .models import Export

class ExportListView(generics.ListAPIView):
    serializer_class = ExportSerializer
    model = Export
    permission_classes = (IsAdminUser, )
    authentication_classes = (BasicAuthentication, SessionAuthentication)
    page_size = 1000

    def get_queryset(self):
        return super(ExportListView, self).get_queryset().filter(
            user=self.request.user
        )
<|endoftext|>


<commit_before>import logging
import functools
import operator

l = logging.getLogger("claripy.backends.backend_vsa")

from ..backend import Backend, BackendError

def arg_filter(f):
    @functools.wraps(f)
    def filter(*args): #pylint:disable=redefined-builtin
        if type(args[0]) in {int, long}: #pylint:disable=unidiomatic-typecheck
            raise BackendError('Unsupported argument type %s' % type(args[0]))
        return f(*args)

    return filter

def normalize_arg_order(f):
    @functools.wraps(f)
    def normalizer(*args):
        if len(args) != 2:
            raise BackendError('Unsupported arguments number %d' % len(args))

        if type(args[0]) not in { StridedInterval, DiscreteStridedIntervalSet, ValueSet }: #pylint:disable=unidiomatic-typecheck
            if type(args[1]) not in { StridedInterval, DiscreteStridedIntervalSet, ValueSet }: #pylint:disable=unidiomatic-typecheck
                raise BackendError('Unsupported arguments')
            args = [args[1], args[0]]

        return f(*args)

    return normalizer

def normalize_reversed_arguments(f):
    @functools.wraps(f)
    def normalizer(self, ast, result=None):
        arg_reversed = []
        raw_args = []
        for i in xrange(len(ast.args)):
            if isinstance(ast.args[i], Base) and \
                            type(self.convert(ast.args[i])) in { #pylint:disable=unidiomatic-typecheck
                                                    StridedInterval,
                                                    DiscreteStridedIntervalSet,
                                                    ValueSet
            }:
                if self.convert(ast.args[i]).reversed:
                    arg_reversed.append(True)
                    raw_args.append(ast.args[i].reversed)
                    continue

            # It's not reversed
            arg_reversed.append(False)
            raw_args.append(ast.args[i])

        any_reversed_arg = any(arg_reversed)
        for i in xrange(len(raw_args)):
            raw_args[i] = self.convert(raw_args[i])

        normalized = ast.swap_args(raw_args)
        ret = f(self, normalized, result=result)

        # inner_i = I(args[0]._claripy, ret, variables=variables)
        if any_reversed_arg:
            return ret.reverse()
            #ret = A(args[0]._claripy, 'Reverse', (inner_i,), variables=variables, collapsible=False)

        return ret

    return normalizer

class BackendVSA(Backend):
    def __init__(self):
        Backend.__init__(self)
        # self._make_raw_ops(set(expression_operations) - set(expression_set_operations), op_module=BackendVSA)
        self._make_expr_ops(set(expression_set_operations), op_class=self)
        self._make_raw_ops(set(backend_operations_vsa_compliant), op_module=BackendVSA)

        self._op_raw['StridedInterval'] = BackendVSA.CreateStridedInterval
        self._op_raw['ValueSet'] = ValueSet.__init__
        self._op_raw['AbstractLocation'] = AbstractLocation.__init__
        self._op_raw['Reverse'] = BackendVSA.Reverse
        self._op_raw['If'] = self.If
        self._op_expr['BVV'] = self.BVV
        self._op_expr['BoolV'] = self.BoolV
        self._op_expr['BVS'] = self.BVS

        self._balancer = Balancer(self)

    def convert(self, expr, result=None):
        return Backend.convert(self, expr.ite_excavated if isinstance(expr, Base) else expr, result=result)

    def _convert(self, a, result=None):
        if type(a) in { int, long }: #pylint:disable=unidiomatic-typecheck
            return a
        if type(a) is bool:
            return TrueResult() if a else FalseResult()
        if type(a) in { StridedInterval, DiscreteStridedIntervalSet, ValueSet }: #pylint:disable=unidiomatic-typecheck
            return a
        if isinstance(a, BoolResult):
            return a

        raise BackendError("why is fish raising NotImplementedError INSTEAD OF THE ERROR THAT'S SUPPOSED TO BE RAISED IN THIS SITUATION? SERIOUSLY, JUST RAISE A BACKENDERROR AND EVERYONE WILL BE HAPPY, BUT NO, PEOPLE HAVE TO RAISE THEIR OWN ERRORS INSTEAD OF USING THE ERRORS THAT WERE ****DESIGNED**** FOR THIS SORT OF THING. WHY DO I BOTHER DESIGNING A GOOD ERROR HIERARCHY, ANYWAYS? WILL IT BE USED? NO! IT'LL BE ALL NotImplementedError('THIS') or Exception('THAT') AND EVERYTHING WILL MELT DOWN. UGH!")

    def _eval(self, expr, n, result=None, solver=None, extra_constraints=()):
        if isinstance(expr, StridedInterval):
            return expr.eval(n)
        elif isinstance(expr, ValueSet):
            results = []

            while len(results) < n:
                results.extend(expr.eval(n - len(results)))

            return results
        elif isinstance(expr, BoolResult):
            return expr.value
        else:
            raise BackendError('Unsupported type %s' % type(expr))

    def _min(self, expr, result=None, solver=None, extra_constraints=()):
        if isinstance(expr, StridedInterval):
            if expr.is_top:
                # TODO: Return
                return StridedInterval.min_int(expr.bits)

            return expr.lower_bound
        else:
            raise BackendError('Unsupported expr type %s' % type(expr))

    def _max(self, expr, result=None, solver=None, extra_constraints=()):
        if isinstance(expr, StridedInterval):
            if expr.is_top:
                # TODO:
                return StridedInterval.max_int(expr.bits)

            return expr.upper_bound

        else:
            raise BackendError('Unsupported expr type %s' % type(expr))

    def _solution(self, obj, v, result=None, solver=None, extra_constraints=()):
        if isinstance(obj, BoolResult):
            return v in obj.value

        if isinstance(obj, StridedInterval):
            return not obj.intersection(v).is_empty

        if isinstance(obj, ValueSet):
            for _, si in obj.items():
                if not si.intersection(v).is_empty:
                    return True
            return False

        raise NotImplementedError(type(obj).__name__)

    def _has_true(self, o):
        return BoolResult.has_true(o)

    def _has_false(self, o):
        return BoolResult.has_false(o)

    def _is_true(self, o):
        return BoolResult.is_true(o)

    def _is_false(self, o):
        return BoolResult.is_false(o)

    #
    # Backend Operations
    #

    def simplify(self, e):
        raise BackendError('nope')

    def _identical(self, a, b, result=None):
        if type(a) != type(b):
            return False
        return a.identical(b)

    def _unique(self, obj, result=None): #pylint:disable=unused-argument,no-self-use
        if isinstance(obj, StridedInterval):
            return obj.unique
        elif isinstance(obj, ValueSet):
            return obj.unique
        else:
            raise BackendError('Not supported type of operand %s' % type(obj))

    def _cardinality(self, a, result=None): #pylint:disable=unused-argument,no-self-use
        return a.cardinality

    def name(self, a, result=None):
        if isinstance(a, StridedInterval):
            return a.name

        else:
            return None

    def BVV(self, ast, result=None): #pylint:disable=unused-argument
        if ast.args[0] is None:
            return StridedInterval.empty(ast.args[1])
        else:
            return self.CreateStridedInterval(bits=ast.args[1], stride=0, lower_bound=ast.args[0], upper_bound=ast.args[0])

    @staticmethod
    def BoolV(ast, result=None): #pylint:disable=unused-argument
        return TrueResult() if ast.args[0] else FalseResult()

    @staticmethod
    def And(a, *args):
        try:
            return reduce(operator.__and__, args, a)
        except TypeError:
            import ipdb; ipdb.set_trace()

    @staticmethod
    def Not(a):
        return ~a

    @staticmethod
    @normalize_arg_order
    def ULT(a, b):
        return a.ULT(b)

    @staticmethod
    @normalize_arg_order
    def ULE(a, b):
        return a.ULE(b)

    @staticmethod
    @normalize_arg_order
    def UGT(a, b):
        return a.UGT(b)

    @staticmethod
    @normalize_arg_order
    def UGE(a, b):
        return a.UGE(b)

    @staticmethod
    @normalize_arg_order
    def SLT(a, b):
        return a.SLT(b)

    @staticmethod
    @normalize_arg_order
    def SLE(a, b):
        return a.SLE(b)

    @staticmethod
    @normalize_arg_order
    def SGT(a, b):
        return a.SGT(b)

    @staticmethod
    @normalize_arg_order
    def SGE(a, b):
        return a.SGE(b)

    @staticmethod
    def BVS(ast, result=None): #pylint:disable=unused-argument
        size = ast.size()
        name, mn, mx, stride, uninitialized = ast.args
        return CreateStridedInterval(name=name, bits=size, lower_bound=mn, upper_bound=mx, stride=stride, uninitialized=uninitialized)

    def If(self, cond, t, f):
        if not self.has_true(cond):
            return f
        elif not self.has_false(cond):
            return t
        else:
            return t.union(f)

    # TODO: Implement other operations!

    @staticmethod
    def LShR(expr, shift_amount):
        return expr >> shift_amount

    @staticmethod
    def Concat(*args):
        ret = None
        for expr in args:
            if type(expr) not in { StridedInterval, DiscreteStridedIntervalSet, ValueSet }: #pylint:disable=unidiomatic-typecheck
                raise BackendError('Unsupported expr type %s' % type(expr))

            ret = ret.concat(expr) if ret is not None else expr

        return ret

    @arg_filter
    def _size(self, arg, result=None):
        if type(arg) in { StridedInterval, DiscreteStridedIntervalSet, ValueSet }: #pylint:disable=unidiomatic-typecheck
            return len(arg)
        else:
            return arg.size()

    @staticmethod
    def Extract(*args):
        low_bit = args[1]
        high_bit = args[0]
        expr = args[2]

        if type(expr) not in { StridedInterval, DiscreteStridedIntervalSet, ValueSet }: #pylint:disable=unidiomatic-typecheck
            raise BackendError('Unsupported expr type %s' % type(expr))

        ret = expr.extract(high_bit, low_bit)

        return ret

    @staticmethod
    def SignExt(*args):
        new_bits = args[0]
        expr = args[1]

        if type(expr) not in { StridedInterval, DiscreteStridedIntervalSet }: #pylint:disable=unidiomatic-typecheck
            raise BackendError('Unsupported expr type %s' % type(expr))

        return expr.sign_extend(new_bits + expr.bits)

    @staticmethod
    def ZeroExt(*args):
        new_bits = args[0]
        expr = args[1]

        if type(expr) not in { StridedInterval, DiscreteStridedIntervalSet }: #pylint:disable=unidiomatic-typecheck
            raise BackendError('Unsupported expr type %s' % type(expr))

        return expr.zero_extend(new_bits + expr.bits)

    @staticmethod
    def Reverse(arg):
        if type(arg) not in {StridedInterval, DiscreteStridedIntervalSet, ValueSet}: #pylint:disable=unidiomatic-typecheck
            raise BackendError('Unsupported expr type %s' % type(arg))

        return arg.reverse()

    @normalize_reversed_arguments
    def union(self, ast, result=None): #pylint:disable=unused-argument,no-self-use
        if len(ast.args) != 2:
            raise BackendError('Incorrect number of arguments (%d) passed to BackendVSA.union().' % len(ast.args))

        ret = ast.args[0].union(ast.args[1])

        if ret is NotImplemented:
            ret = ast.args[1].union(ast.args[0])

        return ret

    @normalize_reversed_arguments
    def intersection(self, ast, result=None): #pylint:disable=unused-argument,no-self-use
        if len(ast.args) != 2:
            raise BackendError('Incorrect number of arguments (%d) passed to BackendVSA.intersection().' % len(ast.args))

        ret = None

        for arg in ast.args:
            if ret is None:
                ret = arg
            else:
                ret = ret.intersection(arg)

        return ret

    @normalize_reversed_arguments
    def widen(self, ast, result=None): #pylint:disable=unused-argument,no-self-use
        if len(ast.args) != 2:
            raise BackendError('Incorrect number of arguments (%d) passed to BackendVSA.widen().' % len(ast.args))

        ret = ast.args[0].widen(ast.args[1])
        if ret is NotImplemented:
            ret = ast.args[1].widen(ast.args[0])

        return ret

    @staticmethod
    def CreateTopStridedInterval(bits, name=None, uninitialized=False): #pylint:disable=unused-argument,no-self-use
        return StridedInterval.top(bits, name, uninitialized=uninitialized)

    def constraint_to_si(self, expr):
        return self._balancer.constraint_to_si(expr)

from ..ast.base import Base
from ..operations import backend_operations_vsa_compliant, expression_set_operations
from ..vsa import StridedInterval, CreateStridedInterval, DiscreteStridedIntervalSet, ValueSet, AbstractLocation, BoolResult, TrueResult, FalseResult
from ..balancer import Balancer

BackendVSA.CreateStridedInterval = staticmethod(CreateStridedInterval)
<commit_msg>remove a rogue ipdb<commit_after>import logging
import functools
import operator

l = logging.getLogger("claripy.backends.backend_vsa")

from ..backend import Backend, BackendError

def arg_filter(f):
    @functools.wraps(f)
    def filter(*args): #pylint:disable=redefined-builtin
        if type(args[0]) in {int, long}: #pylint:disable=unidiomatic-typecheck
            raise BackendError('Unsupported argument type %s' % type(args[0]))
        return f(*args)

    return filter

def normalize_arg_order(f):
    @functools.wraps(f)
    def normalizer(*args):
        if len(args) != 2:
            raise BackendError('Unsupported arguments number %d' % len(args))

        if type(args[0]) not in { StridedInterval, DiscreteStridedIntervalSet, ValueSet }: #pylint:disable=unidiomatic-typecheck
            if type(args[1]) not in { StridedInterval, DiscreteStridedIntervalSet, ValueSet }: #pylint:disable=unidiomatic-typecheck
                raise BackendError('Unsupported arguments')
            args = [args[1], args[0]]

        return f(*args)

    return normalizer

def normalize_reversed_arguments(f):
    @functools.wraps(f)
    def normalizer(self, ast, result=None):
        arg_reversed = []
        raw_args = []
        for i in xrange(len(ast.args)):
            if isinstance(ast.args[i], Base) and \
                            type(self.convert(ast.args[i])) in { #pylint:disable=unidiomatic-typecheck
                                                    StridedInterval,
                                                    DiscreteStridedIntervalSet,
                                                    ValueSet
            }:
                if self.convert(ast.args[i]).reversed:
                    arg_reversed.append(True)
                    raw_args.append(ast.args[i].reversed)
                    continue

            # It's not reversed
            arg_reversed.append(False)
            raw_args.append(ast.args[i])

        any_reversed_arg = any(arg_reversed)
        for i in xrange(len(raw_args)):
            raw_args[i] = self.convert(raw_args[i])

        normalized = ast.swap_args(raw_args)
        ret = f(self, normalized, result=result)

        # inner_i = I(args[0]._claripy, ret, variables=variables)
        if any_reversed_arg:
            return ret.reverse()
            #ret = A(args[0]._claripy, 'Reverse', (inner_i,), variables=variables, collapsible=False)

        return ret

    return normalizer

class BackendVSA(Backend):
    def __init__(self):
        Backend.__init__(self)
        # self._make_raw_ops(set(expression_operations) - set(expression_set_operations), op_module=BackendVSA)
        self._make_expr_ops(set(expression_set_operations), op_class=self)
        self._make_raw_ops(set(backend_operations_vsa_compliant), op_module=BackendVSA)

        self._op_raw['StridedInterval'] = BackendVSA.CreateStridedInterval
        self._op_raw['ValueSet'] = ValueSet.__init__
        self._op_raw['AbstractLocation'] = AbstractLocation.__init__
        self._op_raw['Reverse'] = BackendVSA.Reverse
        self._op_raw['If'] = self.If
        self._op_expr['BVV'] = self.BVV
        self._op_expr['BoolV'] = self.BoolV
        self._op_expr['BVS'] = self.BVS

        self._balancer = Balancer(self)

    def convert(self, expr, result=None):
        return Backend.convert(self, expr.ite_excavated if isinstance(expr, Base) else expr, result=result)

    def _convert(self, a, result=None):
        if type(a) in { int, long }: #pylint:disable=unidiomatic-typecheck
            return a
        if type(a) is bool:
            return TrueResult() if a else FalseResult()
        if type(a) in { StridedInterval, DiscreteStridedIntervalSet, ValueSet }: #pylint:disable=unidiomatic-typecheck
            return a
        if isinstance(a, BoolResult):
            return a

        raise BackendError("why is fish raising NotImplementedError INSTEAD OF THE ERROR THAT'S SUPPOSED TO BE RAISED IN THIS SITUATION? SERIOUSLY, JUST RAISE A BACKENDERROR AND EVERYONE WILL BE HAPPY, BUT NO, PEOPLE HAVE TO RAISE THEIR OWN ERRORS INSTEAD OF USING THE ERRORS THAT WERE ****DESIGNED**** FOR THIS SORT OF THING. WHY DO I BOTHER DESIGNING A GOOD ERROR HIERARCHY, ANYWAYS? WILL IT BE USED? NO! IT'LL BE ALL NotImplementedError('THIS') or Exception('THAT') AND EVERYTHING WILL MELT DOWN. UGH!")

    def _eval(self, expr, n, result=None, solver=None, extra_constraints=()):
        if isinstance(expr, StridedInterval):
            return expr.eval(n)
        elif isinstance(expr, ValueSet):
            results = []

            while len(results) < n:
                results.extend(expr.eval(n - len(results)))

            return results
        elif isinstance(expr, BoolResult):
            return expr.value
        else:
            raise BackendError('Unsupported type %s' % type(expr))

    def _min(self, expr, result=None, solver=None, extra_constraints=()):
        if isinstance(expr, StridedInterval):
            if expr.is_top:
                # TODO: Return
                return StridedInterval.min_int(expr.bits)

            return expr.lower_bound
        else:
            raise BackendError('Unsupported expr type %s' % type(expr))

    def _max(self, expr, result=None, solver=None, extra_constraints=()):
        if isinstance(expr, StridedInterval):
            if expr.is_top:
                # TODO:
                return StridedInterval.max_int(expr.bits)

            return expr.upper_bound

        else:
            raise BackendError('Unsupported expr type %s' % type(expr))

    def _solution(self, obj, v, result=None, solver=None, extra_constraints=()):
        if isinstance(obj, BoolResult):
            return v in obj.value

        if isinstance(obj, StridedInterval):
            return not obj.intersection(v).is_empty

        if isinstance(obj, ValueSet):
            for _, si in obj.items():
                if not si.intersection(v).is_empty:
                    return True
            return False

        raise NotImplementedError(type(obj).__name__)

    def _has_true(self, o):
        return BoolResult.has_true(o)

    def _has_false(self, o):
        return BoolResult.has_false(o)

    def _is_true(self, o):
        return BoolResult.is_true(o)

    def _is_false(self, o):
        return BoolResult.is_false(o)

    #
    # Backend Operations
    #

    def simplify(self, e):
        raise BackendError('nope')

    def _identical(self, a, b, result=None):
        if type(a) != type(b):
            return False
        return a.identical(b)

    def _unique(self, obj, result=None): #pylint:disable=unused-argument,no-self-use
        if isinstance(obj, StridedInterval):
            return obj.unique
        elif isinstance(obj, ValueSet):
            return obj.unique
        else:
            raise BackendError('Not supported type of operand %s' % type(obj))

    def _cardinality(self, a, result=None): #pylint:disable=unused-argument,no-self-use
        return a.cardinality

    def name(self, a, result=None):
        if isinstance(a, StridedInterval):
            return a.name

        else:
            return None

    def BVV(self, ast, result=None): #pylint:disable=unused-argument
        if ast.args[0] is None:
            return StridedInterval.empty(ast.args[1])
        else:
            return self.CreateStridedInterval(bits=ast.args[1], stride=0, lower_bound=ast.args[0], upper_bound=ast.args[0])

    @staticmethod
    def BoolV(ast, result=None): #pylint:disable=unused-argument
        return TrueResult() if ast.args[0] else FalseResult()

    @staticmethod
    def And(a, *args):
        return reduce(operator.__and__, args, a)

    @staticmethod
    def Not(a):
        return ~a

    @staticmethod
    @normalize_arg_order
    def ULT(a, b):
        return a.ULT(b)

    @staticmethod
    @normalize_arg_order
    def ULE(a, b):
        return a.ULE(b)

    @staticmethod
    @normalize_arg_order
    def UGT(a, b):
        return a.UGT(b)

    @staticmethod
    @normalize_arg_order
    def UGE(a, b):
        return a.UGE(b)

    @staticmethod
    @normalize_arg_order
    def SLT(a, b):
        return a.SLT(b)

    @staticmethod
    @normalize_arg_order
    def SLE(a, b):
        return a.SLE(b)

    @staticmethod
    @normalize_arg_order
    def SGT(a, b):
        return a.SGT(b)

    @staticmethod
    @normalize_arg_order
    def SGE(a, b):
        return a.SGE(b)

    @staticmethod
    def BVS(ast, result=None): #pylint:disable=unused-argument
        size = ast.size()
        name, mn, mx, stride, uninitialized = ast.args
        return CreateStridedInterval(name=name, bits=size, lower_bound=mn, upper_bound=mx, stride=stride, uninitialized=uninitialized)

    def If(self, cond, t, f):
        if not self.has_true(cond):
            return f
        elif not self.has_false(cond):
            return t
        else:
            return t.union(f)

    # TODO: Implement other operations!

    @staticmethod
    def LShR(expr, shift_amount):
        return expr >> shift_amount

    @staticmethod
    def Concat(*args):
        ret = None
        for expr in args:
            if type(expr) not in { StridedInterval, DiscreteStridedIntervalSet, ValueSet }: #pylint:disable=unidiomatic-typecheck
                raise BackendError('Unsupported expr type %s' % type(expr))

            ret = ret.concat(expr) if ret is not None else expr

        return ret

    @arg_filter
    def _size(self, arg, result=None):
        if type(arg) in { StridedInterval, DiscreteStridedIntervalSet, ValueSet }: #pylint:disable=unidiomatic-typecheck
            return len(arg)
        else:
            return arg.size()

    @staticmethod
    def Extract(*args):
        low_bit = args[1]
        high_bit = args[0]
        expr = args[2]

        if type(expr) not in { StridedInterval, DiscreteStridedIntervalSet, ValueSet }: #pylint:disable=unidiomatic-typecheck
            raise BackendError('Unsupported expr type %s' % type(expr))

        ret = expr.extract(high_bit, low_bit)

        return ret

    @staticmethod
    def SignExt(*args):
        new_bits = args[0]
        expr = args[1]

        if type(expr) not in { StridedInterval, DiscreteStridedIntervalSet }: #pylint:disable=unidiomatic-typecheck
            raise BackendError('Unsupported expr type %s' % type(expr))

        return expr.sign_extend(new_bits + expr.bits)

    @staticmethod
    def ZeroExt(*args):
        new_bits = args[0]
        expr = args[1]

        if type(expr) not in { StridedInterval, DiscreteStridedIntervalSet }: #pylint:disable=unidiomatic-typecheck
            raise BackendError('Unsupported expr type %s' % type(expr))

        return expr.zero_extend(new_bits + expr.bits)

    @staticmethod
    def Reverse(arg):
        if type(arg) not in {StridedInterval, DiscreteStridedIntervalSet, ValueSet}: #pylint:disable=unidiomatic-typecheck
            raise BackendError('Unsupported expr type %s' % type(arg))

        return arg.reverse()

    @normalize_reversed_arguments
    def union(self, ast, result=None): #pylint:disable=unused-argument,no-self-use
        if len(ast.args) != 2:
            raise BackendError('Incorrect number of arguments (%d) passed to BackendVSA.union().' % len(ast.args))

        ret = ast.args[0].union(ast.args[1])

        if ret is NotImplemented:
            ret = ast.args[1].union(ast.args[0])

        return ret

    @normalize_reversed_arguments
    def intersection(self, ast, result=None): #pylint:disable=unused-argument,no-self-use
        if len(ast.args) != 2:
            raise BackendError('Incorrect number of arguments (%d) passed to BackendVSA.intersection().' % len(ast.args))

        ret = None

        for arg in ast.args:
            if ret is None:
                ret = arg
            else:
                ret = ret.intersection(arg)

        return ret

    @normalize_reversed_arguments
    def widen(self, ast, result=None): #pylint:disable=unused-argument,no-self-use
        if len(ast.args) != 2:
            raise BackendError('Incorrect number of arguments (%d) passed to BackendVSA.widen().' % len(ast.args))

        ret = ast.args[0].widen(ast.args[1])
        if ret is NotImplemented:
            ret = ast.args[1].widen(ast.args[0])

        return ret

    @staticmethod
    def CreateTopStridedInterval(bits, name=None, uninitialized=False): #pylint:disable=unused-argument,no-self-use
        return StridedInterval.top(bits, name, uninitialized=uninitialized)

    def constraint_to_si(self, expr):
        return self._balancer.constraint_to_si(expr)

from ..ast.base import Base
from ..operations import backend_operations_vsa_compliant, expression_set_operations
from ..vsa import StridedInterval, CreateStridedInterval, DiscreteStridedIntervalSet, ValueSet, AbstractLocation, BoolResult, TrueResult, FalseResult
from ..balancer import Balancer

BackendVSA.CreateStridedInterval = staticmethod(CreateStridedInterval)
<|endoftext|>


<commit_before>#!/usr/bin/env python
from datetime import datetime
from clint import args
import json
import time
try:
    import cStringIO as StringIO
except ImportError:
    import StringIO
import requests
import clint
import sys
import os

PYPI_BASE_URL = 'https://pypi.python.org/pypi/'

class TextColours:
    def __init__(self, enabled=False):
        if enabled:
            self.enable()
        else:
            self.disable()

    def enable(self):
        self.HEADER = '\033[95m'
        self.OKBLUE = '\033[94m'
        self.OKGREEN = '\033[92m'
        self.WARNING = '\033[93m'
        self.FAIL = '\033[91m'
        self.ENDC = '\033[0m'

    def disable(self):
        self.HEADER = ''
        self.OKBLUE = ''
        self.OKGREEN = ''
        self.WARNING = ''
        self.FAIL = ''
        self.ENDC = ''

def get_pypi_url(requirement, version=None):
    if version:
        return '{base}/{req}/{version}/json'.format(base=PYPI_BASE_URL,
            req=requirement, version=version)
    else:
        return '{base}/{req}/json'.format(base=PYPI_BASE_URL, req=requirement)

def load_requirements(req_file, lint, colour=TextColours(False)):
    """
        Take a file and return a dict of (requirement, versions)
        based on the requirements files
    """
    req_dict = {}
    requirements = req_file.readlines()

    for requirement in requirements:
        if '-r' in requirement[:3]:
            r, filename = requirement.replace('\n', '').strip().split(' ')
            print 'Getting a little recursive, are we?'
            req_dict = dict(req_dict.items() + load_requirements(open(os.path.join(os.path.dirname(req_file.name), filename)), lint, colour).items())

        requirement = requirement.replace('\n', '').strip().split(' ')[0]
        if requirement and requirement[0] not in ['#', '-'] and 'git' not in requirement:
            try:
                requirement, version = requirement.split('==')
                req_dict[requirement] = version
                print requirement, version
            except ValueError:
                # what are you doing!
                if lint:
                    print '%s%s doesn\'t have a version number%s' % \
                                (colour.FAIL, requirement, colour.ENDC)

    return req_dict

def get_release_date(requirement, version=None, colour=TextColours(False)):
    j = None
    try:
        j = requests.request('GET', get_pypi_url(requirement, version)).json()
    except requests.HTTPError:
        if version:
            print '%s%s (%s) isn\'t available on PyPi anymore!%s' % \
                    (colour.FAIL, requirement, version, colour.ENDC)
        else:
            print '%s%s isn\'t even on PyPi. Check that the project still exists!%s' % \
                    (colour.FAIL, requirement, colour.ENDC)
        return None

    try:
        d = j['urls'][0]['upload_time']
        return datetime.fromtimestamp(time.mktime(time.strptime(d, '%Y-%m-%dT%H:%M:%S')))
    except IndexError:
        print '%s%s (%s) didn\'t return a date property%s' % (colour.FAIL, requirement, version, colour.ENDC)

if __name__ == '__main__':
    # so, you need help do you?
    if '--help' in args.all:
        print 'piprot is a handle little tool that tells you just how rotten your ' + \
                    'requirements are!'
        print 'Turns out, they\'re pretty damn rotten!\n'
        print 'Usage:\tpiprot <requirements-file> [OPTIONS]'
        print '\tpip freeze | piprot [OPTIONS]'
        print '\nAvailable options: '
        print '  -c\t\tPretty colours'
        print '  -l --lint\tEnable linting of your requirements file'
        print '  -v\t\tVerbose output, you\'ll normally want this'
        sys.exit()

    # use the first file as our requirements file
    req_files = []

    # optionally, enable colour output
    colour = TextColours(False)
    if '-c' in args.all:
        colour.enable()

    c = clint.piped_in()
    try:
        if c:
            # some idiot piped something in
            req_file = StringIO.StringIO(c)
        else:
            # the first file is all that matters. Yep.
            # multi file support coming in 2.0
            for f in args.files:
                req_files.append(open(f))

    except IndexError:
        print '%sYou need to supply at least one filename%s' % (colour.FAIL, colour.ENDC)
        sys.exit()

    # are we being annoyingly verbose?
    verbose = False
    if '-v' in args.all:
        verbose = True

    # wanna add a little linting (this is in early stages)
    lint = False
    if '--lint' in args.all or '-l' in args.all:
        lint = True

    requirements = {}
    # basic multi file support
    for req_file in req_files:
        requirements = dict(requirements.items() + load_requirements(req_file, lint, colour).items())

    print requirements
    if len(requirements) > 0:
        total_time_delta = 0
        for req, version in requirements.items():
            latest_version = get_release_date(req, colour=colour)
            specified_version = get_release_date(req, version, colour=colour)

            if latest_version and specified_version:
                time_delta = (latest_version - specified_version).days
                total_time_delta = total_time_delta + time_delta

                if verbose:
                    if time_delta > 0:
                        print '%s%s (%s) is %s days out of date%s' % \
                                (colour.FAIL, req, version, time_delta,
                                        colour.ENDC)
                    else:
                        print '%s%s (%s) is up to date%s' % \
                                (colour.OKGREEN, req, version, colour.ENDC)

        if total_time_delta > 0:
            print "%sYour requirements are %s days out of date%s" % \
                            (colour.FAIL, total_time_delta, colour.ENDC)
        else:
            print "%sLooks like you've been keeping up to date, better go back to taming that beard!%s" % \
                                    (colour.OKGREEN, colour.ENDC)
<commit_msg>superficial reorg of imports<commit_after>#!/usr/bin/env python
from clint import args
import clint
from datetime import datetime
import json
import os
import requests
import sys
import time
try:
    import cStringIO as StringIO
except ImportError:
    import StringIO

PYPI_BASE_URL = 'https://pypi.python.org/pypi/'

class TextColours:
    def __init__(self, enabled=False):
        if enabled:
            self.enable()
        else:
            self.disable()

    def enable(self):
        self.HEADER = '\033[95m'
        self.OKBLUE = '\033[94m'
        self.OKGREEN = '\033[92m'
        self.WARNING = '\033[93m'
        self.FAIL = '\033[91m'
        self.ENDC = '\033[0m'

    def disable(self):
        self.HEADER = ''
        self.OKBLUE = ''
        self.OKGREEN = ''
        self.WARNING = ''
        self.FAIL = ''
        self.ENDC = ''

def get_pypi_url(requirement, version=None):
    if version:
        return '{base}/{req}/{version}/json'.format(base=PYPI_BASE_URL,
            req=requirement, version=version)
    else:
        return '{base}/{req}/json'.format(base=PYPI_BASE_URL, req=requirement)

def load_requirements(req_file, lint, colour=TextColours(False)):
    """
        Take a file and return a dict of (requirement, versions)
        based on the requirements files
    """
    req_dict = {}
    requirements = req_file.readlines()

    for requirement in requirements:
        if '-r' in requirement[:3]:
            r, filename = requirement.replace('\n', '').strip().split(' ')
            print 'Getting a little recursive, are we?'
            req_dict = dict(req_dict.items() + load_requirements(open(os.path.join(os.path.dirname(req_file.name), filename)), lint, colour).items())

        requirement = requirement.replace('\n', '').strip().split(' ')[0]
        if requirement and requirement[0] not in ['#', '-'] and 'git' not in requirement:
            try:
                requirement, version = requirement.split('==')
                req_dict[requirement] = version
                print requirement, version
            except ValueError:
                # what are you doing!
                if lint:
                    print '%s%s doesn\'t have a version number%s' % \
                                (colour.FAIL, requirement, colour.ENDC)

    return req_dict

def get_release_date(requirement, version=None, colour=TextColours(False)):
    j = None
    try:
        j = requests.request('GET', get_pypi_url(requirement, version)).json()
    except requests.HTTPError:
        if version:
            print '%s%s (%s) isn\'t available on PyPi anymore!%s' % \
                    (colour.FAIL, requirement, version, colour.ENDC)
        else:
            print '%s%s isn\'t even on PyPi. Check that the project still exists!%s' % \
                    (colour.FAIL, requirement, colour.ENDC)
        return None

    try:
        d = j['urls'][0]['upload_time']
        return datetime.fromtimestamp(time.mktime(time.strptime(d, '%Y-%m-%dT%H:%M:%S')))
    except IndexError:
        print '%s%s (%s) didn\'t return a date property%s' % (colour.FAIL, requirement, version, colour.ENDC)

if __name__ == '__main__':
    # so, you need help do you?
    if '--help' in args.all:
        print 'piprot is a handle little tool that tells you just how rotten your ' + \
                    'requirements are!'
        print 'Turns out, they\'re pretty damn rotten!\n'
        print 'Usage:\tpiprot <requirements-file> [OPTIONS]'
        print '\tpip freeze | piprot [OPTIONS]'
        print '\nAvailable options: '
        print '  -c\t\tPretty colours'
        print '  -l --lint\tEnable linting of your requirements file'
        print '  -v\t\tVerbose output, you\'ll normally want this'
        sys.exit()

    # use the first file as our requirements file
    req_files = []

    # optionally, enable colour output
    colour = TextColours(False)
    if '-c' in args.all:
        colour.enable()

    c = clint.piped_in()
    try:
        if c:
            # some idiot piped something in
            req_file = StringIO.StringIO(c)
        else:
            # the first file is all that matters. Yep.
            # multi file support coming in 2.0
            for f in args.files:
                req_files.append(open(f))

    except IndexError:
        print '%sYou need to supply at least one filename%s' % (colour.FAIL, colour.ENDC)
        sys.exit()

    # are we being annoyingly verbose?
    verbose = False
    if '-v' in args.all:
        verbose = True

    # wanna add a little linting (this is in early stages)
    lint = False
    if '--lint' in args.all or '-l' in args.all:
        lint = True

    requirements = {}
    # basic multi file support
    for req_file in req_files:
        requirements = dict(requirements.items() + load_requirements(req_file, lint, colour).items())

    print requirements
    if len(requirements) > 0:
        total_time_delta = 0
        for req, version in requirements.items():
            latest_version = get_release_date(req, colour=colour)
            specified_version = get_release_date(req, version, colour=colour)

            if latest_version and specified_version:
                time_delta = (latest_version - specified_version).days
                total_time_delta = total_time_delta + time_delta

                if verbose:
                    if time_delta > 0:
                        print '%s%s (%s) is %s days out of date%s' % \
                                (colour.FAIL, req, version, time_delta,
                                        colour.ENDC)
                    else:
                        print '%s%s (%s) is up to date%s' % \
                                (colour.OKGREEN, req, version, colour.ENDC)

        if total_time_delta > 0:
            print "%sYour requirements are %s days out of date%s" % \
                            (colour.FAIL, total_time_delta, colour.ENDC)
        else:
p            print "%sLooks like you've been keeping up to date, better go back to taming that beard!%s" % \
                                    (colour.OKGREEN, colour.ENDC)
<|endoftext|>


<commit_before># Copyright (c) 2015 Matthew Earl
#
# 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.

__all__ = (
    'place',
)

import cnf

class _HashableDict():
    """
    A dumb wrapper around a dict to make it hashable.

    The hash is just the id() so don't use in sets/dicts if you want different
    objects with the same value to have only one entry.

    """
    def __init__(self, position):
        self.position = position

    def __getitem__(self, key):
        return self.position[key]

def place(board, components, nets):
    """
    Place components on a board, according to a net list.

    board: The board to place components on. A subclas of `component.Board`.
    components: Iterable of components to place on the board. Each component is
        subclass of `component.Component`.
    nets: Iterable of nets. Each net is a set of terminals that are to be
        condutively connected.

    Yields:
        A dict of component to position mappings, which represents a placement
        of the components which satisfies the net list.

    """

    # Modify all objects that we wish to use as keys below such that they are
    # hashable.
    nets = [frozenset(net) for net in nets]
    positions = {c: [_HashableDict(p) for p in c.get_positions(board)]
                                                           for c in components}
    holes = board.holes

    # A lookup used below, which gives the net corresponding with a
    terminal_to_net = {t: net for net in nets for t in net}

    # Set up variables.
    #  - position_vars[comp, pos] is true iff component `comp` is in position
    #    `pos`.
    #  - net_vars[hole, net] is true iff hole `net` is part of the net `net`.
    #  - grid_vars[comp, hole] if component `comp` is occupying hole `hole`.
    position_vars = {(comp, pos): cnf.Var()
                             for comp in components for pos in positions[comp]}
    net_vars = {(hole, net): cnf.Var() for hole in holes for net in nets}
    grid_vars = {(comp, hole): cnf.Var()
                                      for comp in components for hole in holes}

    # Build up a CNF expression:
    #  - A component must be in exactly one position.
    #  - If a hole that is part of a trace is in a net, then the other hole in
    #    the trace is also in that net, and vice versa.
    #  - At most one component can be in a given hole.
    #  - Each hole can be part of at most one net.
    #  - If a component is in a particular position, then each hole occupied by
    #    a terminal of the component must be part of the net corresponding with
    #    that terminal.
    #  - If a component is in a particular position, then the holes
    #    corresponding with its terminals are considered occupied.
    #    TODO: Encode physical hole occupation info, to avoid components
    #    overlapping at non-terminal locations.
    expr = cnf.Expr.all(cnf.exactly_one(position_vars[comp, pos]
                                                    for pos in positions[comp])
                            for comp in components)
    expr |= cnf.Expr.all(cnf.iff(net_vars[h1, net], net_vars[h2, net])
                                    for h1, h2 in board.traces for net in nets)
    expr |= cnf.Expr.all(cnf.at_most_one(grid_vars[comp, hole]
                                                        for comp in components)
                            for hole in holes)
    expr |= cnf.Expr.all(cnf.at_most_one(net_vars[hole, net] for net in nets)
                            for hole in holes)
    expr |= cnf.Expr.all(cnf.implies(position_vars[comp, pos],
                                     net_vars[pos[term],
                                                        terminal_to_net[term]])
                            for comp in components
                            for pos in positions[comp]
                            for term in comp.terminals)
    expr |= cnf.Expr.all(cnf.implies(position_vars[comp, pos],
                                     grid_vars[comp, pos[term]])
                         for comp in components
                         for pos in positions[comp]
                         for term in comp.terminals)

    # Find solutions and map each one back to a mapping of components to
    # positions.
    for sol in cnf.solve(expr):
        mapping = {comp: pos.position
                     for (comp, pos), var in position_vars.items() if sol[var]}
        # If this fails the "exactly one position" constraint has been
        # violated.
        assert len(mapping) == len(components)
        yield mapping

<commit_msg>Fix a bunch of a bugs in the CNF expression<commit_after># Copyright (c) 2015 Matthew Earl
#
# 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.

__all__ = (
    'place',
)

import cnf

class _HashableDict():
    """
    A dumb wrapper around a dict to make it hashable.

    The hash is just the id() so don't use in sets/dicts if you want different
    objects with the same value to have only one entry.

    """
    def __init__(self, position):
        self.position = position

    def __getitem__(self, key):
        return self.position[key]

def place(board, components, nets):
    """
    Place components on a board, according to a net list.

    board: The board to place components on. A subclas of `component.Board`.
    components: Iterable of components to place on the board. Each component is
        subclass of `component.Component`.
    nets: Iterable of nets. Each net is a set of terminals that are to be
        condutively connected.

    Yields:
        A dict of component to position mappings, which represents a placement
        of the components which satisfies the net list.

    """

    # Modify all objects that we wish to use as keys below such that they are
    # hashable, and unpack iterables into lists.
    nets = [frozenset(net) for net in nets]
    positions = {c: [_HashableDict(p) for p in c.get_positions(board)]
                                                           for c in components}
    components = list(components)
    terminals = [t for c in components for t in c.terminals]
    holes = board.holes

    # A lookup used below, which gives the net corresponding with a
    terminal_to_net = {t: net for net in nets for t in net}

    # Set up variables.
    #  - position_vars[comp, pos] is true iff component `comp` is in position
    #    `pos`.
    #  - net_vars[hole, net] is true iff hole `net` is part of the net `net`.
    #  - grid_vars[comp, hole] if component `comp` is occupying hole `hole`.
    position_vars = {(comp, pos): cnf.Var()
                             for comp in components for pos in positions[comp]}
    net_vars = {(hole, net): cnf.Var() for hole in holes for net in nets}
    grid_vars = {(term, hole): cnf.Var()
                     for term in terminals
                     for hole in holes}

    # Build up a CNF expression:
    #  - A component must be in exactly one position.
    #  - If a hole that is part of a trace is in a net, then the other hole in
    #    the trace is also in that net, and vice versa.
    #  - At most one terminal can be in a given hole.
    #  - Each hole can be part of at most one net.
    #  - If a component is in a particular position, then each hole occupied by
    #    a terminal of the component must be part of the net corresponding with
    #    that terminal.
    #  - If a component is in a particular position, then the holes
    #    corresponding with its terminals are considered occupied by that
    #    terminal.
    #    TODO: Encode physical hole occupation info, to avoid components
    #    overlapping at non-terminal locations.
    #  - Each terminal can appear in at most one hole.
    expr = cnf.Expr.all(cnf.exactly_one(position_vars[comp, pos]
                                                    for pos in positions[comp])
                             for comp in components)
    expr |= cnf.Expr.all(cnf.iff(net_vars[h1, net], net_vars[h2, net])
                             for h1, h2 in board.traces for net in nets)
    expr |= cnf.Expr.all(cnf.at_most_one(grid_vars[term, hole]
                                                         for term in terminals)
                             for hole in holes)
    expr |= cnf.Expr.all(cnf.at_most_one(net_vars[hole, net] for net in nets)
                             for hole in holes)
    expr |= cnf.Expr.all(cnf.implies(position_vars[comp, pos],
                                     net_vars[pos[term],
                                                        terminal_to_net[term]])
                             for comp in components
                             for pos in positions[comp]
                             for term in comp.terminals)
    expr |= cnf.Expr.all(cnf.implies(position_vars[comp, pos],
                                     grid_vars[term, pos[term]])
                             for comp in components
                             for pos in positions[comp]
                             for term in comp.terminals)
    expr |= cnf.Expr.all(cnf.at_most_one(grid_vars[term, hole]
                                                             for hole in holes)
                             for term in terminals)

    # Find solutions and map each one back to a mapping of components to
    # positions.
    for sol in cnf.solve(expr):
        mapping = {comp: pos.position
                     for (comp, pos), var in position_vars.items() if sol[var]}
        # If this fails the "exactly one position" constraint has been
        # violated.
        assert len(mapping) == len(components)
        yield mapping

<|endoftext|>


<commit_before>"""
this is the stuff specific to the plant studies that are loaded. It can include comments and all that. The studytreelist will be read from the load_synth_extract file. Other variables in the conf could be overridden here.
"""

import load_synth_extract

studytreelist=["1022_1967",
               "194_2284",#early and nymphaeles
               "562_817",
               "424_532",
               "1916_3902",
               "588_878",
               "2610_6117", #malpighiales
               "826_1584",#rosaceae
               "1133_5647",
               "713_1284", #Lamiales
               "2645_6165",#Menispermaceae
               "2644_6164",#Ranunculales
               "2642_6161",#Cayophyllales; not sure if you have a better study here)
               "2140_4483",#Annonaceae
               "2648_6171",#Marchantiales
               "1118_2226", #Mentheae,lamiaceae
               "650_1147",#Meliaceae, Sapindales
               "2085_4317",#Araceae
               "2044_4212",#Orobanchaceae
               "2626_6142",#Amaranthaceae
               "2624_6139",#Veronica
               "2598_6020",#Boraginaceae
               "2564_5699",#Polystichum
               "2042_4202",#Bartramiaceae
               "2034_4191",#Ruellieae
               "1101_2172",#Rubieae
               "2565_5708",#Ericoideae
               "2641_6160",#Rubiaceae
               "99_5885",#Barnadesioideae
               "93_1411",#Symplocos
               "30_2281",#Illicium
               "36_36",#Dendropanax
               "37_5871",#Rhus
               "41_1396",#Feddea
               "50_1397",#Anagallis
               "59_5731",#Aristolochiaceae
               "73_5787",#Passiflora
               "80_5881",#Rhododendron
               "81_5863",#Pinus
               "82_5792",#Campanula
               "88_5848",#Erodium
               "2539_5465",
               #"2608_6116", #saxifrigales
               #"231_5505", #caryoph SOME SORT OF LOADING PROBLEM
               "14_12",
               "180_794",
               #"574_840", upload problems
               "576_849",
               "581_859",
               "582_862",
               "598_926",
               "599_927",
               "603_940",
               "704_1266",
               "721_1298",
               "723_1300",
               #"724_3212", upload problems
               "921_4103",
               "1300_2613",
               #"1302_2616", make for weird euphyllophyta
               "915_1802",
               "915_1803",
               "9_1",
               "142_38",
               "21_37",
               "57_777",
               "58_775",
               "72_801",
               "75_1743",
               "535_768",
               "61_816",
               "284_185",
               "2546_5493",
               "1086_2111",
               "283_184",
               "54_949",
               "1116_2217",
               "225_5991",#deep plants
               "1867_3766", #cycads
               "412_2166",#conifers
               "2046_5928" #Trebouxiophyceae, Chlorophyta
               ]

if __name__ == "__main__":
	from stephen_desktop_conf import *

	synthottolid="10218"

	print "loading synthottolid:",synthottolid
	print "loading studytreelist:",studytreelist

	load_synth_extract.run(dott,dload,studyloc,studytreelist,javapre,
				 treemloc,generallogfileloc,dsynth,synthottolid,treefn)
<commit_msg>edited plants<commit_after>"""
this is the stuff specific to the plant studies that are loaded. It can include comments and all that. The studytreelist will be read from the load_synth_extract file. Other variables in the conf could be overridden here.
"""

import load_synth_extract

studytreelist=["1022_1967",
               "194_2284",#early and nymphaeles
               "562_817",
               "424_532",
               "1916_3902",
               "588_878",
               "2610_6117", #malpighiales
               "826_1584",#rosaceae
               "1133_5647",
               "1118_2226", #Mentheae,lamiaceae
               "713_1284", #Lamiales
               "605_948", #Strophostyles (Fabaceae)
               "2045_4213", #Acacia
               "2001_4100", #Astragalus
               "2127_4426", #Papilionoideae; Vataireoid Clade
               "2055_4234",  #Genistoid legumes
               "2057_4240", #papilionoid
               "594_890", #robinioid legumes
               "998_2313", #Fabales
               "2539_5465",
               "2645_6165",#Menispermaceae
               "2644_6164",#Ranunculales
               "2642_6161",#Cayophyllales; not sure if you have a better study here)
               "2140_4483",#Annonaceae
               "2648_6171",#Marchantiales
               "650_1147",#Meliaceae, Sapindales
               "2085_4317",#Araceae
               "2044_4212",#Orobanchaceae
               "2626_6142",#Amaranthaceae
               "2624_6139",#Veronica
               "2598_6020",#Boraginaceae
               "2564_5699",#Polystichum
               "2042_4202",#Bartramiaceae
               "2034_4191",#Ruellieae
               "1101_2172",#Rubieae
               "2565_5708",#Ericoideae
               "2641_6160",#Rubiaceae
               "99_5885",#Barnadesioideae
               "93_1411",#Symplocos
               "30_2281",#Illicium
               "36_36",#Dendropanax
               "37_5871",#Rhus
               "41_1396",#Feddea
               "50_1397",#Anagallis
               "59_5731",#Aristolochiaceae
               "73_5787",#Passiflora
               "80_5881",#Rhododendron
               "81_5863",#Pinus
               "82_5792",#Campanula
               "88_5848",#Erodium
               #"2608_6116", #saxifrigales
               #"231_5505", #caryoph SOME SORT OF LOADING PROBLEM
               "14_12",
               "180_794",
               #"574_840", upload problems
               "576_849",
               "581_859",
               "582_862",
               "598_926",
               "599_927",
               "603_940",
               "704_1266",
               "721_1298",
               "723_1300",
               #"724_3212", upload problems
               "921_4103",
               "1300_2613",
               #"1302_2616", make for weird euphyllophyta
               "915_1802",
               "915_1803",
               "9_1",
               "142_38",
               "21_37",
               "57_777",
               "58_775",
               "72_801",
               "75_1743",
               "535_768",
               "61_816",
               "284_185",
               "2546_5493",
               "1086_2111",
               "283_184",
               "54_949",
               "1116_2217",
               "225_5991",#deep plants
               "1867_3766", #cycads
               "412_2166",#conifers
               "2046_5928" #Trebouxiophyceae, Chlorophyta
               ]

if __name__ == "__main__":
	from stephen_desktop_conf import *

	synthottolid="10218"

	print "loading synthottolid:",synthottolid
	print "loading studytreelist:",studytreelist

	load_synth_extract.run(dott,dload,studyloc,studytreelist,javapre,
				 treemloc,generallogfileloc,dsynth,synthottolid,treefn)
<|endoftext|>


<commit_before># Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# 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.
# ==============================================================================
"""MNIST model training using TPUs.

This program demonstrates training of the convolutional neural network model
defined in mnist.py on Google Cloud TPUs (https://cloud.google.com/tpu/).

If you are not interested in TPUs, you should ignore this file.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import os
import sys

# pylint: disable=g-bad-import-order
from absl import app as absl_app  # pylint: disable=unused-import
import tensorflow as tf
# pylint: enable=g-bad-import-order

# For open source environment, add grandparent directory for import
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(sys.path[0]))))

from official.mnist import dataset  # pylint: disable=wrong-import-position
from official.mnist import mnist  # pylint: disable=wrong-import-position

# Cloud TPU Cluster Resolver flags
tf.flags.DEFINE_string(
    "tpu", default=None,
    help="The Cloud TPU to use for training. This should be either the name "
    "used when creating the Cloud TPU, or a grpc://ip.address.of.tpu:8470 "
    "url.")
tf.flags.DEFINE_string(
    "tpu_zone", default=None,
    help="[Optional] GCE zone where the Cloud TPU is located in. If not "
    "specified, we will attempt to automatically detect the GCE project from "
    "metadata.")
tf.flags.DEFINE_string(
    "gcp_project", default=None,
    help="[Optional] Project name for the Cloud TPU-enabled project. If not "
    "specified, we will attempt to automatically detect the GCE project from "
    "metadata.")

# Model specific parameters
tf.flags.DEFINE_string("data_dir", "",
                       "Path to directory containing the MNIST dataset")
tf.flags.DEFINE_string("model_dir", None, "Estimator model_dir")
tf.flags.DEFINE_integer("batch_size", 1024,
                        "Mini-batch size for the training. Note that this "
                        "is the global batch size and not the per-shard batch.")
tf.flags.DEFINE_integer("train_steps", 1000, "Total number of training steps.")
tf.flags.DEFINE_integer("eval_steps", 0,
                        "Total number of evaluation steps. If `0`, evaluation "
                        "after training is skipped.")
tf.flags.DEFINE_float("learning_rate", 0.05, "Learning rate.")

tf.flags.DEFINE_bool("use_tpu", True, "Use TPUs rather than plain CPUs")
tf.flags.DEFINE_bool("enable_predict", True, "Do some predictions at the end")
tf.flags.DEFINE_integer("iterations", 50,
                        "Number of iterations per TPU training loop.")
tf.flags.DEFINE_integer("num_shards", 8, "Number of shards (TPU chips).")

FLAGS = tf.flags.FLAGS

def metric_fn(labels, logits):
  accuracy = tf.metrics.accuracy(
      labels=labels, predictions=tf.argmax(logits, axis=1))
  return {"accuracy": accuracy}

def model_fn(features, labels, mode, params):
  """model_fn constructs the ML model used to predict handwritten digits."""

  del params
  image = features
  if isinstance(image, dict):
    image = features["image"]

  model = mnist.create_model("channels_last")

  if mode == tf.estimator.ModeKeys.PREDICT:
    logits = model(image, training=False)
    predictions = {
        'class_ids': tf.argmax(logits, axis=1),
        'probabilities': tf.nn.softmax(logits),
    }
    return tf.contrib.tpu.TPUEstimatorSpec(mode, predictions=predictions)

  logits = model(image, training=(mode == tf.estimator.ModeKeys.TRAIN))
  loss = tf.losses.sparse_softmax_cross_entropy(labels=labels, logits=logits)

  if mode == tf.estimator.ModeKeys.TRAIN:
    learning_rate = tf.train.exponential_decay(
        FLAGS.learning_rate,
        tf.train.get_global_step(),
        decay_steps=100000,
        decay_rate=0.96)
    optimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate)
    if FLAGS.use_tpu:
      optimizer = tf.contrib.tpu.CrossShardOptimizer(optimizer)
    return tf.contrib.tpu.TPUEstimatorSpec(
        mode=mode,
        loss=loss,
        train_op=optimizer.minimize(loss, tf.train.get_global_step()))

  if mode == tf.estimator.ModeKeys.EVAL:
    return tf.contrib.tpu.TPUEstimatorSpec(
        mode=mode, loss=loss, eval_metrics=(metric_fn, [labels, logits]))

def train_input_fn(params):
  """train_input_fn defines the input pipeline used for training."""
  batch_size = params["batch_size"]
  data_dir = params["data_dir"]
  # Retrieves the batch size for the current shard. The # of shards is
  # computed according to the input pipeline deployment. See
  # `tf.contrib.tpu.RunConfig` for details.
  ds = dataset.train(data_dir).cache().repeat().shuffle(
      buffer_size=50000).batch(batch_size, drop_remainder=True)
  return ds

def eval_input_fn(params):
  batch_size = params["batch_size"]
  data_dir = params["data_dir"]
  ds = dataset.test(data_dir).batch(batch_size, drop_remainder=True)
  return ds

def predict_input_fn(params):
  batch_size = params["batch_size"]
  data_dir = params["data_dir"]
  # Take out top 10 samples from test data to make the predictions.
  ds = dataset.test(data_dir).take(10).batch(batch_size)
  return ds

def main(argv):
  del argv  # Unused.
  tf.logging.set_verbosity(tf.logging.INFO)

  tpu_cluster_resolver = tf.contrib.cluster_resolver.TPUClusterResolver(
      FLAGS.tpu,
      zone=FLAGS.tpu_zone,
      project=FLAGS.gcp_project
  )

  run_config = tf.contrib.tpu.RunConfig(
      cluster=tpu_cluster_resolver,
      model_dir=FLAGS.model_dir,
      session_config=tf.ConfigProto(
          allow_soft_placement=True, log_device_placement=True),
      tpu_config=tf.contrib.tpu.TPUConfig(FLAGS.iterations, FLAGS.num_shards),
  )

  estimator = tf.contrib.tpu.TPUEstimator(
      model_fn=model_fn,
      use_tpu=FLAGS.use_tpu,
      train_batch_size=FLAGS.batch_size,
      eval_batch_size=FLAGS.batch_size,
      predict_batch_size=FLAGS.batch_size,
      params={"data_dir": FLAGS.data_dir},
      config=run_config)
  # TPUEstimator.train *requires* a max_steps argument.
  estimator.train(input_fn=train_input_fn, max_steps=FLAGS.train_steps)
  # TPUEstimator.evaluate *requires* a steps argument.
  # Note that the number of examples used during evaluation is
  # --eval_steps * --batch_size.
  # So if you change --batch_size then change --eval_steps too.
  if FLAGS.eval_steps:
    estimator.evaluate(input_fn=eval_input_fn, steps=FLAGS.eval_steps)

  # Run prediction on top few samples of test data.
  if FLAGS.enable_predict:
    predictions = estimator.predict(input_fn=predict_input_fn)

    for pred_dict in predictions:
      template = ('Prediction is "{}" ({:.1f}%).')

      class_id = pred_dict['class_ids']
      probability = pred_dict['probabilities'][class_id]

      print(template.format(class_id, 100 * probability))

if __name__ == "__main__":
  absl_app.run()
<commit_msg>absl_app.run() fails without including `main` as an argument (#6940)<commit_after># Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# 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.
# ==============================================================================
"""MNIST model training using TPUs.

This program demonstrates training of the convolutional neural network model
defined in mnist.py on Google Cloud TPUs (https://cloud.google.com/tpu/).

If you are not interested in TPUs, you should ignore this file.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import os
import sys

# pylint: disable=g-bad-import-order
from absl import app as absl_app  # pylint: disable=unused-import
import tensorflow as tf
# pylint: enable=g-bad-import-order

# For open source environment, add grandparent directory for import
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(sys.path[0]))))

from official.mnist import dataset  # pylint: disable=wrong-import-position
from official.mnist import mnist  # pylint: disable=wrong-import-position

# Cloud TPU Cluster Resolver flags
tf.flags.DEFINE_string(
    "tpu", default=None,
    help="The Cloud TPU to use for training. This should be either the name "
    "used when creating the Cloud TPU, or a grpc://ip.address.of.tpu:8470 "
    "url.")
tf.flags.DEFINE_string(
    "tpu_zone", default=None,
    help="[Optional] GCE zone where the Cloud TPU is located in. If not "
    "specified, we will attempt to automatically detect the GCE project from "
    "metadata.")
tf.flags.DEFINE_string(
    "gcp_project", default=None,
    help="[Optional] Project name for the Cloud TPU-enabled project. If not "
    "specified, we will attempt to automatically detect the GCE project from "
    "metadata.")

# Model specific parameters
tf.flags.DEFINE_string("data_dir", "",
                       "Path to directory containing the MNIST dataset")
tf.flags.DEFINE_string("model_dir", None, "Estimator model_dir")
tf.flags.DEFINE_integer("batch_size", 1024,
                        "Mini-batch size for the training. Note that this "
                        "is the global batch size and not the per-shard batch.")
tf.flags.DEFINE_integer("train_steps", 1000, "Total number of training steps.")
tf.flags.DEFINE_integer("eval_steps", 0,
                        "Total number of evaluation steps. If `0`, evaluation "
                        "after training is skipped.")
tf.flags.DEFINE_float("learning_rate", 0.05, "Learning rate.")

tf.flags.DEFINE_bool("use_tpu", True, "Use TPUs rather than plain CPUs")
tf.flags.DEFINE_bool("enable_predict", True, "Do some predictions at the end")
tf.flags.DEFINE_integer("iterations", 50,
                        "Number of iterations per TPU training loop.")
tf.flags.DEFINE_integer("num_shards", 8, "Number of shards (TPU chips).")

FLAGS = tf.flags.FLAGS

def metric_fn(labels, logits):
  accuracy = tf.metrics.accuracy(
      labels=labels, predictions=tf.argmax(logits, axis=1))
  return {"accuracy": accuracy}

def model_fn(features, labels, mode, params):
  """model_fn constructs the ML model used to predict handwritten digits."""

  del params
  image = features
  if isinstance(image, dict):
    image = features["image"]

  model = mnist.create_model("channels_last")

  if mode == tf.estimator.ModeKeys.PREDICT:
    logits = model(image, training=False)
    predictions = {
        'class_ids': tf.argmax(logits, axis=1),
        'probabilities': tf.nn.softmax(logits),
    }
    return tf.contrib.tpu.TPUEstimatorSpec(mode, predictions=predictions)

  logits = model(image, training=(mode == tf.estimator.ModeKeys.TRAIN))
  loss = tf.losses.sparse_softmax_cross_entropy(labels=labels, logits=logits)

  if mode == tf.estimator.ModeKeys.TRAIN:
    learning_rate = tf.train.exponential_decay(
        FLAGS.learning_rate,
        tf.train.get_global_step(),
        decay_steps=100000,
        decay_rate=0.96)
    optimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate)
    if FLAGS.use_tpu:
      optimizer = tf.contrib.tpu.CrossShardOptimizer(optimizer)
    return tf.contrib.tpu.TPUEstimatorSpec(
        mode=mode,
        loss=loss,
        train_op=optimizer.minimize(loss, tf.train.get_global_step()))

  if mode == tf.estimator.ModeKeys.EVAL:
    return tf.contrib.tpu.TPUEstimatorSpec(
        mode=mode, loss=loss, eval_metrics=(metric_fn, [labels, logits]))

def train_input_fn(params):
  """train_input_fn defines the input pipeline used for training."""
  batch_size = params["batch_size"]
  data_dir = params["data_dir"]
  # Retrieves the batch size for the current shard. The # of shards is
  # computed according to the input pipeline deployment. See
  # `tf.contrib.tpu.RunConfig` for details.
  ds = dataset.train(data_dir).cache().repeat().shuffle(
      buffer_size=50000).batch(batch_size, drop_remainder=True)
  return ds

def eval_input_fn(params):
  batch_size = params["batch_size"]
  data_dir = params["data_dir"]
  ds = dataset.test(data_dir).batch(batch_size, drop_remainder=True)
  return ds

def predict_input_fn(params):
  batch_size = params["batch_size"]
  data_dir = params["data_dir"]
  # Take out top 10 samples from test data to make the predictions.
  ds = dataset.test(data_dir).take(10).batch(batch_size)
  return ds

def main(argv):
  del argv  # Unused.
  tf.logging.set_verbosity(tf.logging.INFO)

  tpu_cluster_resolver = tf.contrib.cluster_resolver.TPUClusterResolver(
      FLAGS.tpu,
      zone=FLAGS.tpu_zone,
      project=FLAGS.gcp_project
  )

  run_config = tf.contrib.tpu.RunConfig(
      cluster=tpu_cluster_resolver,
      model_dir=FLAGS.model_dir,
      session_config=tf.ConfigProto(
          allow_soft_placement=True, log_device_placement=True),
      tpu_config=tf.contrib.tpu.TPUConfig(FLAGS.iterations, FLAGS.num_shards),
  )

  estimator = tf.contrib.tpu.TPUEstimator(
      model_fn=model_fn,
      use_tpu=FLAGS.use_tpu,
      train_batch_size=FLAGS.batch_size,
      eval_batch_size=FLAGS.batch_size,
      predict_batch_size=FLAGS.batch_size,
      params={"data_dir": FLAGS.data_dir},
      config=run_config)
  # TPUEstimator.train *requires* a max_steps argument.
  estimator.train(input_fn=train_input_fn, max_steps=FLAGS.train_steps)
  # TPUEstimator.evaluate *requires* a steps argument.
  # Note that the number of examples used during evaluation is
  # --eval_steps * --batch_size.
  # So if you change --batch_size then change --eval_steps too.
  if FLAGS.eval_steps:
    estimator.evaluate(input_fn=eval_input_fn, steps=FLAGS.eval_steps)

  # Run prediction on top few samples of test data.
  if FLAGS.enable_predict:
    predictions = estimator.predict(input_fn=predict_input_fn)

    for pred_dict in predictions:
      template = ('Prediction is "{}" ({:.1f}%).')

      class_id = pred_dict['class_ids']
      probability = pred_dict['probabilities'][class_id]

      print(template.format(class_id, 100 * probability))

if __name__ == "__main__":
  absl_app.run(main)
<|endoftext|>


<commit_before>from utils import *

try:
	PlayerEventCallbacks
except NameError:
	# This is fixed. In case we add some, we have to restart.
	class PlayerEventCallbacks:
		onSongChange = None
		onSongFinished = None
		onPlayingStateChange = None

def songs(state):
	if state.curSong:
		# We just started the player and we have a current song from persistent storage.
		# Yield it now so that we begin playing with this song.
		# Yield the Song object itself, though, not the ObjectProxy. The ObjectProxy
		# would result in very strange behavior later for onSongChange events.
		song = state.curSong.__get__(None)
		assert song
		song.openFile()
		yield song
	import queue
	while True:
		song = queue.getNextSong()
		assert song
		song.openFile()
		yield song

# This is an special extra callback.
# This is called very first. We do this so that
# we always have state.curSong right.
def onSongChange(**kwargs):
	from State import state
	state.curSong = kwargs["newSong"]

def loadPlayer(state):
	import ffmpeg
	player = ffmpeg.createPlayer()
	for e in [m for m in dir(PlayerEventCallbacks) if not m.startswith("_")]:
		cb = EventCallback(targetQueue=state.updates, name=e)
		if e == "onSongChange":
			cb.extraCall = onSongChange
		setattr(PlayerEventCallbacks, e, cb)
		setattr(player, e, cb)
	player.queue = songs(state)
	return player

def playerMain():
	from State import state
	#state.player.playing = True
	for ev,args,kwargs in state.updates.read():
		if ev is PlayerEventCallbacks.onSongChange:
			state.curSong.save()
			oldSong = kwargs["oldSong"]
			if oldSong:
				if kwargs["skipped"]: oldSong.skipped = True
				state.recentlyPlayedList.append(oldSong)
				state.recentlyPlayedList.save()
		pass # onPlayingStateChange
<commit_msg>player: higher priority for process<commit_after>from utils import *

try:
	PlayerEventCallbacks
except NameError:
	# This is fixed. In case we add some, we have to restart.
	class PlayerEventCallbacks:
		onSongChange = None
		onSongFinished = None
		onPlayingStateChange = None

def songs(state):
	if state.curSong:
		# We just started the player and we have a current song from persistent storage.
		# Yield it now so that we begin playing with this song.
		# Yield the Song object itself, though, not the ObjectProxy. The ObjectProxy
		# would result in very strange behavior later for onSongChange events.
		song = state.curSong.__get__(None)
		assert song
		song.openFile()
		yield song
	import queue
	while True:
		song = queue.getNextSong()
		assert song
		song.openFile()
		yield song

# This is an special extra callback.
# This is called very first. We do this so that
# we always have state.curSong right.
def onSongChange(**kwargs):
	from State import state
	state.curSong = kwargs["newSong"]

def loadPlayer(state):
	try:
		import os
		os.nice(-5)
	except:
		print "Failed to set process nice value"
		sys.excepthook(*sys.exc_info())

	import ffmpeg
	player = ffmpeg.createPlayer()
	for e in [m for m in dir(PlayerEventCallbacks) if not m.startswith("_")]:
		cb = EventCallback(targetQueue=state.updates, name=e)
		if e == "onSongChange":
			cb.extraCall = onSongChange
		setattr(PlayerEventCallbacks, e, cb)
		setattr(player, e, cb)
	player.queue = songs(state)
	return player

def playerMain():
	from State import state
	#state.player.playing = True
	for ev,args,kwargs in state.updates.read():
		if ev is PlayerEventCallbacks.onSongChange:
			state.curSong.save()
			oldSong = kwargs["oldSong"]
			if oldSong:
				if kwargs["skipped"]: oldSong.skipped = True
				state.recentlyPlayedList.append(oldSong)
				state.recentlyPlayedList.save()
		pass # onPlayingStateChange
<|endoftext|>


<commit_before>import json
import sys
import operator

class Player:
    VERSION = "0.3"

    def betRequest(self, game_state):

        current_buy_in = game_state["current_buy_in"]
        players = game_state["players"]
        in_action = int(game_state["in_action"])
        minimum_raise = game_state["minimum_raise"]
        small_blind = game_state["small_blind"]
        hole_cards = players[in_action]["hole_cards"]
        community_cards = game_state["community_cards"]
        #stack = game_state["stack"]

        figures_count = dict()
        colors_count = dict()

        for card in hole_cards:
            if card["rank"] in figures_count:
                figures_count[card["rank"]] += 1
            else:
                figures_count[card["rank"]] = 1

            if card["suit"] in colors_count:
                colors_count[card["suit"]] += 1
            else:
                colors_count[card["suit"]] = 1

        for card in community_cards:
            if card["rank"] in figures_count:
                figures_count[card["rank"]] += 1
            else:
                figures_count[card["rank"]] = 1

            if card["suit"] in colors_count:
                colors_count[card["suit"]] += 1
            else:
                colors_count[card["suit"]] = 1

        figures_count_sorted = sorted(figures_count.items(), key=operator.itemgetter(1), reverse=True)
        colors_count_sorted = sorted(colors_count.items(), key=operator.itemgetter(1), reverse=True)

        decision_value = max(figures_count_sorted[0][1], colors_count_sorted[0][1])

        if decision_value < 2:
            return 0
        elif decision_value < 3:
            return current_buy_in - players[in_action]["bet"] + minimum_raise
        elif decision_value < 4:
            return current_buy_in - players[in_action]["bet"] + small_blind * 4
        else:
            return 10000

    def showdown(self, game_state):
        pass
<commit_msg>dont fold<commit_after>import json
import sys
import operator

class Player:
    VERSION = "0.4"

    def betRequest(self, game_state):

        current_buy_in = game_state["current_buy_in"]
        players = game_state["players"]
        in_action = int(game_state["in_action"])
        minimum_raise = game_state["minimum_raise"]
        small_blind = game_state["small_blind"]
        hole_cards = players[in_action]["hole_cards"]
        community_cards = game_state["community_cards"]
        #stack = game_state["stack"]

        figures_count = dict()
        colors_count = dict()

        for card in hole_cards:
            if card["rank"] in figures_count:
                figures_count[card["rank"]] += 1
            else:
                figures_count[card["rank"]] = 1

            if card["suit"] in colors_count:
                colors_count[card["suit"]] += 1
            else:
                colors_count[card["suit"]] = 1

        for card in community_cards:
            if card["rank"] in figures_count:
                figures_count[card["rank"]] += 1
            else:
                figures_count[card["rank"]] = 1

            if card["suit"] in colors_count:
                colors_count[card["suit"]] += 1
            else:
                colors_count[card["suit"]] = 1

        figures_count_sorted = sorted(figures_count.items(), key=operator.itemgetter(1), reverse=True)
        colors_count_sorted = sorted(colors_count.items(), key=operator.itemgetter(1), reverse=True)

        decision_value = max(figures_count_sorted[0][1], colors_count_sorted[0][1])

        if decision_value < 2:
            return current_buy_in - players[in_action]["bet"]
        elif decision_value < 3:
            return current_buy_in - players[in_action]["bet"] + minimum_raise
        elif decision_value < 4:
            return current_buy_in - players[in_action]["bet"] + small_blind * 4
        else:
            return 10000

    def showdown(self, game_state):
        pass
<|endoftext|>