from .. import Error
from GenericRequest import GenericRequest
from ..manager import PatternManager
from ..util import ResponseParser

class GenericAdventuringRequest(GenericRequest):
    """
    A base class used for common adventuring functionality. Other request
    classes related to adventuring should probably extend this one.
    """

    twiddleMsg = "Could not perform action. Thumbs were twiddled."
    notAllowedMsg = "Unable to adventure. You should not be here."
    noMonsterMsg = "Unable to determine which monster we're fighting"

    #list of self.responseData keys and ResponseParser functions to
    #iterate over with the response text to populate responseData:
    responseParsers = [
        ("meat", ResponseParser.meatGainedLost),
        ("substats", ResponseParser.substatsGainedLost),
        ("hp", ResponseParser.HPGainedLost),
        ("mp", ResponseParser.MPGainedLost),
    ]

    def parseResponse(self):
        """
        Default response method for adventuring.
        """

        if PatternManager.search("userShouldNotBeHere", self.responseText):
            raise Error.Error(self.notAllowedMsg, Error.INVALID_LOCATION)

        url = self.response.url
        if url.find("/fight.php") >= 0:
            self.responseData["adventureType"] = "combat"

            # See if the user tried to perform an invalid action.
            if PatternManager.search("twiddlingThumbs", self.responseText):
                raise Error.Error(self.twiddleMsg, Error.INVALID_ACTION)

            # Get the monster's name.
            if not PatternManager.search("monsterName", self.responseText):
                raise Error.Error(self.noMonsterMsg, Error.REQUEST_GENERIC)
            self.responseData["monsterName"] = PatternManager.match.group(1)

            # Check to see if the fight was won or lost.
            if PatternManager.search("fightWon", self.responseText):
                self.responseData["fightWon"] = True
            elif PatternManager.search("fightList", self.responseText):
                self.responseData["fightLost"] = True

            # Get items, meat/substats/hp/mp. We always need to check these
            # since they can happen at any point during the fight.
            self.parseGains()
        elif url.find("/choice.php") >= 0:
            self.responseData["adventureType"] = "choice"

            #see if we need to input a choice:
            if PatternManager.search("choiceIdentifier", self.responseText):
                self.responseData["choiceId"] = PatternManager.match.group(1)
                PatternManager.search("choiceName", self.responseText)
                self.responseData["choiceName"] = PatternManager.match.group(1)
            #otherwise we already chosen and may have received something
            else:
                self.parseGains()
        elif url.find("/adventure.php") >= 0:
            self.responseData["adventureType"] = "noncombat"
            if PatternManager.search("noncombatName", self.responseText):
                self.responseData["noncombatName"] = PatternManager.match.group(1)
            self.parseGains()
        else:
            raise Error.Error("Adventure URL not recognized: %s" %
                              url, Error.REQUEST_GENERIC)

    def parseGains(self):
        #get all of the items in responseParsers:
        for key, parser in self.responseParsers:
            self.responseData[key] = parser(self.responseText)
        #items parser requires the session to get add'l info:
        items = ResponseParser.itemsReceived(self.responseText, self.session)
        self.responseData["items"] = items

class AdventureRequest(GenericAdventuringRequest):
    """A request used to initiate an adventure at any location."""

    def __init__(self, session, locationId):
        super(AdventureRequest, self).__init__(session)
        self.url = session.serverURL + "adventure.php"
        self.requestData['snarfblat'] = locationId

class ChoiceRequest(GenericAdventuringRequest):
    """A request to choose an option for a choice adventure."""

    def __init__(self, session, choiceId, choiceNumber):
        super(ChoiceRequest, self).__init__(session)
        self.url = session.serverURL + "choice.php"
        self.requestData['pwd'] = session.pwd
        self.requestData['whichchoice'] = choiceId
        self.requestData['option'] = choiceNumber

class CombatRequest(GenericAdventuringRequest):
    """
    A request used for a single round of combat. The user may attack, use an
    item or skill, or attempt to run away.
    """
    notBothMsg = "You can't use both a skill and an item"

    # What follows are a list of available actions.
    ATTACK = 0
    USE_ITEM = 1
    USE_SKILL = 2
    RUN_AWAY = 3
    PICK_POCKET = 4

    def __init__(self, session, action, skill=None, item1=None, item2=None):
        """
        In this constructor, action should be set to CombatRequest.ATTACK,
        CombatRequest.USE_ITEM, CombatRequest.USE_SKILL, CombatRequest.RUN_AWAY,
        or CombatRequest.PICK_POCKET. If a skill or item is to be used, the
        caller should also specify param to be the number of the item or skill
        the user wishes to use.
        """
        super(CombatRequest, self).__init__(session)
        self.url = session.serverURL + "fight.php"

        if skill is not None and (item1 or item2):
            raise Error.Error(self.notBothMsg, Error.REQUEST_GENERIC)

        if action == self.ATTACK:
            self.requestData["action"] = "attack"
        elif action == self.USE_ITEM:
            self.requestData["action"] = "useitem"
            self.requestData["whichitem"] = item1
            if item2 is not None:
                self.requestData["whichitem2"] = item2
        elif action == self.USE_SKILL:
            self.requestData["action"] = "skill"
            self.requestData["whichskill"] = skill
        elif action == self.RUN_AWAY:
            self.requestData["action"] = "runaway"
        elif action == self.PICK_POCKET:
            self.requestData["action"] = "steal"

class BarrelRequest(GenericAdventuringRequest):
    """Opens a Barrel in the Barrel Full of Barrels."""
    usedMsg = "Barrel already opened or doesn't exist. (#%s)"
    noAdventuresMsg = "You don't have enough adventures to smash that"

    def __init__(self, session, whichBarrel):
        super(BarrelRequest, self).__init__(session)
        self.session = session
        self.url = session.serverURL + "barrel.php"
        self.requestData['pwd'] = session.pwd
        self.requestData['smash'] = whichBarrel

    def parseResponse(self):
        if PatternManager.search("usedBarrel", self.responseText):
            raise Error.Error(self.usedMsg % self.requestData['smash'],
                              Error.INVALID_ACTION)
        if PatternManager.search("noAdventures", self.responseText):
            raise Error.Error(self.noAdventuresMsg, Error.NOT_ENOUGH_ADVENTURES)

        url = self.response.url
        if url.find("/fight.php") >= 0:
            # Get the monster's name.
            self.responseData["adventureType"] = "combat"
            PatternManager.search("monsterName", self.responseText)
            self.responseData["monsterName"] = PatternManager.match.group(1)

            # Check to see if the fight was won or lost.
            if PatternManager.search("fightWon", self.responseText):
                self.responseData["fightWon"] = True
            elif PatternManager.search("fightLost", self.responseText):
                self.responseData["fightLost"] = True

        self.parseGains()


class Solution(object):
    def swimInWater(self, grid):
        """
        :type grid: List[List[int]]
        :rtype: int
        """
        heap = []
        heapq.heappush(heap, (grid[0][0], (0,0), grid[0][0]))
        visited = set([(0,0)])
        directions = [(1, 0), (-1, 0), (0, 1), (0, -1)]
        while True:
            h, pos, maxH = heapq.heappop(heap)
            for d in directions:
                newPos = (pos[0]+d[0], pos[1]+d[1])
                if newPos not in visited and 0<=newPos[1]<len(grid) and 0<=newPos[0]<len(grid[0]):
                    if newPos == (len(grid[0])-1, len(grid)-1):
                        return max(grid[-1][-1], maxH)
                    heapq.heappush(heap, (grid[newPos[1]][newPos[0]], newPos, max(maxH, grid[newPos[1]][newPos[0]])))
                    visited.add(newPos)


import numpy as np

from ._shapecontext import _shapecontext

def shapecontext(image, r_min, r_max, current_pixel, radial_bins=5, polar_bins=12):
    """Compute Shape Context descriptor for a given point.

    Compute Shape Context by summing non-zero points into a log-polar histogram. All non-zero pixels of the image are considered to be in the object or shape.

    Parameters
    ----------
    image : (M, N) ndarray
        Input image (greyscale).

    r_max : float
        maximum distance of the pixels that are considered in computation of histogram
        from current_pixel

    r_min : float
        minmimum distance of the pixels that are considered in computation of histogram
        from current_pixel

    current_pixel : integer tuple, (r, c)
        the pixel for which to find shape context descriptor

    radial_bins : integer
        number of log r bins in log-r vs theta histogram

    polar_bins : integer
        number of theta bins in log-r vs theta histogram

    Returns
    -------
    bin_histogram : (radial_bins, polar_bins) ndarray
        the shapecontext - the log-polar histogram of points on shape

    References
    ----------
    .. [1] Serge Belongie, Jitendra Malik and Jan Puzicha.
           "Shape matching and object recognition using shape contexts." PAMI 2002.
            http://www.eecs.berkeley.edu/Research/Projects/CS/vision/shape/belongie-pami02.pdf

    .. [2] Wikipedia, "Shape Contexts". http://en.wikipedia.org/wiki/Shape_context

    Examples
    --------
    >>> import numpy as np
    >>> from skimage import img_as_float
    >>> from skimage.feature import shapecontext
    >>> img = np.zeros((20, 20)).astype(float)
    >>> img[4:8, 4:8] = 1
    >>> px = (10, 10)
    >>> shapecontext(img, 0, 25, px, radial_bins=3, polar_bins=4)
    array([[  0.,   0.,   0.,   0.],
           [  0.,   0.,  16.,   0.],
           [  0.,   0.,   0.,   0.]])

    """
    # view input array as arrays with atleast two dimensions
    image = np.atleast_2d(image)

    if image.ndim > 3:
        raise ValueError("Currently only supports grey-level images")

    # call helper
    bin_histogram = _shapecontext(image, r_min, r_max,
                                  current_pixel[0], current_pixel[1],
                                  radial_bins, polar_bins)

    return bin_histogram


from plone.testing.z2 import Browser

import unittest
from zope import event
from emc.kb.testing import INTEGRATION_TESTING
from emc.kb.testing import FUNCTIONAL_TESTING
from plone.app.testing import TEST_USER_ID,TEST_USER_NAME, TEST_USER_PASSWORD
from plone.app.testing import setRoles,login,logout

from z3c.relationfield import RelationCatalog
from zc.relation.interfaces import ICatalog
from zope import component
from Products.CMFCore.utils import getToolByName
from zope.component import getUtility
from zope.intid import IntIds
from zope.intid.interfaces import IIntIds
from z3c.relationfield import RelationValue

from emc.kb.events import FollowedEvent
from emc.kb.events import UnFollowedEvent
from emc.kb.events import FollowedEvent
from emc.kb.events import UnFollowedEvent
from emc.memberArea.events import FavoriteEvent
from emc.memberArea.events import UnFavoriteEvent
from emc.kb.events import LikeEvent
from emc.kb.events import UnLikeEvent
from emc.memberArea.events import MemberAreaCreatedEvent

from zope.lifecycleevent.interfaces import IObjectModifiedEvent
from zope.lifecycleevent import ObjectModifiedEvent,ObjectAddedEvent

from emc.kb.contents.question import Iquestion
from emc.kb.contents.topic import Itopic
from emc.kb.contents.answer import Ianswer
from emc.kb.contents.feed import Ifeed

from emc.kb.interfaces import IFollowing
# from emc.kb.interfaces import IAnswerEvaluate
from emc.kb.interfaces import IFollowing

class TestView(unittest.TestCase):

    layer = FUNCTIONAL_TESTING
    def setUp(self):
        portal = self.layer['portal']
        self.catalog = getToolByName(portal, 'portal_catalog')
        setRoles(portal, TEST_USER_ID, ('Manager',))
        intids = getUtility(IIntIds)
        portal.invokeFactory('Folder', 'Members')
        portal.invokeFactory('emc.kb.folder', 'folder')
        portal['folder'].invokeFactory('emc.kb.mentionmefolder', 'mentionmefolder')
        portal['folder'].invokeFactory('emc.kb.feedsfolder', 'feedsfolder')
        portal['folder'].invokeFactory('emc.kb.questionfolder', 'questionfolder')
        portal['folder'].invokeFactory('emc.kb.topicfolder', 'topicfolder',title="topicfolder title")
        portal['folder']['topicfolder'].invokeFactory("emc.kb.topic",'topic1',
                                            title=u"topicone",
                                            description=u"descriptionone"
                                            )
        portal['folder']['topicfolder'].invokeFactory("emc.kb.topic",'topic2',
                                            title=u"topictwo",
                                            description=u"descriptiontwo"
                                            )
        self.t1 = portal['folder']['topicfolder']['topic1']
        self.t2 = portal['folder']['topicfolder']['topic2']
        portal['folder']['questionfolder'].invokeFactory('emc.kb.question', 'question1',
                                            title='questionone',
                                            affiliatedtopics=[RelationValue(intids.getId(self.t1))],
                                            )
        portal['folder']['questionfolder'].invokeFactory('emc.kb.question', 'question2',
                                            title='questiontwo',
                                            affiliatedtopics=[RelationValue(intids.getId(self.t1))],
                                            )
        portal['folder']['questionfolder'].invokeFactory('emc.kb.question', 'question3',
                                            title='questionthree',
                                            affiliatedtopics=[RelationValue(intids.getId(self.t1))],
                                            )
        self.q1 = portal['folder']['questionfolder']['question1']
        self.q2 = portal['folder']['questionfolder']['question2']
        self.q3 = portal['folder']['questionfolder']['question3']
        portal['folder']['questionfolder']['question1'].invokeFactory('emc.kb.answer', 'answer1',
                                                            content=u"answerone",
                                                            title=u"answerone"
                                                            )
        portal['folder']['questionfolder']['question2'].invokeFactory('emc.kb.answer', 'answer2',
                                                            content=u"answertwo",
                                                            title=u"answer2 title"
                                                            )
        portal['folder']['questionfolder']['question3'].invokeFactory('emc.kb.answer', 'answer3',
                                                            content=u"answerthree",
                                                            title=u"answer3 title"
                                                            )
        self.answer1 =portal['folder']['questionfolder']['question1']['answer1']
        self.answer2 =portal['folder']['questionfolder']['question2']['answer2']
        self.answer3 =portal['folder']['questionfolder']['question3']['answer3']
        self.t1.relatedquestion=[RelationValue(intids.getId(self.q1)),RelationValue(intids.getId(self.q2)),RelationValue(intids.getId(self.q3))]

        event.notify(ObjectModifiedEvent(self.t1))

#         acl_users = getToolByName(portal, 'acl_users')
        self.membership = getToolByName(portal,'portal_membership')
        self.membership.addMember('member', 'secret', ['Member'], [])
        self.membership.addMember('user1', 'secret', ['Member'], [])
        self.membership.addMember('user2', 'secret', ['Member'], [])
        self.membership.addMember('user3', 'secret', ['Member'], [])
#         acl_users.userFolderAddUser('user1', 'secret', ['Member'], [])
#         acl_users.userFolderAddUser('user2', 'secret', ['Member'], [])
#         acl_users.userFolderAddUser('user3', 'secret', ['Member'], [])
        self.membership.memberareaCreationFlag = True
        import transaction
        transaction.commit()
        logout()
        login(portal, 'user1')
        self.membership.loginUser()
        user = self.membership.getAuthenticatedMember()
        event.notify(MemberAreaCreatedEvent(user))
        transaction.commit()

        logout()
        login(portal, 'user2')
        self.membership.loginUser()
        user = self.membership.getAuthenticatedMember()
        event.notify(MemberAreaCreatedEvent(user))
        transaction.commit()
        logout()
        login(portal, 'user3')
        self.membership.loginUser()
        user = self.membership.getAuthenticatedMember()
        event.notify(MemberAreaCreatedEvent(user))
        user.setProperties(fullname=u"test user3")
        setRoles(portal, 'user3', ('Manager',))
        transaction.commit()
        self.portal = portal

#     def testLoggedInCreatesMemberArea(self):
#         if self.membership.memberareaCreationFlag == 'True':
#             self.assertEqual(self.membership.getHomeFolder(), None)
#             self.portal.logged_in()
#             self.assertNotEqual(self.membership.getHomeFolder(), None)

    def testtopicView(self):

        app = self.layer['app']
        portal = self.layer['portal']
        setRoles(portal, TEST_USER_ID, ('Manager',))
        browser = Browser(app)
        browser.handleErrors = False

        intids = getUtility(IIntIds)
        portal['folder']['questionfolder'].invokeFactory('emc.kb.question', 'question4',
                                            title='newquestion',
                                            affiliatedtopics=[RelationValue(intids.getId(self.t1))],
                                            )

#        browser.addHeader('Authorization', 'Basic %s:%s' % (TEST_USER_NAME, TEST_USER_PASSWORD,))
        browser.addHeader('Authorization', 'Basic %s:%s' % ('user3', 'secret',))
        import transaction
        transaction.commit()
        browser.open(self.t1.absolute_url())

        self.assertTrue("topicone" in browser.contents)
        self.assertTrue("descriptionone" in browser.contents)

#         self.assertTrue("newquestion" in browser.contents)

        self.assertTrue("questionone" in browser.contents)
        self.assertTrue("answerone" in browser.contents)
#        self.assertTrue("questiontwo" in browser.contents)
#        self.assertTrue("answertwo" in browser.contents)
#        self.assertTrue("questionthree" in browser.contents)
#        self.assertTrue("answerthree" in browser.contents)

    def testquestionView(self):
        app = self.layer['app']
        portal = self.layer['portal']

        browser = Browser(app)
        browser.handleErrors = False
        browser.addHeader('Authorization', 'Basic %s:%s' % (TEST_USER_NAME, TEST_USER_PASSWORD,))

        import transaction
        transaction.commit()

        browser.open(self.q1.absolute_url())
        self.assertTrue("topicone" in browser.contents)
        self.assertTrue("topic1" in browser.contents)
        self.assertTrue("questionone" in browser.contents)
        self.assertTrue("answerone" in browser.contents)
#        self.assertTrue("2011-12-" in browser.contents)

        self.assertTrue("test_user_1_" in browser.contents)
        self.assertTrue("defaultUser.png" in browser.contents)

    def testanswerView(self):
        app = self.layer['app']
        portal = self.layer['portal']

        browser = Browser(app)
        browser.handleErrors = False
        browser.addHeader('Authorization', 'Basic %s:%s' % ('user3', 'secret',))
        intids = getUtility(IIntIds)
        self.q1.affiliatedtopics=[RelationValue(intids.getId(self.t1))]
        event.notify(ObjectModifiedEvent(self.q1))

        import transaction
        transaction.commit()
        browser.open(self.answer1.absolute_url())

        self.assertTrue("topicone" in browser.contents)
        self.assertTrue("questionone" in browser.contents)
        self.assertTrue("test_user_1_" in browser.contents)
        self.assertTrue("defaultUser.png" in browser.contents)

        self.assertTrue("answerone" in browser.contents)
        self.assertTrue("2011-12-" in browser.contents)

    def testhotanswerView(self):
        app = self.layer['app']
        portal = self.layer['portal']

        browser = Browser(app)
        browser.handleErrors = False
        event.notify(LikeEvent(self.answer2))
        event.notify(LikeEvent(self.answer3))
        logout()
        login(portal, 'user1')
        event.notify(LikeEvent(self.answer3))
        browser.addHeader('Authorization', 'Basic %s:%s' % (TEST_USER_NAME, TEST_USER_PASSWORD,))
        import transaction
        transaction.commit()
        hotanswer = portal.absolute_url() + '/@@hotanswer'
        browser.open(hotanswer)

        self.assertTrue(u"test_user_1_" in browser.contents)
        self.assertTrue("defaultUser.png" in browser.contents)

        self.assertTrue(u"answerthree" in browser.contents)
        self.assertTrue(u"answertwo" in browser.contents)

    def testhottopicView(self):

        app = self.layer['app']
        portal = self.layer['portal']

        browser = Browser(app)
        browser.handleErrors = False
        browser.addHeader('Authorization', 'Basic %s:%s' % (TEST_USER_NAME, TEST_USER_PASSWORD,))
        import transaction
        transaction.commit()

        hottopic = portal.absolute_url() + '/@@hottopic'
        browser.open(hottopic)

#         self.assertTrue("topicfolder title" in browser.contents)
        self.assertTrue("topicone" in browser.contents)
        self.assertTrue("topictwo" in browser.contents)

    def testIfollowedView(self):
        app = self.layer['app']
        portal = self.layer['portal']

        browser = Browser(app)
        browser.handleErrors = False

        event.notify(FollowedEvent(self.q1))
        event.notify(FollowedEvent(self.q2))
        event.notify(FollowedEvent(self.q3))
        browser.addHeader('Authorization', 'Basic %s:%s' % (TEST_USER_NAME, TEST_USER_PASSWORD,))
        import transaction
        transaction.commit()

        questionfollowed = portal.absolute_url() + '/@@followed'
        browser.open(questionfollowed)

        self.assertTrue("questionone" in browser.contents)
        self.assertTrue("questiontwo" in browser.contents)
        self.assertTrue("questionthree" in browser.contents)
        self.assertTrue("col-md-2 unfollow" in browser.contents)

        event.notify(FollowedEvent(self.t1))
        event.notify(FollowedEvent(self.t2))

        browser.addHeader('Authorization', 'Basic %s:%s' % (TEST_USER_NAME, TEST_USER_PASSWORD,))
        import transaction
        transaction.commit()

        topicfollowed = portal.absolute_url() + '/@@followed'
        browser.open(topicfollowed)

        self.assertTrue("topicone" in browser.contents)
#         self.assertTrue("descriptionone" in browser.contents)
        self.assertTrue("topictwo" in browser.contents)
#         self.assertTrue("descriptiontwo" in browser.contents)

    def testmyqaView(self):
        app = self.layer['app']
        portal = self.layer['portal']

        browser = Browser(app)
        browser.handleErrors = False

        browser.addHeader('Authorization', 'Basic %s:%s' % (TEST_USER_NAME, TEST_USER_PASSWORD,))
        import transaction
        transaction.commit()
#        import pdb
#        pdb.set_trace()
        myquestion = portal.absolute_url() + '/@@myquestion'
        browser.open(myquestion)

        self.assertTrue("questionone" in browser.contents)
        self.assertTrue("questiontwo" in browser.contents)
        self.assertTrue("questionthree" in browser.contents)
        import transaction
        transaction.commit()

        myquestion = portal.absolute_url() + '/@@myquestion'
        browser.open(myquestion)
        self.assertTrue("questionone" in browser.contents)
        self.assertTrue("questiontwo" in browser.contents)
        self.assertTrue("questionthree" in browser.contents)

        browser.addHeader('Authorization', 'Basic %s:%s' % (TEST_USER_NAME, TEST_USER_PASSWORD,))
        import transaction
        transaction.commit()

        myanswer = portal.absolute_url() + '/@@myanswer'
        browser.open(myanswer)

        self.assertTrue("questionone" in browser.contents)
        self.assertTrue("questiontwo" in browser.contents)
        self.assertTrue("questionthree" in browser.contents)
        self.assertTrue("answerone" in browser.contents)
        self.assertTrue("answertwo" in browser.contents)
        self.assertTrue("answerthree" in browser.contents)

    def testmyfavoritefolderView(self):

        app = self.layer['app']
        portal = self.layer['portal']
        browser = Browser(app)
        browser.handleErrors = False

        event.notify(FavoriteEvent(self.answer1))
        event.notify(FavoriteEvent(self.answer2))
        event.notify(FavoriteEvent(self.answer3))

        browser.addHeader('Authorization', 'Basic %s:%s' % (TEST_USER_NAME, TEST_USER_PASSWORD,))
        import transaction
        transaction.commit()

        myfavoritefolder = portal.absolute_url() + '/@@myfavoritefolder'
        browser.open(myfavoritefolder)

        self.assertTrue("questionone" in browser.contents)
        self.assertTrue("questiontwo" in browser.contents)
        self.assertTrue("questionthree" in browser.contents)
        self.assertTrue("answerone" in browser.contents)
        self.assertTrue("answertwo" in browser.contents)
        self.assertTrue("answerthree" in browser.contents)

        self.assertTrue("test_user_1_" in browser.contents)
#        self.assertTrue("defaultUser.png" in browser.contents)

    def testmentionmeView(self):

        app = self.layer['app']
        portal = self.layer['portal']
        browser = Browser(app)
        browser.handleErrors = False
        event.notify(FollowedEvent(self.q1))
        event.notify(FollowedEvent(self.q2))
        event.notify(FollowedEvent(self.q3))
        portal['folder']['questionfolder'].invokeFactory('emc.kb.question', 'question10',
                             title=u"question10",
                             description = u"by user3 created"
                             )
        portal['folder']['questionfolder']['question10'].invokeFactory('emc.kb.answer', 'answer10',
                             title=u"answer10",
                             description = u"by user3 created"
                             )
        event.notify(ObjectAddedEvent(portal['folder']['questionfolder']['question10']['answer10']))
        logout()
        login(portal, 'user1')

        setRoles(portal, 'user1', ('Manager',))
        event.notify(LikeEvent(portal['folder']['questionfolder']['question10']['answer10']))
        portal['folder']['questionfolder']['question10'].invokeFactory('emc.kb.answer', 'answer11',
                             title=u"answer11",
                             description = u"by user1 created"
                             )
        event.notify(ObjectAddedEvent(portal['folder']['questionfolder']['question10']['answer11']))
        portal['folder']['questionfolder']['question1'].invokeFactory('emc.kb.answer', 'answer9',
                             title=u"answer9",
                             description = u"by user1 created"
                             )
        event.notify(ObjectAddedEvent(portal['folder']['questionfolder']['question1']['answer9']))
        browser.addHeader('Authorization', 'Basic %s:%s' % ('user3', 'secret',))
        import transaction
        transaction.commit()
        user = self.membership.getAuthenticatedMember()
        mentionmefolderUrl = self.membership.getHomeUrl(user.getId()) + "/workspace/mentionmefolder"

        browser.open(mentionmefolderUrl)
        import pdb
        pdb.set_trace()

        self.assertTrue("questionone" in browser.contents)
        self.assertTrue("questiontwo" in browser.contents)
        self.assertTrue("questionthree" in browser.contents)
        self.assertTrue("answerone" in browser.contents)
        self.assertTrue("answertwo" in browser.contents)
        self.assertTrue("answerthree" in browser.contents)

    def testsearchView(self):

        app = self.layer['app']
        portal = self.layer['portal']
        browser = Browser(app)
        browser.handleErrors = False

        browser.addHeader('Authorization', 'Basic %s:%s' % (TEST_USER_NAME, TEST_USER_PASSWORD,))
        import transaction
        transaction.commit()

        search = portal.absolute_url() + '/@@search'
        browser.open(search)

#        self.assertFalse("questionone" in browser.contents)
#        self.assertFalse("questiontwo" in browser.contents)
#        self.assertFalse("questionthree" in browser.contents)

        browser.getControl(name='form.SearchableText').value = "question"
        browser.getControl(name='form.search').click()

        self.assertTrue("questionone" in browser.contents)
        self.assertTrue("questiontwo" in browser.contents)
        self.assertTrue("questionthree" in browser.contents)

    def testpersonalhomepageView(self):
        app = self.layer['app']
        portal = self.layer['portal']
        browser = Browser(app)
        browser.handleErrors = False

        browser.addHeader('Authorization', 'Basic %s:%s' % (TEST_USER_NAME, TEST_USER_PASSWORD,))
        import transaction
        transaction.commit()

        event.notify(FollowedEvent(self.t1))
        event.notify(FollowedEvent(self.t2))
        event.notify(FollowedEvent(self.q3))
        intids = getUtility(IIntIds)
        portal['folder']['questionfolder']['question3'].invokeFactory('emc.kb.answer', 'answer5',
                                 content=u"answerfour"
                                )

        portal['folder']['questionfolder'].invokeFactory('emc.kb.question', 'question4',
                                            title='questionfour',
                                            affiliatedtopics=[RelationValue(intids.getId(self.t1))],
                                            )
        q4 = portal['folder']['questionfolder']['question4']
        event.notify(FollowedEvent(q4))
        import transaction
        transaction.commit()
        browser.open(portal['folder']['feedsfolder'].absolute_url())
        self.assertTrue("questionthree" in browser.contents)
        self.assertTrue("questionfour" in browser.contents)
#        self.assertTrue(u"test_user_1_" in browser.contents)
#        self.assertTrue("defaultUser.png" in browser.contents)
#        self.assertFalse("answerfour" in browser.contents)

    def testhomepageView(self):
        app = self.layer['app']
        portal = self.layer['portal']
        browser = Browser(app)
        browser.handleErrors = False

        browser.addHeader('Authorization', 'Basic %s:%s' % (TEST_USER_NAME, TEST_USER_PASSWORD,))
        import transaction
        transaction.commit()
        intids = getUtility(IIntIds)
        portal['folder']['questionfolder'].invokeFactory('emc.kb.question', 'question4',
                                            title='questionfour',
                                            affiliatedtopics=[RelationValue(intids.getId(self.t1))],
                                            )
        portal['folder']['questionfolder'].invokeFactory('emc.kb.question', 'question5',
                                            title='questionfive',
                                            affiliatedtopics=[RelationValue(intids.getId(self.t1))],
                                            )
        import transaction
        transaction.commit()

        event.notify(FollowedEvent(portal['folder']['questionfolder']['question4']))
        event.notify(FollowedEvent(portal['folder']['questionfolder']['question5']))
        event.notify(FollowedEvent(self.t1))
        event.notify(FollowedEvent(self.t2))

        import transaction
        transaction.commit()

        homepage = portal['folder'].absolute_url() + '/@@view'
        browser.open(homepage)

#        open('/tmp/test.html','w').write(browser.contents)

        import transaction
        transaction.commit()
        self.assertTrue("questionfour" in browser.contents)
        self.assertTrue("questionfive" in browser.contents)
        self.assertTrue("topicone" in browser.contents)
        self.assertTrue("topictwo" in browser.contents)

        self.assertTrue("questionone" in browser.contents)
        self.assertTrue("questiontwo" in browser.contents)
        self.assertTrue("questionthree" in browser.contents)
        self.assertTrue("answerone" in browser.contents)
        self.assertTrue("answertwo" in browser.contents)
        self.assertTrue("answerthree" in browser.contents)

    def testtopicfolderView(self):
        app = self.layer['app']
        portal = self.layer['portal']

        browser = Browser(app)
        browser.handleErrors = False

        import transaction
        transaction.commit()

        browser.open(portal['folder']['topicfolder'].absolute_url())

#        open('/tmp/test.html','w').write(browser.contents)

        self.assertTrue("topicone" in browser.contents)
        self.assertTrue("topictwo" in browser.contents)
#        self.assertTrue("descriptionone" in browser.contents)

#        self.assertTrue("questionone" in browser.contents)
#        self.assertTrue("questiontwo" in browser.contents)
#        self.assertTrue("questionthree" in browser.contents)
#
#        self.assertTrue("answerone" in browser.contents)
#        self.assertTrue("answertwo" in browser.contents)
#        self.assertTrue("answerthree" in browser.contents)

    def testquesionfollowView(self):
        app = self.layer['app']
        portal = self.layer['portal']

        browser = Browser(app)
        browser.handleErrors = False

        import transaction
        transaction.commit()
        event.notify(FollowedEvent(self.q1))
        event.notify(FollowedEvent(self.q2))
        event.notify(FollowedEvent(self.q3))
        browser.addHeader('Authorization', 'Basic %s:%s' % (TEST_USER_NAME, TEST_USER_PASSWORD,))
        import transaction
        transaction.commit()

        questionfollowed = portal.absolute_url() + '/@@followed'
        browser.open(questionfollowed)

        self.assertTrue("questionone" in browser.contents)
        self.assertTrue("questiontwo" in browser.contents)
        self.assertTrue("questionthree" in browser.contents)
        self.assertTrue("col-md-2 unfollow" in browser.contents)

        event.notify(FollowedEvent(self.t1))
        event.notify(FollowedEvent(self.t2))

        browser.open(portal.absolute_url() + "/@@questionfollowed")

#        open('/tmp/test.html','w').write(browser.contents)

        self.assertTrue("topicone" in browser.contents)
#         self.assertTrue("topictwo" in browser.contents)
        self.assertTrue("questionone" in browser.contents)
        self.assertTrue("questiontwo" in browser.contents)

    def testtopicfollowView(self):
        app = self.layer['app']
        portal = self.layer['portal']

        browser = Browser(app)
        browser.handleErrors = False

        import transaction
        transaction.commit()
        event.notify(FollowedEvent(self.q1))
        event.notify(FollowedEvent(self.q2))
        event.notify(FollowedEvent(self.q3))
        browser.addHeader('Authorization', 'Basic %s:%s' % (TEST_USER_NAME, TEST_USER_PASSWORD,))
        import transaction
        transaction.commit()

        questionfollowed = portal.absolute_url() + '/@@followed'
        browser.open(questionfollowed)

        self.assertTrue("questionone" in browser.contents)
        self.assertTrue("questiontwo" in browser.contents)
        self.assertTrue("questionthree" in browser.contents)
        self.assertTrue("col-md-2 unfollow" in browser.contents)

        event.notify(FollowedEvent(self.t1))
        event.notify(FollowedEvent(self.t2))
        browser.addHeader('Authorization', 'Basic %s:%s' % (TEST_USER_NAME, TEST_USER_PASSWORD,))
        import transaction
        transaction.commit()
        browser.open(portal.absolute_url() + "/@@topicfollowed")

        self.assertTrue("topicone" in browser.contents)
        self.assertTrue("topictwo" in browser.contents)


norm_cfg = dict(type='SyncBN', requires_grad=True)
data_preprocessor = dict(
    type='SegDataPreProcessor',
    mean=[123.675, 116.28, 103.53],
    std=[58.395, 57.12, 57.375],
    bgr_to_rgb=True,
    pad_val=0,
    seg_pad_val=255,
    size=(64, 64))
model = dict(
    type='EncoderDecoder',
    data_preprocessor=dict(
        type='SegDataPreProcessor',
        mean=[123.675, 116.28, 103.53],
        std=[58.395, 57.12, 57.375],
        bgr_to_rgb=True,
        pad_val=0,
        seg_pad_val=255,
        size=(64, 64)),
    pretrained=None,
    backbone=dict(
        type='UNet',
        in_channels=3,
        base_channels=64,
        num_stages=5,
        strides=(1, 1, 1, 1, 1),
        enc_num_convs=(2, 2, 2, 2, 2),
        dec_num_convs=(2, 2, 2, 2),
        downsamples=(True, True, True, True),
        enc_dilations=(1, 1, 1, 1, 1),
        dec_dilations=(1, 1, 1, 1),
        with_cp=False,
        conv_cfg=None,
        norm_cfg=dict(type='SyncBN', requires_grad=True),
        act_cfg=dict(type='ReLU'),
        upsample_cfg=dict(type='InterpConv'),
        norm_eval=False),
    neck=dict(
        type='FPN',
        in_channels=[1024, 512, 256, 128, 64],
        out_channels=64,
        num_outs=5),
    decode_head=dict(
        type='FCNHead',
        in_channels=64,
        in_index=4,
        channels=64,
        num_convs=1,
        concat_input=False,
        dropout_ratio=0.1,
        num_classes=2,
        norm_cfg=dict(type='SyncBN', requires_grad=True),
        align_corners=False,
        loss_decode=dict(
            type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0)),
    auxiliary_head=dict(
        type='FCNHead',
        in_channels=64,
        in_index=3,
        channels=64,
        num_convs=1,
        concat_input=False,
        dropout_ratio=0.1,
        num_classes=2,
        norm_cfg=dict(type='SyncBN', requires_grad=True),
        align_corners=False,
        loss_decode=dict(
            type='CrossEntropyLoss', use_sigmoid=False, loss_weight=0.4)),
    train_cfg=dict(),
    test_cfg=dict(mode='slide', crop_size=(64, 64), stride=(42, 42)))
dataset_type = 'PascalVOCDataset'
data_root = 'F:\\Python_C_Project\\Python_Project\\mmlab\\mmsegmentationv1.0.0-main\\mmsegmentation-main\\data\\training_images_voc\\'
img_scale = (584, 565)
crop_size = (64, 64)
train_pipeline = [
    dict(type='LoadImageFromFile'),
    dict(type='LoadAnnotations'),
    dict(
        type='RandomResize',
        scale=(584, 565),
        ratio_range=(0.5, 2.0),
        keep_ratio=True),
    dict(type='RandomCrop', crop_size=(64, 64), cat_max_ratio=0.75),
    dict(type='RandomFlip', prob=0.5),
    dict(type='PhotoMetricDistortion'),
    dict(type='PackSegInputs')
]
test_pipeline = [
    dict(type='LoadImageFromFile'),
    dict(type='Resize', scale=(584, 565), keep_ratio=True),
    dict(type='LoadAnnotations'),
    dict(type='PackSegInputs')
]
img_ratios = [0.5, 0.75, 1.0, 1.25, 1.5, 1.75]
tta_pipeline = [
    dict(type='LoadImageFromFile', backend_args=None),
    dict(
        type='TestTimeAug',
        transforms=[[{
            'type': 'Resize',
            'scale_factor': 0.5,
            'keep_ratio': True
        }, {
            'type': 'Resize',
            'scale_factor': 0.75,
            'keep_ratio': True
        }, {
            'type': 'Resize',
            'scale_factor': 1.0,
            'keep_ratio': True
        }, {
            'type': 'Resize',
            'scale_factor': 1.25,
            'keep_ratio': True
        }, {
            'type': 'Resize',
            'scale_factor': 1.5,
            'keep_ratio': True
        }, {
            'type': 'Resize',
            'scale_factor': 1.75,
            'keep_ratio': True
        }],
                    [{
                        'type': 'RandomFlip',
                        'prob': 0.0,
                        'direction': 'horizontal'
                    }, {
                        'type': 'RandomFlip',
                        'prob': 1.0,
                        'direction': 'horizontal'
                    }], [{
                        'type': 'LoadAnnotations'
                    }], [{
                        'type': 'PackSegInputs'
                    }]])
]
train_dataloader = dict(
    batch_size=2,
    num_workers=2,
    persistent_workers=True,
    sampler=dict(type='InfiniteSampler', shuffle=True),
    dataset=dict(
        type='RepeatDataset',
        times=4000,
        dataset=dict(
            type='PascalVOCDataset',
            data_root=
            'F:\\Python_C_Project\\Python_Project\\mmlab\\mmsegmentationv1.0.0-main\\mmsegmentation-main\\data\\training_images_voc\\',
            data_prefix=dict(
                img_path='JPEGImages', seg_map_path='SegmentationClassPNG'),
            ann_file='train.txt',
            pipeline=[
                dict(type='LoadImageFromFile'),
                dict(type='LoadAnnotations'),
                dict(
                    type='RandomResize',
                    scale=(584, 565),
                    ratio_range=(0.5, 2.0),
                    keep_ratio=True),
                dict(
                    type='RandomCrop', crop_size=(64, 64), cat_max_ratio=0.75),
                dict(type='RandomFlip', prob=0.5),
                dict(type='PhotoMetricDistortion'),
                dict(type='PackSegInputs')
            ])))
val_dataloader = dict(
    batch_size=1,
    num_workers=4,
    persistent_workers=True,
    sampler=dict(type='DefaultSampler', shuffle=False),
    dataset=dict(
        type='PascalVOCDataset',
        data_root=
        'F:\\Python_C_Project\\Python_Project\\mmlab\\mmsegmentationv1.0.0-main\\mmsegmentation-main\\data\\training_images_voc\\',
        data_prefix=dict(
            img_path='JPEGImages', seg_map_path='SegmentationClassPNG'),
        ann_file='train.txt',
        pipeline=[
            dict(type='LoadImageFromFile'),
            dict(type='Resize', scale=(584, 565), keep_ratio=True),
            dict(type='LoadAnnotations'),
            dict(type='PackSegInputs')
        ]))
test_dataloader = dict(
    batch_size=1,
    num_workers=4,
    persistent_workers=True,
    sampler=dict(type='DefaultSampler', shuffle=False),
    dataset=dict(
        type='PascalVOCDataset',
        data_root=
        'F:\\Python_C_Project\\Python_Project\\mmlab\\mmsegmentationv1.0.0-main\\mmsegmentation-main\\data\\training_images_voc\\',
        data_prefix=dict(
            img_path='JPEGImages', seg_map_path='SegmentationClassPNG'),
        ann_file='train.txt',
        pipeline=[
            dict(type='LoadImageFromFile'),
            dict(type='Resize', scale=(584, 565), keep_ratio=True),
            dict(type='LoadAnnotations'),
            dict(type='PackSegInputs')
        ]))
val_evaluator = dict(type='IoUMetric', iou_metrics=['mDice'])
test_evaluator = dict(type='IoUMetric', iou_metrics=['mDice'])
default_scope = 'mmseg'
env_cfg = dict(
    cudnn_benchmark=True,
    mp_cfg=dict(mp_start_method='fork', opencv_num_threads=0),
    dist_cfg=dict(backend='nccl'))
vis_backends = [dict(type='LocalVisBackend')]
visualizer = dict(
    type='SegLocalVisualizer',
    vis_backends=[dict(type='LocalVisBackend')],
    name='visualizer')
log_processor = dict(by_epoch=False)
log_level = 'INFO'
load_from = None
resume = False
tta_model = dict(type='SegTTAModel')
optim_wrapper = dict(
    type='OptimWrapper',
    optimizer=dict(type='SGD', lr=0.01, momentum=0.9, weight_decay=0.0005),
    clip_grad=None)
param_scheduler = [
    dict(
        type='PolyLR',
        eta_min=0.0001,
        power=0.9,
        begin=0,
        end=40000,
        by_epoch=False)
]
train_cfg = dict(type='IterBasedTrainLoop', max_iters=40000, val_interval=4000)
val_cfg = dict(type='ValLoop')
test_cfg = dict(type='TestLoop')
default_hooks = dict(
    timer=dict(type='IterTimerHook'),
    logger=dict(type='LoggerHook', interval=50, log_metric_by_epoch=False),
    param_scheduler=dict(type='ParamSchedulerHook'),
    checkpoint=dict(type='CheckpointHook', by_epoch=False, interval=4000),
    sampler_seed=dict(type='DistSamplerSeedHook'),
    visualization=dict(type='SegVisualizationHook'))
launcher = 'none'
work_dir = './work_dirs\\unet-s5-d16_fcn_4xb4-40k_drive-64x64'


from flask import Flask
app = Flask(__name__)

import os
from flask_sqlalchemy import SQLAlchemy

if os.environ.get("HEROKU"):
    app.config["SQLALCHEMY_DATABASE_URI"] = os.environ.get("DATABASE_URL")
else:
    app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///data.db"
    app.config["SQLALCHEMY_ECHO"] = True
db = SQLAlchemy(app)

from application.views import auth, forms, game, index, scoreboard, team

from os import urandom
app.config["SECRET_KEY"] = urandom(32)

from flask_login import LoginManager
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = "auth_login"
login_manager.login_message = "Please login to use this functionality."

from application.models.user import User
@login_manager.user_loader
def load_user(user_id):
    return User.query.get(user_id)

try:
    db.create_all()
except:
    pass

from application.models.bot import Bot
if Bot.query.filter_by(name="Easy").first() == None:    # If database doesn't contain information of the bots, set them up
    easy_bot = Bot("Easy")
    db.session.add(easy_bot)
    db.session().commit()
if Bot.query.filter_by(name="Hard").first() == None:
    hard_bot = Bot("Hard")
    db.session.add(hard_bot)
    db.session().commit()


from collections import defaultdict
from math import log2
from textwrap import wrap
from typing import Callable, Tuple, Union
from unicodedata import normalize

import regex  # type: ignore

from .user_types import Span

def title_to_slug_factory():
    slug_counts = defaultdict(int)
    cache = {}

    def title_to_slug(title, deduplicate=False):
        title = title.strip()
        if title not in cache:
            slug = normalize("NFD", title.lower()).encode("ASCII", "ignore").decode("ASCII")
            slug = slug.replace(" ", "-")
            slug = regex.sub(r"[^\w-]", "", slug)
            cache[title] = slug
        if deduplicate:
            slug = cache[title]
            slug_counts[slug] += 1
            slug = f"{slug}-{slug_counts[slug] - 1}"
            slug_counts[slug] += 1
            slug = slug.rstrip("-0")
            return slug
        else:
            return cache[title]

    return title_to_slug

def add_line_numbers(source: str) -> str:
    """Return a numbered version of the given source-code. Result readable up to 999 lines."""
    return "\n".join(f"{n: <4}{line}" for (n, line) in enumerate(source.split("\n"), 1))

def enumeration_to_txt_factory(
    width: int = 20,
    default_string: str = "",
    sep: str = "
",
    template: str = "{summary}{details}",
    initial_indent: str = "   ",  # take into account the details marker
) -> Callable[[str], str]:
    """Return a function formatting an enumeration string on a given column width."""

    def enumeration_to_txt(s: str) -> str:
        if not s:
            return default_string
        if len(s) <= width:
            return s
        lines = wrap(s, width, initial_indent=initial_indent)
        summary = lines[0][len(initial_indent) :]
        details = sep.join(lines[1:])
        return template.format(summary=summary, details=details)

    return enumeration_to_txt

def cost_bucket(cost: int) -> str:
    """Among a predetermined set of intervals, return that including the given positive number.

    The intervals are `[0, 0]`, `]0, 0.25[`, `[0.25, 0.5[`, `[0.5, 1[`, `[1, 2[`, `[2,
    4[`, `[4, 8[`, and so on. The result is returned as a string ready to be included in the
    recommendation report.

    >>> cost_bucket(0.75)
    "in [0.5, 1["
    """
    if cost == 0:
        return "0"
    if cost < 0.25:
        return "in ]0, 0.25["
    if cost < 0.5:
        return "in [0.25, 0.5["
    if cost < 1:
        return "in [0.5, 1["
    upper = 2 ** int(log2(cost))
    lower = 2 ** int(log2(cost) + 1)
    return f"in [{upper}, {lower}["

def couple_to_string(couple: Union[Span, Tuple[int, int]]) -> str:
    """Return a deduplicated string representation of the given couple or span.

    >>> couple_to_string((12, 15))
    "12-15"
    >>> couple_to_string((12, 12))
    "12"
    >>> couple_to_string(Span(12, 15))
    "12-15"
    """
    return f"{couple[0]}" + ("" if couple[0] == couple[1] else f"-{couple[1]}")


import csv
import math
import matplotlib.pyplot as plt
from numpy import *
from scipy import optimize

phys =  open('phys.csv', 'r')
reader = csv.reader(phys)

chi_square_val = 0
e = 2.71828 # Euler number
items = []
pre_intervals = []
counts = []

for row in reader:
	items.append(row)

for i in range(1,len(items)):
	counts.append(items[i][0])

for i1 in range(1,len(items)):
	pre_intervals.append(items[i1][1])

pre_two_intervals = "".join(pre_intervals)
intervals = pre_two_intervals.split()

def summation(d):
	summation = 0
	q = 0
	for i in d:
		summation += int(counts[q])*int(i)
		q = q + 1
	return summation

def mean(d):
	total_count = 0
	for i in range(len(counts)):
		total_count += int(d[i])
	mu  = summation(d) / total_count
	return mu

ndf = len(counts) - 2 # Header eliminated also found mean from data.

def A_the_constant(d): # Number of intervals in 15 secs
	A = 0
	for i in range(len(d)):
		A += int(d[i])
	return A

A = A_the_constant(intervals)

def Poisson(f):
	P = []
	for i in range(len(f)):
		P.append((A*e**-(mean(intervals))*(mean(intervals)**i)/(math.factorial(i))))
	return P

Poisson_dist = Poisson(counts)

def chi_square(x,y):
	chi_square = []
	i = 0
	for c in range(len(x)):
		chi_square.append(((float(intervals[i])-float(y[i])))**2/(float(y[i])))
		i += 1
	return chi_square

for i in chi_square(counts,Poisson_dist):
	chi_square_val += i

print(chi_square(counts,Poisson_dist), "Here is the result",chi_square_val,"." )

With_degrees_of_freedom_applied = chi_square_val/ndf

print(With_degrees_of_freedom_applied," is the result after n.d.f applied, and it can be seen that the probability is not high so it is not Poisson.")

plt.plot(counts, Poisson(counts), 'bo')
plt.xlabel('Number of Counts in 15 seconds intervals')
plt.ylabel('Predicated Number of intervals with above counts')
plt.show()


#Stephen Bowen 2021

# System modules
from __future__ import print_function
import os
import time
import requests
import logging

# Server modules
import flask
from flask import Flask

# Custom modules
from estop import EstopNoGui
from API import SpotAPI

# Set the web app name and create the app object
app = Flask("SpotAPI")

# Log user into spot and create instance of API
@app.route('/start')
def start():
    print("Starting")
    global activeAPI
    try:
        activeAPI = SpotAPI(flask.request.args.get("user"), flask.request.args.get("pass"))
        return flask.jsonify("Success!")
    except:
        return flask.jsonify("Failure")

# Receive generic request and execute the command
@app.route('/GenericRequest')
def GenericRequest():
    global activeAPI
    try:
        activeAPI.GenericRequest(flask.request.args.get("request"))
        return flask.jsonify("Success!")
    except:
        return flask.jsonify("Failure")

# Trigger EStop
@app.route('/stop')
def stop():
    global activeAPI
    try:
        activeAPI.stop()
        return flask.jsonify("Success!")
    except:
        return flask.jsonify("Failure")

# Clear EStop
@app.route('/ClearStop')
def clearStop():
    global activeAPI
    try:
        activeAPI.ClearStop()
        return flask.jsonify("Success!")
    except:
        return flask.jsonify("Failure")

# End connection to robot and set activeAPI to NULL
@app.route('/End')
def End():
    global activeAPI
    try:
        activeAPI.End()
        activeAPI = None
        return flask.jsonify("Success!")
    except:
        return flask.jsonify("Failure")

# Run web app on local machine
if __name__ == '__main__':
    app.run(host="192.168.80.100", port=8080)


import telebot
from telebot import types

token = ''
saved_users_massege = {} # сюда сохраняем сообщения пользователя в формате id:[mes1, mes2, mes3]

bot = telebot.TeleBot(token)

def save_message(message):
    """ функция сохраняет сообщения пользователя
    для идентефикации используется message.chat.id
    при количестве сообщений больше 3 удаляет самое старое """
    id_user = message.chat.id
    text = message.text
    try:
        saved_users_massege[id_user].append(text)
    except KeyError:
        saved_users_massege[id_user] = [text]
    if len(saved_users_massege[id_user])>3:
        saved_users_massege[id_user].remove(saved_users_massege[id_user][0])

def send_battom(message):
    """функция отправляет клавиатуру с 3 последними сообщениями
    при отсутствие сообщений отсылает одну кнопку"""
    try:
        data = saved_users_massege[message.chat.id]
    except KeyError:
        data = ['you do not have message']
    for i in range(len(data)):
        data[i] = types.KeyboardButton(data[i])
    key = types.ReplyKeyboardMarkup(resize_keyboard=True)
    key.add(*data)
    bot.send_message(message.chat.id, 'last 3 message', reply_markup=key)

@bot.message_handler(commands=['start', 'help'])
def start(message):
    bot.send_message(message.chat.id, 'send message for me :)')

@bot.message_handler(content_types = ['text'])
def communication(message):
    if message.text.lower() == 'старт':
        send_battom(message)
    else:
        bot.send_message(message.chat.id, message.text)
        save_message(message)

if __name__ == '__main__':
    bot.polling()


class Solution:
    # @param A, a list of integers
    # @param target, an integer to be searched
    # @return a list of length 2, [index1, index2]
    def searchRange(self, A, target):
        start = 0
        end = len(A) - 1
        index1 = -1
        index2 = -1
        while start != end:
            mid = (start+end)/2
            if target == A[mid]:
                break
            if target < A[mid]:
                if mid > start:
                    end = mid - 1
                elif mid == start:
                    end = mid
            elif target > A[mid]:
                if mid < end:
                    start = mid + 1
                elif mid == end:
                    start = mid
        mid = (start+end)/2
        if A[mid] != target:
            return [index1, index2]
        index1 = mid
        index2 = mid
        cur = mid-1
        while cur >= start and A[cur] == A[mid]:
            index1 = cur
            cur = cur-1
        cur = mid+1
        while cur <= end and A[cur] == A[mid]:
            index2 = cur
            cur = cur+1
        return [index1, index2]


class EntitySearchMixin(object):
    """Mixin for filtering the queryset of the EntityListView queryset"""

    def get_queryset(self):
        # Fetch the queryset from the parent's get_queryset
        queryset = super(EntitySearchMixin, self).get_queryset()

        # Get the q GET parameter from client side input
        name = self.request.GET.get("name")
        ticker = self.request.GET.get("ticker")
        cik = self.request.GET.get("cik")
        sic = self.request.GET.get("sic")
        insider = self.request.GET.get("form4_insider")
        form_4_company = self.request.GET.get("form4_subject_company")
        sc13d_beneficial_owner = self.request.GET.get("sc13d_beneficial_owner")
        sc13d_company = self.request.GET.get("sc13d_subject_company")

        # Return a filtered queryset
        if name:
            queryset = queryset.filter(entity_name__icontains=name)
        if ticker:
            queryset = queryset.filter(ticker__icontains=ticker)
        if cik:
            queryset = queryset.filter(entity_cik__icontains=cik)
        if sic:
            queryset = queryset.filter(sic__sic__icontains=sic)
        if insider:
            queryset = queryset.filter(form_4_filer__isnull=False)
        if form_4_company:
            queryset = queryset.filter(form_4_company__isnull=False)
        if sc13d_beneficial_owner:
            queryset = queryset.filter(beneficial_owner_filer__isnull=False)
        if sc13d_company:
            queryset = queryset.filter(sc13_company__isnull=False)

        # If no filters are specified return queryset
        return queryset.filter().distinct()

class SICSearchMixin(object):
    """Mixin for filtering the queryset of the SICListView queryset"""

    def get_queryset(self):
        # Fetch the queryset from the parent's get_queryset
        queryset = super(SICSearchMixin, self).get_queryset()

        # Get the q GET parameter from client side input
        sic_code = self.request.GET.get("sic_code")
        description = self.request.GET.get("description")

        # Return a filtered queryset
        if sic_code:
            queryset = queryset.filter(sic__icontains=sic_code)
        if description:
            queryset = queryset.filter(description__icontains=description)

        # If no filters are specified return queryset
        return queryset


import pandas as pd
from time import sleep as sl
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
from pandas import ExcelWriter

import seaborn as sns
sns.set_palette(sns.color_palette("tab20", 20))

from make_outp_excel_ready import split_hgts
mpl.rcParams['pdf.fonttype'] = 42

def data_metadata_import_merge(datafile,metafile,precombined):
    if precombined != "":
        fulldata = pd.read_excel(precombined, index_col=0)
    else:
        mgt_data = split_hgts(datafile, False)
        metadata = pd.read_excel(metafile,index_col=0, dtype=str,na_values="0")
        fulldata = pd.merge(mgt_data,metadata,left_index=True,right_index=True)

    return fulldata

# def major_st_over_time(dataframe):
#     df = pd.read_csv("/Users/michaelpayne/Documents/UNSW/OneDrive - UNSW/HGT_Paper/figures/dt104_major_ST_over_time/major_st_perc_over_time_cc.txt",sep="\t",header=0).set_index('Year')
#     df = df[4:]
#
#     plot = df.plot.line(figsize=(10,6))
#
#     # ax.legend(loc=1)
#     # plt.ylabel("Strain count")
#     # plt.xticks(df.index)
#     plot.set_yticks([0,20,40,60,80,100])
#     plot.set_xticks(range(1990,2011,2))
#     plot.set_xlim(1990,2018)
#     plot.legend(loc=0)
#     #plt.show
#
#     plot = plot.get_figure()
#     # plot.tight_layout()
#     plot.show()

def change_recursive(change_dict,string,count,no):
    if count == no:
        return string
    else:
        l = string.split("-")
        tocheck = l[count]
        tochange = count-1
        l = l[:tochange] + [change_dict[count][tocheck]] + l[tochange+1:]
        nstring = "-".join(l)
        count += 1
        return change_recursive(change_dict,nstring,count,no)

def get_inconsistent(all,scheme):

    nos = all.groupby(scheme).count()
    nos = (nos["Strain"])
    no = int(scheme[-1])

    ind_lis = list(nos.T.index)

    # print(ind_lis)
    exist = {}
    exist2 = {}
    for pos in range(1,no):
        exist[pos] = {}
        exist2[pos] = {}
        for i in ind_lis:
            l = i.split("-")
            id = l[pos]
            up = l[pos-1]
            if id not in exist[pos]:
                exist[pos][id] = [up]
            else:
                exist[pos][id].append(up)
        for i in exist[pos]:
            idlis = exist[pos][i]
            nums1 = list(set(exist[pos][i]))
            nums = [(x,idlis.count(x)) for x in nums1]
            mx = max(nums, key=lambda item: item[1])

            # exist2[pos][i] = mx[0]
            if len(nums1) > 1:
                # exist2[pos][i] = mx[0]+"*"
                exist2[pos][i] = "/".join(nums1)
            # elif len(nums1) > 1 and len(nums1) <= 3 :
            #     exist2[pos][i] = "/".join(nums1)
            else:
                exist2[pos][i] = mx[0]

    # print(exist2[1])
    conv = dict()
    convr = {}
    ind_lis2 = list(nos.T.index)
    for i in ind_lis2:
        newi = change_recursive(exist2,i,1,no)
        convr[i] = newi
        if newi in conv:
            conv[newi].append(i)
        else:
            conv[newi] = [i]
    # print(convr)
    return convr

def leekit_country(leekit,schemes,outfolder):
    for scheme in schemes:

        scheme = "id_string_"+scheme

        print(leekit.columns)
        df2 = leekit.groupby(["Location (Corrected - Country)", scheme])["Location (Corrected - Country)"].count().unstack(scheme).fillna(0)
        print(df2.columns)
        df2 = df2[df2.sum().sort_values(ascending=False).index]
        print(df2.columns)
        df2 = df2.reindex(["Austria","Germany","Denmark","Netherlands","Luxembourg","Switzerland","France","Spain","Ireland","Poland","Czech Republic","Israel","Morocco","Thailand","Taiwan","New Zealand","Canada","United States","Argentina"])
        print(df2.columns)
        # get_inconsistent(df2)

        # print(list(df2.T.index))

        ###### with singletons separate plot

        # plt = df2.plot.bar(stacked=True,figsize=(10,8),width=0.8).get_figure()
        # # plt.tight_layout()
        # plt.savefig(scheme+"_leekit_country_distribution.pdf")
        # plt.show()

        #####################

        ###### with singletons together plot
        # df2.to_excel(writer, 'leekit_country_' + scheme)
        series = df2.sum(axis=0)
        mask = (series).gt(1)

        # print(series)
        tokeep = list(series[mask].index)
        tocombine = list(series[~mask].index)

        morethanone = df2[tokeep]

        singles = pd.DataFrame(columns=["Singletons"])

        singles["Singletons"] = df2[tocombine].sum(axis=1)

        final = pd.concat([morethanone,singles],axis=1)

        plt2 = final.plot.bar(stacked=True,figsize=(10,8),width=0.8).get_figure()
        # plt2.xlabel("Country")
        # plt2.ylabel("Strain count")
        # plt2.tight_layout()

        plt2.savefig(outfolder+scheme+"_leekit_country_distribution_no1.pdf")

        ##################
def all_source(total,schemes,outfolder):
    schemes+=["MGT92","MGT95","MGT910"]
    for scheme in schemes:
        if len(scheme) == 4:
            scheme = "id_string_"+scheme

        to_keep = ["clinical", "environmental/other"]
        total = total[total["met2"].isin(to_keep)]

        to_keep = ["United Kingdom: Scotland", "United Kingdom: England", "United Kingdom: Wales"]
        total = total[total["Location (Corrected - Country)"].isin(to_keep)]

        df2 = total.groupby(['met2', scheme])['met2'].count().unstack(scheme).fillna(0)

        df2 = df2[df2.sum().sort_values(ascending=False).index]

        # df2 = df2.reindex(["Austria","Germany","Denmark","Netherlands","Luxembourg","Switzerland","France","Spain","Ireland","Poland","Czech Republic","Israel","Morocco","Thailand","Taiwan","New Zealand","Canada","United States","Argentina"])

        # get_inconsistent(df2)

        # print(list(df2.T.index))

        ###### with singletons separate plot

        # plt = df2.plot.bar(stacked=True,figsize=(10,8),width=0.8).get_figure()
        # # plt.tight_layout()
        # plt.savefig(scheme+"_leekit_country_distribution.pdf")
        # plt.show()

        #####################

        ###### with singletons together plot
        # df2.to_excel(writer, 'leekit_country_' + scheme)
        series = df2.sum(axis=0)
        mask = (series).gt(1)

        # print(series)
        tokeep = list(series[mask].index)
        tocombine = list(series[~mask].index)

        morethanone = df2[tokeep]

        singles = pd.DataFrame(columns=["Singletons"])

        singles["Singletons"] = df2[tocombine].sum(axis=1)

        final = pd.concat([morethanone,singles],axis=1)

        plt2 = final.plot.bar(stacked=True,figsize=(10,8),width=0.8).get_figure()
        # plt2.xlabel("Country")
        # plt2.ylabel("Strain count")
        # plt2.tight_layout()

        plt2.savefig(outfolder+scheme+"_with_string_source_distribution_no1.pdf")

        ##################

def mather_UK_time(mather,schemes,outfolder):
    # print(mather)
    to_keep = ["United Kingdom: Scotland","United Kingdom: England","United Kingdom: Wales"]
    mather = mather[mather["Location (Corrected - Country)"].isin(to_keep)]
    # print(mather)
    for scheme in schemes:
        scheme = "id_string_" + scheme
        df2 = mather.groupby(['Collection Year', scheme])['Collection Year'].count().unstack(scheme).fillna(0)
        # print(df2)

        # df2 = df2.reindex(df2.T.sum().sort_values().T.index,axis=1)
        df2 = df2[df2.sum().sort_values(ascending=False).index]
        # df2.to_excel(writer, 'mather_time_' + scheme)
        series = df2.sum(axis=0)
        mask = (series).gt(1)

        # print(series)
        tokeep = list(series[mask].index)
        tocombine = list(series[~mask].index)

        morethanone = df2[tokeep]

        singles = pd.DataFrame(columns=["Singletons"])

        singles["Singletons"] = df2[tocombine].sum(axis=1)

        final = pd.concat([morethanone, singles], axis=1)

        plt2 = final.plot.area(stacked=True, figsize=(8, 6),lw=0,fontsize=12).get_figure()
        # plt2.xlabel("Year")
        # plt2.ylabel("Strain count")
        plt2.tight_layout()

        plt2.savefig(outfolder+scheme + "_mather_time_UK_distribution_no1.pdf")

def major_ST_over_time(all,schemes,outfolder,name,cc_or_st):
    df = pd.DataFrame()
    c = 0
    for scheme in schemes:
        scheme = "id_string_" + scheme
        # all[['Collection Year']].apply(pd.to_numeric, errors='ignore')

        df2 = all.groupby(['Collection Year', scheme])['Collection Year'].count().unstack(scheme).fillna(0)
        # print(df2)
        # df3 = list(df2.sum(axis=0).sort_values(ascending=False).T.index)
        maxst = list(df2.sum().sort_values(ascending=False).index)[0]
        df2 = df2.div(df2.sum(axis=1), axis=0).multiply(100)

        # print(df2)
        # sl(10)

        if c == 0:
            df = df2[maxst]
        else:
            df = pd.concat([df, df2[maxst]], axis=1)

        c+=1
        # df2 = df2.reindex(df3)
    # df = df.drop(["??"])

    # print(df)

    # df.to_csv("/Users/michaelpayne/Documents/UNSW/OneDrive - UNSW/HGT_Paper/figures/dt104_major_ST_over_time/3-major_cc_perc_over_time_rerun2.txt",sep="\t")

    # df.to_excel(writer, 'major_over_time')

    # df = df.drop(df.columns[[7,8]], axis=1)
    # print(df)

    # print(df)

    plot = df.plot.line(figsize=(10, 6))

    # ax.legend(loc=1)
    # plt.ylabel("Strain count")
    # plt.xticks(df.index)
    plot.set_yticks([0, 20, 40, 60, 80, 100])
    if name == "DT104":
        plot.set_xticks(range(1990, 2011, 2))
        plot.set_xlim(1990, 2018)
    elif name == "DT160":
        plot.set_xticks(range(1998, 2012, 2))
        plot.set_xlim(1998, 2012)
    plot.legend(loc=0)
    plot = plot.get_figure()
    plot.tight_layout()
    plot.savefig(outfolder+ cc_or_st + "_" +
        name +"_major_st_perc_over_time_rerun.pdf")

        # print(df2)

def add_singletones(df): ####creating for graph, just a large block for the single STs instead of lots of little blocks.
    df = df[df.sum().sort_values(ascending=False).index]
    series = df.sum(axis=0)
    mask = (series).gt(1)

    # print(series)
    tokeep = list(series[mask].index)
    tocombine = list(series[~mask].index)

    morethanone = df[tokeep]

    singles = pd.DataFrame(columns=["<3"])

    singles["<3"] = df[tocombine].sum(axis=1)

    final = pd.concat([morethanone, singles], axis=1)

    return final

def general_dt104_mgt_summary(dt104,schemes,outfolder,name,cc_or_st):
    df = pd.DataFrame()
    c=0
    for scheme in schemes:
        # scheme = "id_string_" + scheme

        df2 = dt104[scheme].fillna(0).value_counts().to_frame().T
        # print(df2)
        final = add_singletones(df2).T

        # print(df2)
        if c==0:
            df = final
        else:
            df = pd.merge(df,final,how="outer",left_index=True,right_index=True).fillna(0)
        c+=1
    # df.to_excel(writer, 'overall')

    # print(df)
    plt2 = df.T.plot.bar(stacked=True, figsize=(10, 10), width=0.8,legend=False,fontsize=12).get_figure()
    # plt2.xlabel("Country")
    # plt2.ylabel("Strain count")
    # plt2.rcParams.update({'font.size': 12})
    plt2.tight_layout()

    plt2.savefig(outfolder+name+"_"+cc_or_st+"_counts_nostring.pdf")

hgt = "/Users/michaelpayne/Documents/UNSW/OneDrive - UNSW/HGT_Paper/data/10k_run_initial_29-8-18/MGT_stm4_hgt.txt"
meta = "/Users/michaelpayne/Documents/UNSW/OneDrive - UNSW/HGT_Paper/data/old/10krun_final_21-8-18/10k_full_metadata.xlsx"
outfolder = "/Users/michaelpayne/Documents/UNSW/OneDrive - UNSW/HGT_Paper/data/10k_run_initial_29-8-18/graphs/"

annotated_HGT = ""#"/Users/michaelpayne/Documents/UNSW/OneDrive - UNSW/HGT_Paper/data/10k_run_initial_29-8-18/MGT_stm4_initial.xlsx"#"/Users/michaelpayne/Documents/UNSW/OneDrive - UNSW/HGT_Paper/data/10krun_initial_27-8-18/10k_initial.txt"

schemes = ["MGT"+str(x) for x in range(1,10)]
schemes2 = ["ac_MGT"+str(x) for x in range(2,10)]
print(schemes)

all = data_metadata_import_merge(hgt,meta,annotated_HGT)

all[['Collection Year']] = all[['Collection Year']].replace("nan", '0', regex=True)

all[['Collection Year']] = all[['Collection Year']].astype(int)

for i in range(len(schemes)):
    nscheme = "id_string_" + schemes[i]
    # print(nscheme)
    if i == 0:
        all[nscheme] = all[schemes[i]]
        # print(all[nscheme])
    else:
        all[nscheme] = all["id_string_"+schemes[i-1]] + "-" +all[schemes[i]]
        # print(all["id_string_"+schemes[i-1]])
        # print(all[schemes[i]])
        # print(all["id_string_"+schemes[i-1]] + "-" +all[schemes[i]])
        # sl(0.3)

for i in range(len(schemes2)):
    nscheme = "id_string_" + schemes2[i]
    if i == 0:
        all[nscheme] = all[schemes2[i]]
    else:
        all[nscheme] = all["id_string_"+schemes2[i-1]] + "-" + all[schemes2[i]]
print(all.columns)

# for i in range(len(schemes)):
#     nscheme = "id_string_" + schemes[i]
#     changedict = get_inconsistent(all,nscheme)
#     all[nscheme] = all[nscheme].replace(changedict)

# print(all["id_string_MGT5"])

# print(all.describe())
mather = all.loc[all['substudy']=="mathers"]
print(mather.shape)
leekit = all.loc[all['substudy']=="leekit"]
dt104 = all.loc[all['Initial_experiment']=="DT104"]
nz = all.loc[all['Initial_experiment']=="NZ"]
# writer = ExcelWriter('/Users/michaelpayne/Documents/UNSW/OneDrive - UNSW/HGT_Paper/figures/dt104_combined.xlsx')

leekit_country(leekit,schemes,outfolder)
all_source(mather,schemes,outfolder)
schemes = ["MGT"+str(x) for x in range(1,10)]
mather_UK_time(mather,schemes,outfolder)

# sns.set_palette(sns.color_palette("tab10", 9))
#
major_ST_over_time(dt104,schemes,outfolder,"DT104","st")
major_ST_over_time(nz,schemes,outfolder,"DT160","st")
general_dt104_mgt_summary(dt104,schemes,outfolder,"DT104","st")
general_dt104_mgt_summary(nz,schemes,outfolder,"DT160","st")
# writer.save()


from unittest.mock import Mock, patch
import pytest
import numpy as np

from shfl.model.linear_classifier_model import LinearClassifierModel

@pytest.fixture(name="wrapper_arguments")
def fixture_wrapper_arguments():
    """Returns the component necessary for wrapping a k-means clustering model."""
    n_features = 9
    classes = ["a", "b", "c"]

    return n_features, classes

@pytest.fixture(name="input_data")
def fixture_input_data(wrapper_arguments):
    """Returns a random labeled dataset."""
    n_features, classes = wrapper_arguments
    num_data = 50
    data = np.random.rand(num_data, n_features)
    labels = np.random.choice(classes, size=num_data)

    return data, labels

@pytest.mark.parametrize("classes, n_classes", [(["a", "b"], 1),
                                                (["a", "b", "c"], 3)])
@patch('shfl.model.linear_classifier_model.LogisticRegression')
def test_initialization_binary_classes(mock_classifier, classes, n_classes,
                                       wrapper_arguments):
    """Checks that the linear classifier correctly initializes.

    For a binary classification, the number of classes
    "n_classes" is equal to one. Instead, for a multi-class case,
    the number of classes "n_classes" is equal
    to the actual number of classes."""
    model = Mock()
    mock_classifier.return_value = model

    wrapped_model = LinearClassifierModel(n_features=wrapper_arguments[0],
                                          classes=classes)

    assert hasattr(wrapped_model, "_model")
    assert hasattr(wrapped_model, "_n_features")
    assert model.intercept_.shape[0] == n_classes
    assert model.coef_.shape == (n_classes, wrapper_arguments[0])
    assert np.array_equal(classes, model.classes_)

@pytest.mark.parametrize("n_features, classes", [(9.5, ['a', 'b', 'c']),
                                                 (-1, ['a', 'b', 'c']),
                                                 (9, ['b']),
                                                 (9, ['a', 'b', 'a'])])
@patch('shfl.model.linear_classifier_model.LogisticRegression')
def test_model_wrong_initialization(mock_classifier, n_features, classes):
    """Checks that the linear classification model throws an error if
    not initialized correctly.

    Namely, the number of features must be: integer, non-negative.
    The classes must be: more than one, not repeating."""
    mock_classifier.return_value = Mock()

    with pytest.raises(AssertionError):
        LinearClassifierModel(n_features, classes)

@patch('shfl.model.linear_classifier_model.LogisticRegression')
def test_train(mock_classifier, wrapper_arguments, input_data):
    """Checks that the linear classifier model trains correctly."""
    model = Mock()
    mock_classifier.return_value = model
    wrapped_model = LinearClassifierModel(*wrapper_arguments)

    wrapped_model.train(*input_data)

    model.fit.assert_called_once_with(*input_data)

@patch('shfl.model.linear_classifier_model.LogisticRegression')
def test_train_wrong_data(mock_classifier, wrapper_arguments, input_data, helpers):
    """Checks that the linear classifier model throws an error if wrong
    data are used as input."""
    mock_classifier.return_value = Mock()
    wrapped_model = LinearClassifierModel(*wrapper_arguments)

    helpers.check_wrong_data(wrapped_model, *input_data)

@patch('shfl.model.linear_classifier_model.LogisticRegression')
def test_train_wrong_data_single_feature(mock_classifier, wrapper_arguments, input_data):
    """Checks that the linear classifier model throws an error if wrong
    data are used as input.

    If data contains only one column, then the number of features must be 1."""
    mock_classifier.return_value = Mock()
    wrapped_model = LinearClassifierModel(*wrapper_arguments)
    data, labels = input_data
    wrong_data = np.random.rand(len(data))

    with pytest.raises(AssertionError):
        wrapped_model.train(wrong_data, labels)

@patch('shfl.model.linear_classifier_model.LogisticRegression')
def test_train_wrong_labels(mock_classifier, wrapper_arguments, input_data):
    """Checks that the linear classifier model throws an error if wrong
    labels are used as input."""
    mock_classifier.return_value = Mock()
    wrapped_model = LinearClassifierModel(*wrapper_arguments)
    data, labels = input_data
    wrong_labels = labels
    wrong_labels[0] = "not_initialized_class"

    with pytest.raises(AssertionError):
        wrapped_model.train(data, wrong_labels)

@patch('shfl.model.linear_classifier_model.LogisticRegression')
def test_predict(mock_classifier, wrapper_arguments, input_data):
    """Checks that the linear classifier model predicts correctly."""
    data, labels = input_data
    model = Mock()
    true_prediction = np.random.choice(labels, size=len(data))
    model.predict.return_value = true_prediction
    mock_classifier.return_value = model
    wrapped_model = LinearClassifierModel(*wrapper_arguments)

    output_prediction = wrapped_model.predict(data)

    model.predict.assert_called_once_with(data)
    np.testing.assert_array_equal(output_prediction, true_prediction)

@patch('shfl.model.linear_classifier_model.metrics')
@patch('shfl.model.linear_classifier_model.LogisticRegression')
def test_evaluate(mock_classifier, mock_metrics, wrapper_arguments, input_data):
    """Checks that the linear classifier model evaluates correctly."""
    data, labels = input_data
    model = Mock()
    mock_classifier.return_value = model
    wrapped_model = LinearClassifierModel(*wrapper_arguments)
    wrapped_model.predict = Mock()
    true_prediction = np.random.choice(labels, size=len(data))
    wrapped_model.predict.return_value = true_prediction
    mock_metrics.balanced_accuracy_score.return_value = 0.5
    mock_metrics.cohen_kappa_score.return_value = 0.7

    balanced_accuracy_score, cohen_kappa_score = wrapped_model.evaluate(data, labels)

    wrapped_model.predict.assert_called_once_with(data)
    mock_metrics.balanced_accuracy_score.assert_called_once_with(labels, true_prediction)
    mock_metrics.cohen_kappa_score.assert_called_once_with(labels, true_prediction)
    assert balanced_accuracy_score == 0.5
    assert cohen_kappa_score == 0.7

@patch('shfl.model.linear_classifier_model.LogisticRegression')
def test_evaluate_wrong_labels(mock_classifier, wrapper_arguments, input_data):
    """Checks that the linear classifier model throws an error if wrong
    labels are used as input."""
    mock_classifier.return_value = Mock()
    wrapped_model = LinearClassifierModel(*wrapper_arguments)
    data, labels = input_data
    wrong_labels = labels
    wrong_labels[0] = "not_initialized_class"

    with pytest.raises(AssertionError):
        wrapped_model.evaluate(data, wrong_labels)

@patch('shfl.model.linear_classifier_model.metrics')
@patch('shfl.model.linear_classifier_model.LogisticRegression')
def test_performance(mock_classifier, mock_metrics, wrapper_arguments, input_data):
    """Checks that the linear classifier model calls performance correctly."""
    data, labels = input_data
    model = Mock()
    mock_classifier.return_value = model
    wrapped_model = LinearClassifierModel(*wrapper_arguments)
    wrapped_model.predict = Mock()
    true_prediction = np.random.choice(labels, size=len(data))
    wrapped_model.predict.return_value = true_prediction
    mock_metrics.balanced_accuracy_score.return_value = 0.5

    balanced_accuracy_score = wrapped_model.performance(data, labels)

    wrapped_model.predict.assert_called_once_with(data)
    assert balanced_accuracy_score == 0.5

@patch('shfl.model.linear_classifier_model.LogisticRegression')
def test_get_model_params(mock_classifier, wrapper_arguments):
    """Checks that the linear classifier gets the model's parameters correctly."""
    model = Mock()
    mock_classifier.return_value = model
    wrapped_model = LinearClassifierModel(*wrapper_arguments)

    output_params = wrapped_model.get_model_params()

    np.testing.assert_array_equal(model.intercept_, output_params[0])
    np.testing.assert_array_equal(model.coef_, output_params[1])

@patch('shfl.model.linear_classifier_model.LogisticRegression')
def test_set_model_params(mock_classifier, wrapper_arguments):
    """Checks that the linear classifier sets the model's parameters correctly."""
    n_features, classes = wrapper_arguments
    model = Mock()
    mock_classifier.return_value = model
    wrapped_model = LinearClassifierModel(n_features, classes)
    n_classes = len(classes)
    input_params = (np.random.rand(n_classes),
                    np.random.rand(n_classes, n_features))

    wrapped_model.set_model_params(input_params)

    np.testing.assert_array_equal(model.intercept_, input_params[0])
    np.testing.assert_array_equal(model.coef_, input_params[1])


"""Test .NET autoapi domain"""

from unittest import mock
from unittest.mock import patch

from autoapi.mappers import dotnet

class MockConfig:
    def __getattr__(self, key):
        attrs = {
            "autoapi_dirs": ["/tmp/autoapi/tmp"],
            "autoapi_root": "/tmp/autoapi/root",
        }
        return attrs.get(key, None)

class MockApplication:
    config = MockConfig()

    def warn(self, *args, **kwargs):
        pass

class TestDotNetSphinxMapper:
    def test_create_class(self):
        """Test .NET class instance creation helper"""
        dom = dotnet.DotNetSphinxMapper(MockApplication())

        def _create_class(data):
            return list(dom.create_class(data))[0]

        cls = _create_class({"id": "Foo.Bar", "type": "Namespace"})
        assert isinstance(cls, dotnet.DotNetNamespace)
        cls = _create_class({"id": "Foo.Bar", "type": "Class"})
        assert isinstance(cls, dotnet.DotNetClass)
        cls = _create_class({"id": "Foo.Bar", "type": "Property"})
        assert isinstance(cls, dotnet.DotNetProperty)
        cls = _create_class({"id": "Foo.Bar", "type": "Method"})
        assert isinstance(cls, dotnet.DotNetMethod)
        cls = _create_class({"id": "Foo.Bar", "type": "Enum"})
        assert isinstance(cls, dotnet.DotNetEnum)
        cls = _create_class({"id": "Foo.Bar", "type": "Constructor"})
        assert isinstance(cls, dotnet.DotNetConstructor)
        cls = _create_class({"id": "Foo.Bar", "type": "Struct"})
        assert isinstance(cls, dotnet.DotNetStruct)
        cls = _create_class({"id": "Foo.Bar", "type": "Interface"})
        assert isinstance(cls, dotnet.DotNetInterface)
        cls = _create_class({"id": "Foo.Bar", "type": "Delegate"})
        assert isinstance(cls, dotnet.DotNetDelegate)
        cls = _create_class({"id": "Foo.Bar", "type": "Field"})
        assert isinstance(cls, dotnet.DotNetField)
        cls = _create_class({"id": "Foo.Bar", "type": "Event"})
        assert isinstance(cls, dotnet.DotNetEvent)

    def test_create_class_with_children(self):
        dom = dotnet.DotNetSphinxMapper(MockApplication())

        def _create_class(data):
            return list(dom.create_class(data))[0]

        cls = _create_class(
            {
                "id": "Foo.Bar",
                "type": "Class",
                "items": [{"id": "Foo.Bar.Baz", "type": "Method"}],
            }
        )
        assert isinstance(cls, dotnet.DotNetClass)
        assert cls.item_map == {}

    @patch("subprocess.check_output", lambda foo: foo)
    def test_get_objects(self):
        """Test basic get objects"""
        objs = []

        def _mock_find(self, patterns, **kwargs):
            return {"items": ["foo", "bar"]}

        def _mock_read(self, path):
            return {
                "items": [
                    {"id": "Foo.Bar", "name": "Foo", "type": "property"},
                    {"id": "Foo.Bar2", "name": "Bar", "type": "property"},
                ],
                "id": "Foo.Bar",
                "type": "Class",
                "summary": path,
            }

        with patch("autoapi.mappers.dotnet.DotNetSphinxMapper.find_files", _mock_find):
            with patch(
                "autoapi.mappers.dotnet.DotNetSphinxMapper.read_file", _mock_read
            ):
                dom = dotnet.DotNetSphinxMapper(MockApplication())
                dom.load("", "", "")
                dom.map()
                objs = dom.objects
                assert len(objs) == 2
                assert objs["Foo.Bar"].id == "Foo.Bar"
                assert objs["Foo.Bar"].name == "Foo.Bar"
                assert objs["Foo.Bar2"].id == "Foo.Bar2"
                assert objs["Foo.Bar2"].name == "Foo.Bar2"

class TestDotNetPythonMapper:
    def test_xml_parse(self):
        """XML doc comment parsing"""
        ret = dotnet.DotNetPythonMapper.transform_doc_comments(
            'This is an example comment <see cref="FOO" />'
        )
        assert ret == "This is an example comment :any:`FOO`"

        ret = dotnet.DotNetPythonMapper.transform_doc_comments(
            'This is an example comment <see cref="!:FOO" />'
        )
        assert ret == "This is an example comment FOO"

        ret = dotnet.DotNetPythonMapper.transform_doc_comments(
            'This is an example comment <see cref="N:FOO">inner foo</see>'
        )
        assert ret == "This is an example comment :dn:ns:`FOO`"

        ret = dotnet.DotNetPythonMapper.transform_doc_comments(
            'Test <see cref="P:FOO" /> and <see cref="E:BAR">Blah</see>'
        )
        assert ret == "Test :dn:prop:`FOO` and :dn:event:`BAR`"

        ret = dotnet.DotNetPythonMapper.transform_doc_comments(
            'This is an example comment <paramref name="FOO" />'
        )
        assert ret == "This is an example comment ``FOO``"

        ret = dotnet.DotNetPythonMapper.transform_doc_comments(
            'This is an example comment <typeparamref name="FOO" />'
        )
        assert ret == "This is an example comment ``FOO``"

        ret = dotnet.DotNetPythonMapper.transform_doc_comments(
            'With surrounding characters s<see cref="FOO" />s'
        )
        assert ret == r"With surrounding characters s :any:`FOO`\s"

        ret = dotnet.DotNetPythonMapper.transform_doc_comments(
            'With surrounding characters s<paramref name="FOO" />s'
        )
        assert ret == r"With surrounding characters s ``FOO``\s"

    def test_xml_transform_escape(self):
        """XML transform escaping"""
        ret = dotnet.DotNetPythonMapper.transform_doc_comments(
            'Foo <see cref="Foo`1" /> Bar'
        )
        assert ret == "Foo :any:`Foo\\`1` Bar"

        ret = dotnet.DotNetPythonMapper.transform_doc_comments(
            'No space before<see cref="M:Foo`1" />or after'
        )
        assert ret == "No space before :dn:meth:`Foo\\`1`\\or after"

    def test_parsing_obj(self):
        """Parse out object, test for transforms, etc"""
        obj = {
            "uid": "Foo`1",
            "name": "Foo<TUser>",
            "summary": 'Test parsing <see cref="Bar" />',
            "syntax": {
                "parameters": [
                    {
                        "id": "a",
                        "type": "{TUser}",
                        "description": 'Test <see cref="TUser" />',
                    }
                ],
                "return": {
                    "type": "Bar",
                    "description": (
                        'Test references <see cref="Bar" /> '
                        'and paramrefs <paramref name="a" />'
                    ),
                },
            },
        }
        mapped = dotnet.DotNetPythonMapper(obj, app=mock.MagicMock(), jinja_env=None)
        expected = {"name": "a", "type": "{TUser}", "desc": "Test :any:`TUser`"}
        assert mapped.parameters[0] == expected
        assert (
            mapped.returns["description"]
            == "Test references :any:`Bar` and paramrefs ``a``"
        )


#!/usr/bin/env python3
from tkinter import *
from tkinter import messagebox
import configparser
import xml.etree.ElementTree as ET
import grequests
import requests
import grequests
import xmltodict

# main program ################################################################
def main(*args):
    # barcode
    barcode = gui.get_barcode()
    if barcode == "":
        gui.msgbox(barcode, "Bad barcode")
        return
    gui.clear_barcode()

    # get item record
    url = "https://api-na.hosted.exlibrisgroup.com/almaws/v1/items?item_barcode="+barcode+"&apikey="+apikey
    r = requests.get(url)

    # check for invalid api key
    if r.text == "Invalid API Key":
        gui.msgbox(barcode, "Invalid API Key")
        return

    # check for errors
    errors_exist = check_errors_200(r)
    if errors_exist[0] == True:
        error = errors_exist[1]
        gui.msgbox(barcode, error)
        return

    # get item values
    item_xml    = r.text
    item       = ET.fromstring(item_xml)
    title      = item.find('bib_data/title').text[:50]
    mms_id     = item.find('bib_data/mms_id').text
    holding_id = item.find('holding_data/holding_id').text
    item_pid   = item.find('item_data/pid').text
    desc       = item.find('item_data/description').text

    if desc == None:
        desc = ""

    # other records
    urls = [
        "https://api-na.hosted.exlibrisgroup.com/almaws/v1/bibs/"+mms_id+"?apikey="+apikey,
        "https://api-na.hosted.exlibrisgroup.com/almaws/v1/bibs/"+mms_id+"/holdings?apikey="+apikey,
        "https://api-na.hosted.exlibrisgroup.com/almaws/v1/bibs/"+mms_id+"/holdings/"+holding_id+"/items?limit=10&offset=0&apikey="+apikey,
    ]

    r = getXML(urls)
    bib_xml         = r[0].text
    holdings_xml    = r[1].text
    other_items_xml = r[2].text

    # check for multiple holdings
    holdings = ET.fromstring(holdings_xml)
    h_dict   = holdings.attrib
    holdings_count = int(h_dict['total_record_count'])

    # check for other items
    other_items    = ET.fromstring(other_items_xml)
    item_dict      = other_items.attrib
    items_count = int(item_dict['total_record_count'])

    # check if last item and holding on record
    if last_item_check == "active":
        if holdings_count == 1 and items_count == 1:
           gui.msgbox(title, "LAST ITEM ON RECORD")
           return

    # add statistics note to item
    if add_item_note == "active":
        item_stat_note = item.find('item_data/'+item_note_field)
        item_stat_note.text = item_note

        # make final changes to item
        item_final = ET.tostring(item, encoding="unicode", method="xml")
        url = "https://api-na.hosted.exlibrisgroup.com/almaws/v1/bibs/"+mms_id+"/holdings/"+holding_id+"/items/"+item_pid+"?apikey="+apikey
        r = putXML(url, item_final)

        # check for errors
        errors_exist = check_errors_200(r)
        if errors_exist[0] == True:
            error = errors_exist[1]
            gui.msgbox(title, error)
            return

    # withdraw item and holdings
    if wd_item == "active":
        url     = "https://api-na.hosted.exlibrisgroup.com/almaws/v1/bibs/"+mms_id+"/holdings/"+holding_id+"/items/"+item_pid+"?override=false&holdings=retain&apikey="+apikey
        headers = {'Content-Type': 'application/xml', 'charset':'UTF-8'}
        r = deleteXML(url)

        # check for errors
        errors_exist = check_errors_204(r)
        if errors_exist[0] == True:
            error = errors_exist[1]
            gui.msgbox(title, error)
            return

    # finish
    gui.update_status_success(title+" ("+str(desc)+")")

# functions ###################################################################
def getXML(urls):
    rs = (grequests.get(u) for u in urls)
    r = grequests.map(rs)
    return r

def check_errors_200(r):
    if r.status_code != 200:
        errors = xmltodict.parse(r.text)
        error = errors['web_service_result']['errorList']['error']['errorMessage']
        return True, error
    else:
        return False, "OK"

def check_errors_204(r):
    if r.status_code != 204:
        errors = xmltodict.parse(r.text)
        error = errors['web_service_result']['errorList']['error']['errorMessage']
        return True, error
    else:
        return False, "OK"

def putXML(url, xml):
    headers = {'Content-Type': 'application/xml', 'charset':'UTF-8'}
    r = requests.put(url, data=xml.encode('utf-8'), headers=headers)
    return r

def deleteXML(url):
    headers = {'Content-Type': 'application/xml', 'charset':'UTF-8'}
    r = requests.delete(url, headers=headers)
    return r

# configurations ##############################################################
config = configparser.ConfigParser()
config.read('config.ini')

apikey                         = config['misc']['apikey']
version                        = config['misc']['version']

last_item_check                = config['checks']['last_item']

item_note_field                = config['stats']['item_note_field']
item_note                      = config['stats']['item_note']

add_item_note                  = config['operations']['add_item_note']
wd_item                        = config['operations']['wd_item']

# gui #########################################################################
class gui:
    def __init__(self, master):
        self.master = master
        master.title("Item-Be-Gone "+version)
        master.resizable(0, 0)
        master.minsize(width=600, height=100)
        master.iconbitmap("./images/logo_small.ico")

        logo = PhotoImage(file="./images/logo_large.png")
        self.logo = Label(image=logo)
        self.logo.image = logo
        self.logo.pack()

        self.status_title = Label(height=1, text="Scan barcode to begin.", font="Consolas 12 italic")
        self.status_title.pack(fill="both", side="top")

        self.status_wd = Label(height=1, text="READY", font="Consolas 12 bold", fg="green")
        self.status_wd.pack(fill="both", side="top")

        self.barcode_entry_field = Entry(font="Consolas 16")
        self.barcode_entry_field.focus()
        self.barcode_entry_field.bind('<Key-Return>', main)
        self.barcode_entry_field.pack(fill="both", side="top")

        self.scan_button = Button(text="SCAN", font="Arial 16", command=main)
        self.scan_button.pack(fill="both", side="top")

    def msgbox(self, title, msg):
        messagebox.showerror("Attention", msg)
        self.update_status_failure(title, msg)

    def get_barcode(self):
        barcode = self.barcode_entry_field.get()
        barcode = barcode.replace(" ", "")
        return barcode

    def clear_barcode(self):
        self.barcode_entry_field.delete(0, END)
        self.status_title.config(text="")
        self.status_wd.config(text="")

    def update_status_success(self, title):
        self.status_title.config(text=title)
        self.status_wd.config(text="SUCCESSFULLY WD", fg="green")

    def update_status_failure(self, title, msg):
        self.status_title.config(text=title)
        self.status_wd.config(text=msg, fg="red")

root = Tk()
gui = gui(root)
root.mainloop()


#1 to cal the area of circle

def area(a):
    a=3.14*a*a
    return a
x=int(input("enter radius:"))
print("area of circle is:%s"%area(x))

#2

def perfect(n):
    sum=0
    for i in range (1,n):
        if(n%i==0):
            sum=sum+i
    if(sum==n):
     print("true")
    else:
            print("false")
perfect(2)

#3 multiplication table of 12 using recursion
i=1
def table(n,i):
    print(n*i)
    i=i+1
    if(i<=10):
         table(n,i)
table(12,i)

#4write a function to cal power of a nuber raised to other(a^b)using recursion
base = int(input("enter base:"))
exp = int(input("enter exponential value:"))
def power(base,exp):
    if(exp==1):
        return(base)
    if(exp!=1):
        return(base*power(base,exp-1))
print("result:",power(base,exp))

#5 write a function to find the factorial of a number but also store the factorial in dictionary
n=int(input("enter nuber"))
def factorial(n):
   if (n == 1):
       return 1
   else:
       return (n*factorial(n-1))
d={}
d={n:factorial(n)}
print(d)


import os

from jina.logging.base import get_logger
from tests import JinaTestCase

class MyTestCase(JinaTestCase):

    def test_logging_message(self):
        os.environ['JINA_LOG_VERBOSITY'] = 'success'
        logger = get_logger('test_logger')
        logger.debug('this is test debug message')
        logger.info('this is test info message')
        logger.success('this is test success message')
        logger.warning('this is test warning message')
        logger.error('this is test error message')
        logger.critical('this is test critical message')


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

import os
import io
from rest_framework import generics
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from intranet.apps.search.views import get_search_results
from .models import User, Class, Grade
from .serializers import UserSerializer, ClassSerializer, StudentSerializer, CounselorTeacherSerializer
from .renderers import JPEGRenderer
from intranet import settings

class ProfileDetail(generics.RetrieveAPIView):
    """API endpoint that retrieves an Ion profile

    /api/profile: retrieve your profile
    /api/profile/<pk>: retrieve the profile of the user with id <pk>
    """
    serializer_class = UserSerializer
    permission_classes = (IsAuthenticated,)

    def retrieve(self, request, *args, **kwargs):
        if 'pk' in kwargs:
            user = User.objects.get(pk=kwargs['pk'])
        else:
            user = request.user

        serializer = self.get_serializer(user)
        data = serializer.data
        return Response(data)

class ProfilePictureDetail(generics.RetrieveAPIView):
    """API endpoint that retrieves an Ion profile picture

    /api/profile/<pk>/picture: retrieve default profile picture
    /api/profile/<pk>/picture/<photo_year>: retrieve profile picture for year <photo_year>
    """
    serializer_class = UserSerializer
    permission_classes = (IsAuthenticated,)
    renderer_classes = (JPEGRenderer,)

    def retrieve(self, request, *args, **kwargs):
        if 'pk' in kwargs:
            user = User.objects.get(pk=kwargs['pk'])
        else:
            user = request.user

        binary = None
        if 'photo_year' in kwargs:
            photo_year = kwargs['photo_year']
            if photo_year in Grade.names:
                binary = user.photo_binary(photo_year)
        else:
            binary = user.default_photo()
        if not binary:
            default_image_path = os.path.join(settings.PROJECT_ROOT, "static/img/default_profile_pic.png")
            binary = io.open(default_image_path, mode="rb").read()

        response = Response(binary, content_type='image/jpeg')
        return response

class ClassDetail(generics.RetrieveAPIView):
    """API endpoint that retrieves details of a TJHSST class
    """
    serializer_class = ClassSerializer
    permission_classes = (IsAuthenticated,)

    def retrieve(self, request, *args, **kwargs):
        cl = Class(id=kwargs['pk'])

        serializer = self.get_serializer(cl)
        return Response(serializer.data)

class Search(generics.RetrieveAPIView):
    """API endpoint that retrieves the results of a search for Ion users

    Paginated using ?page=<page>
    """

    permission_classes = (IsAuthenticated,)

    def retrieve(self, request, *args, **kwargs):
        query = kwargs['query']
        user_ids = []
        query = query.replace("+", " ")
        query_error, results = get_search_results(query)
        for unserialized_user in results:
            user_ids.append(unserialized_user.id)

        queryset = User.objects.filter(pk__in=user_ids)
        users = self.paginate_queryset(queryset)

        response = []
        for user in users:
            if user.is_student:
                response.append(StudentSerializer(user, context={'request': request}).data)
            else:
                response.append(CounselorTeacherSerializer(user, context={'request': request}).data)

        return self.get_paginated_response(response)