# -----------------------------------------------------------------------------
#  (c) 2005 by Basler Vision Technologies
#  Section: Vision Components
#  Project: GenApiTest
#    Author:
#  $Header:
# -----------------------------------------------------------------------------

from genicam import *
import unittest
from genicamtestcase import GenicamTestCase
from testport import CTestPort, cast_data, cast_buffer, CStructTestPort
from callbackhelper import CallbackTestTarget

class EnumerationTestSuite(GenicamTestCase):
    FLOAT32_EPSILON = 1.19209e-07  # np.finfo(np.float32).eps
    FLOAT64_EPSILON = 2.22044604925e-16  # np.finfo(float).eps

    def test_ValueAccess(self):
        """[ GenApiTest@EnumerationTestSuite_TestValueAccess.xml|gxml

            <Enumeration Name="Enum">
                <EnumEntry Name="EnumValue1">
                    <Value>10</Value>
               </EnumEntry>
                <EnumEntry Name="EnumValue2">
                    <Value>20</Value>
               </EnumEntry>
                <pValue>Value</pValue>
            </Enumeration>

            <Integer Name="Value">
                <Value>10</Value>
            </Integer>

            <Enumeration Name="Enum2">
                <pIsLocked>Lock</pIsLocked>
                <EnumEntry Name="EnumValue1">
                    <Value>10</Value>
               </EnumEntry>
                <EnumEntry Name="EnumValue2">
                    <Value>20</Value>
               </EnumEntry>
                <EnumEntry Name="EnumValue3">
                    <pIsAvailable>False</pIsAvailable>
                    <Value>30</Value>
               </EnumEntry>
                <pValue>Value2</pValue>
            </Enumeration>

            <IntReg Name="Value2">
                <Address>0</Address>
                <Length>4</Length>
                <AccessMode>RW</AccessMode>
                <pPort>Port</pPort>
                <Sign>Signed</Sign>
                <Endianess>LittleEndian</Endianess>
            </IntReg>

            <Integer Name="False">
                <Value>0</Value>
            </Integer>

           <Integer Name="Lock">
               <Value>0</Value>
           </Integer>

            <Port Name="Port"/>
        """

        # LOG4CPP_NS::Category *pLogger = &CLog::GetLogger( "CppUnit.Performance" )

        Camera = CNodeMapRef()
        Camera._LoadXMLFromFile("GenApiTest", "EnumerationTestSuite_TestValueAccess")

        Enum = Camera.GetNode("Enum")
        self.assertEqual(intfIEnumeration, Enum.GetNode().GetPrincipalInterfaceType())

        Value = Camera.GetNode("Value")

        # happy path
        Enum.FromString("EnumValue1")
        self.assertEqual("EnumValue1", Enum.ToString())
        self.assertEqual(10, Value.GetValue())

        Enum.FromString("EnumValue2")
        self.assertEqual("EnumValue2", Enum.ToString())
        self.assertEqual(20, Value.GetValue())

        EnumEntry = Enum.GetCurrentEntry()
        print(EnumEntry)
        self.assertEqual("EnumValue2", EnumEntry.GetSymbolic())

        # Ahaem - this should not change over time :-)
        EnumEntry.GetNode().InvalidateNode()
        self.assertEqual(RO, EnumEntry.GetAccessMode())
        self.assertEqual(RO, EnumEntry.GetAccessMode())

        # value too small
        with self.assertRaises(InvalidArgumentException):   Enum.FromString("BlaBla")

        # GCLOGINFO( pLogger, "-------------------------------------------------")
        # GCLOGINFO( pLogger, "Setup : Enumeration <=> Integer")

        Value.GetNode().InvalidateNode()
        # TEST_BEGIN(1000)
        Enum.FromString("EnumValue1")
        # StopWatch.PauseBegin()
        Value.GetNode().InvalidateNode()
        # StopWatch.PauseEnd()
        # TEST_END( Enumeration::FromString )

        # now some tests with the other enum, connected to a real port
        Port = CTestPort()
        Port.CreateEntry(0x000, "int32_t", 10, RW, LittleEndian)
        Camera._Connect(Port, "Port")
        Enum2 = Camera.GetNode("Enum2")
        self.assertEqual(10, Enum2.GetIntValue())
        # modify the underlying value, not visible through the cache
        Value = 20
        Port.Write(0x00, cast_data("uint32_t", LittleEndian, Value))
        self.assertEqual(10, Enum2.GetIntValue())
        self.assertEqual("EnumValue1", Enum2.ToString())
        # but visible when bypassing the cache
        self.assertEqual(20, Enum2.GetIntValue(False, True))
        self.assertEqual("EnumValue2", Enum2.ToString(False, True))
        # now change it to point to the NA entry
        Value = 30
        Port.Write(0x00, cast_data("uint32_t", LittleEndian, Value))
        # and test without/with verification
        self.assertEqual(30, Enum2.GetIntValue(False, True))
        with self.assertRaises(AccessException):   Enum2.SetIntValue(30)
        self.assertEqual("EnumValue3", Enum2.ToString(False, True))
        with self.assertRaises(GenericException):
            Enum2.GetIntValue(True, True)
        with self.assertRaises(GenericException):
            Enum2.ToString(True, True)

    def test_EnumEntry(self):
        # (one of the Enumerations is a terminal node, the other not)
        """[ GenApiTest@EnumerationTestSuite_TestEnumEntry.xml|gxml

            <Enumeration Name="Value">
                <EnumEntry Name="MyEnumEntry0">
                    <Value>0</Value>
                </EnumEntry>
                <EnumEntry Name="MyEnumEntry1">
                    <Value>1</Value>
                </EnumEntry>
                <EnumEntry Name="MyEnumEntry2">
                    <Value>2</Value>
                </EnumEntry>
                <EnumEntry Name="MyEnumEntry3">
                    <pIsAvailable>EntryAvailable</pIsAvailable>
                    <Value>3</Value>
                </EnumEntry>
                <EnumEntry Name="MyEnumEntry4">
                    <pIsImplemented>EntryImplemented</pIsImplemented>
                    <Value>4</Value>
                </EnumEntry>
                <pValue>Value2</pValue>
            </Enumeration>

            <Integer Name="EntryAvailable">
                <Value>0</Value>
            </Integer>

            <Integer Name="EntryImplemented">
                <Value>0</Value>
            </Integer>

            <Integer Name="Value2">
                <Value>10</Value>
            </Integer>

            <Enumeration Name="OtherValue">
                <EnumEntry Name="MyOtherEnumEntry0">
                    <Value>0</Value>
                </EnumEntry>
                <EnumEntry Name="MyOtherEnumEntry1">
                    <Value>1</Value>
                </EnumEntry>
                <Value>0</Value>
            </Enumeration>

        """

        Camera = CNodeMapRef()
        Camera._LoadXMLFromFile("GenApiTest", "EnumerationTestSuite_TestEnumEntry")

        featureNode = Camera.GetNode("Value")
        Feature = featureNode
        if (Feature):
            # IEnumeration* pEnumeration =  dynamic_cast<IEnumeration*>(featureNode)
            # if (pEnumeration  not = NULL)
            # {
            #    gcstring_vector symbolics
            #    pEnumeration.GetSymbolics(symbolics)
            #    int i=0
            #    self.assertEqual( (int)symbolics.size(), 3 )
            #    self.assertEqual( gcstring("MyEnumEntry0"), symbolics[i++] )
            #    self.assertEqual( gcstring("MyEnumEntry1"), symbolics[i++] )
            #    self.assertEqual( gcstring("MyEnumEntry2"), symbolics[i++] )
            # }
            pass

        Value = Camera.GetNode("Value")

        Value.FromString("MyEnumEntry1")
        gstr = "MyEnumEntry1"
        self.assertEqual(gstr, Value.ToString())

        Value.FromString("MyEnumEntry2")
        gstr = "MyEnumEntry2"
        self.assertEqual(gstr, Value.ToString())

        Value.FromString("MyEnumEntry0")
        gstr = "MyEnumEntry0"
        self.assertEqual(gstr, Value.ToString())

        MyEntry = Value.GetEntryByName("MyEnumEntry1")
        #    self.assertEqual( (gcstring)"1", MyEntry.ToString(MyEntry.GetValue()) ) # *JS* removed warning
        self.assertEqual("1", MyEntry.ToString(MyEntry.GetValue() != 0))
        #    gcstring str = MyEntry.ToString( MyEntry.GetValue() ) # *JS* removed warning
        Str = MyEntry.ToString(MyEntry.GetValue() != 0)
        print(Str, type(Str))
        # entries are not writeable
        with self.assertRaises(GenericException):
            MyEntry.FromString(Str)

        gstr = MyEntry.GetSymbolic()
        self.assertEqual("MyEnumEntry1", gstr)

        # CEnumEntryRef refEnumEntry
        # self.assertTrue_NO_THROW(refEnumEntry.SetReference( Value ) )
        # with self.assertRaises( refEnumEntry.GetSymbolic()):  AccessException
        # with self.assertRaises( refEnumEntry.GetValue()):  AccessException
        # self.assertTrue_NO_THROW( refEnumEntry.SetReference( MyEntry ) )
        # self.assertEqual( (gcstring)"MyEnumEntry1", refEnumEntry.GetSymbolic())
        # self.assertEqual( 1,refEnumEntry.GetValue())
        # self.assertEqual (RO, refEnumEntry.GetAccessMode())

        # now do some additional tests with the terminal node
        Enum = Camera.GetNode("OtherValue")
        Enum.SetIntValue(1)
        self.assertEqual(1, Enum.GetIntValue())
        Enum.GetIntValue(True)

        with self.assertRaises(InvalidArgumentException):
            Enum.SetIntValue(100)
        # note that the Verify=False does not disable the checking against valid enum values...
        with self.assertRaises(InvalidArgumentException):
            Enum.SetIntValue(100, False)

        # what if value points to a NI entry?
        IntVal = Camera.GetNode("Value2")
        IntVal.SetValue(3)  # this entry is NA
        with self.assertRaises(AccessException):
            Value.ToString(True)
        with self.assertRaises(AccessException):
            Value.FromString("MyEnumEntry4")

    def test_EnumFalseEntry(self):
        """[ GenApiTest@EnumerationTestSuite_TestEnumFalseEntry.xml|gxml
            <Enumeration Name="NoValue">
                <EnumEntry Name="MyEnumEntry1">
                <Value>3</Value>
                </EnumEntry>
                <pValue>Value2</pValue>
            </Enumeration>

            <Integer Name="Value2">
                <Value>10</Value>
            </Integer>

        """

        Camera = CNodeMapRef()
        Camera._LoadXMLFromFile("GenApiTest", "EnumerationTestSuite_TestEnumFalseEntry")

        # gcstring_vector symbolics
        FalsePtr = Camera.GetNode("NoValue")
        self.assertEqual(RW, FalsePtr.GetAccessMode())
        symbolics = FalsePtr.GetSymbolics()
        with self.assertRaises(InvalidArgumentException):   FalsePtr.ToString()
        FalsePtr.SetIntValue(3)
        self.assertEqual("MyEnumEntry1", FalsePtr.ToString())

    def test_EnumRef(self):
        """[ GenApiTest@EnumerationTestSuite_TestEnumRef.xml|gxml
            <Enumeration Name="PixelFormat">
              <EnumEntry Name="Mono8">
                 <Value>0</Value>
              </EnumEntry>
              <EnumEntry Name="Mono16">
                 <Value>1</Value>
              </EnumEntry>
              <EnumEntry Name="RGB24">
                 <Value>2</Value>
              </EnumEntry>
              <pValue>Value</pValue>
            </Enumeration>

            <Integer Name="Value">
                <Value>10</Value>
            </Integer>

        """

        Camera = CNodeMapRef()
        Camera._LoadXMLFromFile("GenApiTest", "EnumerationTestSuite_TestEnumRef")

        Port = CTestPort()
        Port.CreateEntry(0x0104, "uint32_t", 1024, RW, LittleEndian)

        # connect the node map to the port
        Camera._Connect(Port, "Port")

        Value = Camera.GetNode("PixelFormat")

        # not valid pointer for testing False cases
        # CEnumerationTRef<int> refFalse

        # CEnumerationTRef<int> refEnumT
        # self.assertTrue_NO_THROW( refEnumT.SetReference( Value ) )
        # self.assertTrue_NO_THROW( refEnumT.SetEnumReference(0, "PixelFormat" ) )

        # with self.assertRaises( refFalse.IsValueCacheValid()):  AccessException
        # self.assertTrue(  not refEnumT.IsValueCacheValid() )

        # Value = refEnumT.GetNode()
        # with self.assertRaises( refFalse.GetNode()):  AccessException

        # CEnumerationTRef<EAccessMode> refEnumAcc
        # EAccessMode AMode = RW
        # self.assertTrue_NO_THROW( refEnumAcc.GetAccessMode())
        # self.assertTrue_NO_THROW( refEnumAcc.SetReference( Value ) )
        # self.assertEqual( AMode, refEnumAcc.GetAccessMode())

        # gcstring_vector symbolics
        # with self.assertRaises( refFalse.GetSymbolics(symbolics)):  AccessException
        # refEnumT.GetSymbolics(symbolics)
        # int i(0)
        # self.assertEqual( gcstring("Mono8"), symbolics[i++] )
        # self.assertEqual( gcstring("Mono16"), symbolics[i++] )
        # self.assertEqual( gcstring("RGB24"), symbolics[i++] )
        # self.assertEqual( size_t(i), symbolics.size() )

        # NodeList_t entries
        # i=0
        # gcstring str1 = "EnumEntry_PixelFormat_Mono8",
        #    str2 = "EnumEntry_PixelFormat_Mono16",
        #    str3 = "EnumEntry_PixelFormat_RGB24"
        # with self.assertRaises( refFalse.GetEntries(entries)):  AccessException
        # refEnumT.GetEntries(entries)
        # self.assertEqual( str1, entries[i++].GetName() )
        # self.assertEqual( str2, entries[i++].GetName() )
        # self.assertEqual( str3, entries[i++].GetName() )
        # self.assertEqual( size_t(i), entries.size() )

        """* AH: no longer allowed since Mantis #9 is fixed.
        Value.SetIntValue(1234)  # AH: now checked in test EnumerationTestSuite::TestInvalidValues()
        self.assertEqual(  1234LL,refEnumT.GetIntValue() )
        """

        # with self.assertRaises( refFalse.SetIntValue(5432)):  AccessException

        """* AH: no longer allowed since Mantis #9 is fixed
        refEnumT.SetIntValue(5432) # AH: now checked in test EnumerationTestSuite::TestInvalidValues()
        self.assertEqual(  5432LL,refEnumT.GetIntValue() )
        """

        # with self.assertRaises( refFalse.GetEntry(0)):   GenericException
        # with self.assertRaises( refFalse.GetCurrentEntry()):   GenericException
        # with self.assertRaises( refFalse.GetEntry((int)0), GenericException ) # falls into the EnumT version of GetEntry (EnumT=int):   above

        # IEnumEntry *MyEntry
        # with self.assertRaises( refFalse.GetEntryByName("RGB24")):  AccessException
        # MyEntry = refEnumT.GetEntryByName("RGB24")
        # self.assertTrue(MyEntry)
        # self.assertEqual((gcstring)"2", MyEntry.ToString())

        #    self.assertEqual(  10LL, refEnumT.GetIntValue(MyEntry.GetValue())) # *JS* removed warning
        # with self.assertRaises( refEnumT.GetIntValue(MyEntry.GetValue()  not = 0)):   OutOfRangeException
        #    with self.assertRaises( refFalse.GetIntValue(MyEntry.GetValue())):  AccessException  # *JS* removed warning
        # with self.assertRaises( refFalse.GetIntValue(MyEntry.GetValue()  not = 0)):  AccessException

        # with self.assertRaises( refEnumT.ToString(0)):   InvalidArgumentException
        # refEnumT.SetIntValue(1)
        # self.assertEqual((gcstring)"Mono16",refEnumT.ToString(0) )
        # self.assertEqual ((gcstring)"Mono16",refEnumT.GetCurrentEntry().GetSymbolic())
        # self.assertEqual ((gcstring)"Mono8",refEnumT.GetEntry(0).GetSymbolic())
        # self.assertEqual ((IEnumEntry*)NULL,refEnumT.GetEntry(234))
        # with self.assertRaises( refFalse.ToString(0)):  AccessException

        # refEnumT.FromString("Mono8") # ???
        # with self.assertRaises( refFalse.FromString("Mono8")):  AccessException

        # with self.assertRaises( refEnumT.GetValue()):  AccessException

        # refEnumT.SetNumEnums(3)
        #   undef max
        # with self.assertRaises( refEnumT.SetValue(int(MyEntry.GetValue() & numeric_limits<unsigned>::max() ))):  AccessException
        # with self.assertRaises( refFalse.SetValue(int(MyEntry.GetValue() & numeric_limits<unsigned>::max() ))):  AccessException

        # With the fix of Mantis 376, the following assertion would fail.
        #    self.assertEqual( 0, refEnumT.GetValue() )

        # Since no enum references are set, GetValue() must throw an exception
        # with self.assertRaises( refEnumT.GetValue()):   AccessException  # checks if Mantis 376 works

        # with self.assertRaises( refFalse.GetValue()):  AccessException

        # refEnumT.SetEnumReference(0, "Mono8")
        # refEnumT.SetEnumReference(1, "Mono16")
        # refEnumT.SetEnumReference(2, "RGB24")

        # this one does nothing (the call is ignored), it is here just to complete the coverage
        # self.assertTrue_NO_THROW( refFalse.SetEnumReference(0, "FooBar") )

        # refEnumT.SetValue(1)
        # self.assertEqual( 1, refEnumT.GetValue() )
        # self.assertEqual (True, refEnumT.IsValueCacheValid())

        # refEnumT = "Mono16"
        # self.assertEqual( 1, refEnumT.GetIntValue() )
        # with self.assertRaises( refFalse = "Mono16"):   AccessException

        # refEnumT = gcstring("RGB24")
        # self.assertEqual( 2, refEnumT.GetIntValue() )
        # with self.assertRaises( refFalse = gcstring("Mono16")):   AccessException

        # self.assertEqual( gcstring("RGB24"), *refEnumT )
        # with self.assertRaises( *refFalse):   AccessException

        # self.assertEqual( 2, refEnumT() )
        # with self.assertRaises( refFalse()):  AccessException

        Camera.GetNode("PixelFormat")

    def test_DisplayName(self):
        """[ GenApiTest@EnumerationTestSuite_TestDisplayName.xml|gxml
            <Enumeration Name="Enumeration">
                <EnumEntry Name="EnumEntry0">
                    <Value>0</Value>
                </EnumEntry>
                <EnumEntry Name="EnumEntry1">
                    <Value>1</Value>
                    <Symbolic>Symbolic1</Symbolic>
                </EnumEntry>
                <EnumEntry Name="EnumEntry2">
                    <DisplayName>DisplayName2</DisplayName>
                    <Value>2</Value>
                </EnumEntry>
                <EnumEntry Name="EnumEntry3">
                    <DisplayName>DisplayName3</DisplayName>
                    <Value>3</Value>
                    <Symbolic>Symbolic3</Symbolic>
                </EnumEntry>
                <Value>0</Value>
            </Enumeration>

        """

        Camera = CNodeMapRef()
        Camera._LoadXMLFromFile("GenApiTest", "EnumerationTestSuite_TestDisplayName")

        Enumeration = Camera.GetNode("Enumeration")
        # IEnumeration* pEnumeration =  dynamic_cast<IEnumeration*>(ValueNode)

        # self.assertTrue(dynamic_cast<INode*>(Enumeration.GetEntryByName("EnumEntry0")))
        # self.assertEqual (gcstring("EnumEntry0"), (dynamic_cast<INode*>(Enumeration.GetEntryByName("EnumEntry0"))).GetDisplayName() )
        # self.assertEqual ((IEnumEntry*)NULL, Enumeration.GetEntryByName("EnumEntry1") )
        # self.assertEqual (gcstring("Symbolic1"), (dynamic_cast<INode*>(Enumeration.GetEntryByName("Symbolic1"))).GetDisplayName() )
        # self.assertEqual (gcstring("DisplayName2"), (dynamic_cast<INode*>(Enumeration.GetEntryByName("EnumEntry2"))).GetDisplayName() )
        # self.assertEqual ((IEnumEntry*)NULL, Enumeration.GetEntryByName("EnumEntry3") )
        # self.assertEqual (gcstring("DisplayName3"), (dynamic_cast<INode*>(Enumeration.GetEntryByName("Symbolic3"))).GetDisplayName() )

    def test_NumericValue(self):
        # if(GenApiSchemaVersion == v1_0)
        #    return

        # create and initialize node map
        """[ GenApiTest@EnumerationTestSuite_TestNumericValue.xml|gxml

            <Integer Name="IntFromEnum">
                <pValue>Enum</pValue>
            </Integer>

            <Enumeration Name="Enum">
                <EnumEntry Name="EnumValue1">
                    <Value>10</Value>
                    <NumericValue>1.5</NumericValue>
               </EnumEntry>
                <EnumEntry Name="EnumValue2">
                    <Value>20</Value>
               </EnumEntry>
                <EnumEntry Name="EnumValue3">
                    <Value>30</Value>
                    <NumericValue>1.7</NumericValue>
               </EnumEntry>
                <Value>10</Value>
            </Enumeration>

        """

        Camera = CNodeMapRef()
        Camera._LoadXMLFromFile("GenApiTest", "EnumerationTestSuite_TestNumericValue")

        Enum = Camera.GetNode("Enum")
        EnumEntry1 = Enum.GetEntryByName("EnumValue1")
        EnumEntry2 = Enum.GetEntryByName("EnumValue2")
        IntFromEnum = Camera.GetNode("IntFromEnum")

        self.assertAlmostEqual(1.5, EnumEntry1.GetNumericValue(), delta=self.FLOAT64_EPSILON)
        self.assertAlmostEqual(20.0, EnumEntry2.GetNumericValue(), delta=self.FLOAT64_EPSILON)

        # the same through reference
        # CEnumEntryRef refEnumEntry1, refEnumEntry2
        # self.assertRaises (refEnumEntry1.GetNumericValue(), GenICam::AccessException)
        # self.assertTrue_NO_THROW(refEnumEntry1.SetReference( EnumEntry1 ) )
        # self.assertTrue_NO_THROW(refEnumEntry2.SetReference( EnumEntry2 ) )
        # self.assertAlmostEqual( 1.5, refEnumEntry1.GetNumericValue(), delta=self.FLOAT64_EPSILON )
        # self.assertAlmostEqual( 20.0, refEnumEntry2.GetNumericValue(), delta=self.FLOAT64_EPSILON )

        # try setting an enum through an integer
        IntFromEnum.SetValue(1)
        self.assertEqual("EnumValue1", Enum.ToString())
        IntFromEnum.SetValue(2)
        self.assertEqual("EnumValue3", Enum.ToString())
        IntFromEnum.SetValue(20)
        self.assertEqual("EnumValue2", Enum.ToString())

    # def TestAutoGain_Callback(INode *pNode)
    # {
    #    CValuePtr Value(pNode)
    #    Value.ToString()
    # }

    def test_AutoGain(self):
        # if(GenApiSchemaVersion == v1_0)
        #    return
        """============ type definitions for the register space defined below ========== """

        class EGainAuto:
            Off = 1
            Once = 2
            Continuous = 3

        """============ Setup the register space ========== """
        regs = [("Gain", "uint32_t", 0, RW, LittleEndian),
                ("GainAutoReg", "uint8_t", 0, RW, LittleEndian),
                ]

        GainAutoFeaturePort = CStructTestPort(regs)
        GainAutoFeaturePort.Gain = 42
        GainAutoFeaturePort.GainAutoReg = EGainAuto.Off

        """============ Setup the corresponding XML file ========== """

        # create and initialize node map
        """[ GenApiTest@EnumerationTestSuite_TestAutoGain.xml|gxml

            <IntReg Name="Gain">
                <pBlockPolling>GainPollingBlock</pBlockPolling>
                <Address>0</Address>
                <Length>4</Length>
                <AccessMode>RW</AccessMode>
                <pPort>Port</pPort>
                <PollingTime>1000</PollingTime>
                <Sign>Unsigned</Sign>
                <Endianess>LittleEndian</Endianess>
            </IntReg>

            <IntReg Name="GainAutoReg">
                <Address>4</Address>
                <Length>1</Length>
                <AccessMode>RW</AccessMode>
                <pPort>Port</pPort>
                <Sign>Unsigned</Sign>
                <Endianess>LittleEndian</Endianess>
            </IntReg>

            <Enumeration Name="GainAuto">
               <EnumEntry Name="Off">
                    <Value>1</Value>
               </EnumEntry>
               <EnumEntry Name="Once">
                    <Value>2</Value>
                    <IsSelfClearing>Yes</IsSelfClearing>
               </EnumEntry>
               <EnumEntry Name="Continuous">
                    <Value>3</Value>
               </EnumEntry>
               <pValue>GainAutoReg</pValue>
               <PollingTime>50</PollingTime>
            </Enumeration>

            <IntSwissKnife Name="GainPollingBlock">
                <pVariable Name="GainAuto">GainAuto</pVariable>
                <Formula> GainAuto=1 ? 1 : 0 </Formula>
            </IntSwissKnife>

            <Port Name="Port"/>

        """

        Camera = CNodeMapRef()
        Camera._LoadXMLFromFile("GenApiTest", "EnumerationTestSuite_TestAutoGain")
        Camera._Connect(GainAutoFeaturePort, "Port")

        """============ Get pointers and do basic checks ========== """

        Gain = Camera.GetNode("Gain")
        GainAuto = Camera.GetNode("GainAuto")

        self.assertEqual(42, Gain.GetValue(IgnoreCache=True))
        Gain.SetValue(4711)
        self.assertEqual(4711, Gain.GetValue())
        self.assertEqual(4711, GainAutoFeaturePort.Gain)

        self.assertEqual("Off", GainAuto.ToString())
        GainAuto.SetValue("Continuous")
        self.assertEqual("Continuous", GainAuto.ToString())
        self.assertEqual(EGainAuto.Continuous, (GainAutoFeaturePort.GainAutoReg))

        GainAutoOff = GainAuto.GetEntryByName("Off")
        GainAutoOnce = GainAuto.GetEntryByName("Once")

        self.assertEqual(False, GainAutoOff.IsSelfClearing())
        self.assertEqual(True, GainAutoOnce.IsSelfClearing())

        """============ Test basic auto-reset ========== """

        GainAutoCallback = CallbackTestTarget(GainAuto)

        # this callback will read the value
        # Register( GainAuto.GetNode(), TestAutoGain_Callback )

        # start one cycle of auto-gain
        GainAuto.SetValue("Once")
        self.assertEqual(EGainAuto.Once, (GainAutoFeaturePort.GainAutoReg))
        self.assertTrue(GainAutoCallback.HasFiredOnce())

        # poll while waiting for the auto-gain cycle to complete
        Camera._Poll(100)
        self.assertTrue(GainAutoCallback.HasFiredOnce())

        Camera._Poll(100)
        self.assertTrue(GainAutoCallback.HasFiredOnce())

        Camera._Poll(25)
        self.assertTrue(not GainAutoCallback.HasFiredOnce())
        Camera._Poll(25)
        self.assertTrue(GainAutoCallback.HasFiredOnce())

        # the camera signals we're ready
        GainAutoFeaturePort.GainAutoReg = EGainAuto.Off

        Camera._Poll(100)
        self.assertTrue(GainAutoCallback.HasFiredOnce())
        self.assertEqual("Off", GainAuto.ToString())

        Camera._Poll(100)
        self.assertTrue(GainAutoCallback.HasNotFired())

        """============ Test different use cases of auto-reset ========== """

        GainAuto.SetValue("Once")
        GainAutoCallback.Reset()
        GainAutoFeaturePort.GainAutoReg = EGainAuto.Off

        # "cleared" by setting another value
        GainAuto.SetValue("Continuous")
        self.assertTrue(GainAutoCallback.HasFiredOnce())

        #######

        GainAuto.SetValue("Once")
        GainAutoCallback.Reset()
        GainAutoFeaturePort.GainAutoReg = EGainAuto.Off

        # "cleared" by setting another value
        GainAuto.SetIntValue(EGainAuto.Continuous)
        self.assertTrue(GainAutoCallback.HasFiredOnce())

        #######

        GainAuto.SetValue("Once")
        GainAuto.GetIntValue()
        GainAutoCallback.Reset()
        GainAutoFeaturePort.GainAutoReg = EGainAuto.Off

        # "cleared" by getting the value
        GainAuto.GetIntValue()
        # but no callback, since it is a read
        self.assertTrue(GainAutoCallback.HasNotFired())
        # no callback since it is cleared already
        Camera._Poll(100)
        self.assertTrue(GainAutoCallback.HasNotFired())

        #######

        GainAuto.SetValue("Once")
        GainAutoCallback.Reset()
        GainAutoFeaturePort.GainAutoReg = EGainAuto.Off

        # "cleared" by getting the value
        GainAuto.ToString()
        # but no callback, since it is a read
        self.assertTrue(GainAutoCallback.HasNotFired())
        # no callback since it is cleared already
        Camera._Poll(100)
        self.assertTrue(GainAutoCallback.HasNotFired())

        """============ Test continuous ========== """
        GainAuto.SetValue("Continuous")

        GainAutoFeaturePort.Gain = 48
        GainCallback = CallbackTestTarget(Gain)
        Camera._Poll(100)
        self.assertTrue(GainCallback.HasNotFired())
        Camera._Poll(1000)
        self.assertTrue(GainCallback.HasFiredOnce())
        self.assertEqual(48, Gain.GetValue())

        """============ Test off ========== """

        GainAuto.SetValue("Off")
        GainCallback.Reset()

        # fill the cache and then change the register value
        self.assertEqual(48, Gain.GetValue())
        GainAutoFeaturePort.Gain = 49

        # now polling does not happen and the cache is not cleared
        Camera._Poll(2000)
        self.assertTrue(GainCallback.HasNotFired())
        # because the cache is enabled the old value is given
        self.assertEqual(48, Gain.GetValue())

        """============ Test caching, Continuous ========== """

        GainAuto.SetValue("Continuous")  # this clears the Gain cache
        GainAutoFeaturePort.Gain = 111
        self.assertEqual(111, Gain.GetValue())
        GainAutoFeaturePort.Gain = 222
        # Since there is no polling and Continuous is not self clearing anyway the cached value is
        # returned
        self.assertEqual(111, Gain.GetValue())

        """============ Test caching, Off ========== """
        GainAuto.SetValue("Off")  # this clears the Gain cache
        # this fills the cache
        self.assertEqual(222, Gain.GetValue())
        GainAutoFeaturePort.Gain = 333
        # value comes from cache
        self.assertEqual(222, Gain.GetValue())

        """============ Test caching, Once ========== """
        GainAuto.SetValue("Once")  # this clears the cache
        GainAutoFeaturePort.Gain = 444
        # this fills the cache
        self.assertEqual(444, Gain.GetValue())
        GainAutoFeaturePort.Gain = 555
        GainAutoFeaturePort.GainAutoReg = EGainAuto.Off
        # since Once is self clearing the value is read and Gain's cache is cleard
        self.assertEqual("Off", GainAuto.ToString())
        # this fills the cache
        self.assertEqual(555, Gain.GetValue())

        # once again without direct read of GainAuto
        GainAuto.SetValue("Once")  # this clears the Gain cache
        GainAutoFeaturePort.Gain = 666
        # this fills the cache
        self.assertEqual(666, Gain.GetValue())
        GainAutoFeaturePort.Gain = 777
        # since GainAuto is not read this goes unnotices
        GainAutoFeaturePort.GainAutoReg = EGainAuto.Off
        # value comes form cache
        self.assertEqual(666, Gain.GetValue())
        GainAutoFeaturePort.Gain = 888
        # value comes form cache
        self.assertEqual(666, Gain.GetValue())  # from cache

        """============ Test auto-reset, read before poll ========== """

        # start one cycle of auto-gain
        Gain.SetValue(123)
        self.assertEqual(123, Gain.GetValue())
        GainAutoCallback.Reset()
        GainCallback.Reset()
        GainAuto.SetValue("Once")
        self.assertEqual(EGainAuto.Once, (GainAutoFeaturePort.GainAutoReg))
        self.assertTrue(GainAutoCallback.HasFiredOnce())
        self.assertTrue(GainCallback.HasFiredOnce())
        self.assertEqual(123, Gain.GetValue())

        # the camera signals we're ready, get to know that through reading (before any poll)
        GainAutoFeaturePort.Gain = 234
        GainAutoFeaturePort.GainAutoReg = EGainAuto.Off
        self.assertEqual("Off", GainAuto.ToString())

        # polling does not fire any more
        Camera._Poll(1000)
        self.assertTrue(GainAutoCallback.HasNotFired())
        self.assertTrue(GainCallback.HasNotFired())

        # the callbacks do not come, but Gain value is still invalidated
        self.assertEqual(234, Gain.GetValue())

    def test_GetEntry(self):
        """[ GenApiTest@EnumerationTestSuite_TestGetEntry.xml|gxml

                <Enumeration Name="Enum">
                    <EnumEntry Name="EnumValue1">
                        <Value>10</Value>
                   </EnumEntry>
                    <EnumEntry Name="EnumValue2">
                        <Value>20</Value>
                   </EnumEntry>
                    <pValue>Value</pValue>
                </Enumeration>

                <Integer Name="Value">
                    <Value>10</Value>
                </Integer>

        """

        Camera = CNodeMapRef()
        Camera._LoadXMLFromFile("GenApiTest", "EnumerationTestSuite_TestGetEntry")

        Enum = Camera.GetNode("Enum")

        EnumEntry = Enum.GetEntry(20)
        self.assertEqual(20, EnumEntry.GetValue())

    def test_AccessMode(self):
        # create and initialize node map
        """[ GenApiTest@EnumerationTestSuite_TestAccessMode.xml|gxml

            <Enumeration Name="Enum">
                <EnumEntry Name="EnumEntry1">
                    <pIsImplemented>Toggle_I</pIsImplemented>
                    <pIsAvailable>Toggle_A</pIsAvailable>
                    <Value>10</Value>
                </EnumEntry>
                <EnumEntry Name="EnumEntry2">
                    <pIsImplemented>Toggle_I</pIsImplemented>
                    <pIsAvailable>Toggle_A</pIsAvailable>
                    <Value>20</Value>
                </EnumEntry>
                <Value>10</Value>
            </Enumeration>

            <Integer Name="Toggle_A">
               <Value>1</Value>
            </Integer>

            <Integer Name="Toggle_I">
               <Value>1</Value>
            </Integer>

        """

        Camera = CNodeMapRef()
        Camera._LoadXMLFromFile("GenApiTest", "EnumerationTestSuite_TestAccessMode")

        # Fetch node pointers
        Enum = Camera.GetNode("Enum")
        EnumEntry1 = Camera.GetNode("EnumEntry_Enum_EnumEntry1")
        EnumEntry2 = Camera.GetNode("EnumEntry_Enum_EnumEntry2")
        ToggleAvailabilty = Camera.GetNode("Toggle_A")
        ToggleImplementationAvailabilty = Camera.GetNode("Toggle_I")

        # What happens if both EnumEntries become not available?
        self.assertEqual(RW, Enum.GetAccessMode())
        ToggleAvailabilty.SetValue(0)
        self.assertEqual(NA, Enum.GetAccessMode())
        # Repeat the same test to see if correct access mode was cached
        self.assertEqual(NA, Enum.GetAccessMode())
        with self.assertRaises(GenericException):   Enum.GetIntValue()
        ToggleAvailabilty.SetValue(1)
        self.assertEqual(RW, Enum.GetAccessMode())

        # What happens if both EnumEntries become not implemented?
        self.assertEqual(RW, Enum.GetAccessMode())
        ToggleImplementationAvailabilty.SetValue(0)
        self.assertEqual(NI, Enum.GetAccessMode())
        ToggleImplementationAvailabilty.SetValue(1)
        self.assertEqual(RW, Enum.GetAccessMode())

        # Same questions but triggered using ImposeAccessMode
        self.assertEqual(RW, Enum.GetAccessMode())
        Enum.GetNode().ImposeAccessMode(RO)
        self.assertEqual(RO, Enum.GetAccessMode())
        EnumEntry1.GetNode().ImposeAccessMode(NA)
        self.assertEqual(RO, Enum.GetAccessMode())
        EnumEntry2.GetNode().ImposeAccessMode(NA)
        self.assertEqual(NA, Enum.GetAccessMode())
        EnumEntry1.GetNode().ImposeAccessMode(NI)
        self.assertEqual(NA, Enum.GetAccessMode())
        EnumEntry2.GetNode().ImposeAccessMode(NI)
        self.assertEqual(NI, Enum.GetAccessMode())

    def test_Ticket778(self):
        # create and initialize node map
        """[ GenApiTest@EnumerationTestSuite_TestTicket778.xml|gxml

            <Enumeration Name="EnumA">
                <EnumEntry Name="EnumValue1">
                    <pIsAvailable>AvailableA</pIsAvailable>
                    <Value>10</Value>
                </EnumEntry>
                <EnumEntry Name="EnumValue2">
                    <Value>20</Value>
                </EnumEntry>
                <Value>10</Value>
            </Enumeration>

            <Enumeration Name="EnumB">
                <EnumEntry Name="EnumValue1">
                    <pIsAvailable>AvailableB</pIsAvailable>
                    <Value>10</Value>
                </EnumEntry>
                <EnumEntry Name="EnumValue2">
                    <Value>20</Value>
                </EnumEntry>
                <Value>10</Value>
            </Enumeration>

            <IntReg Name="AvailableA">
                <Address>0</Address>
                <Length>4</Length>
                <AccessMode>RW</AccessMode>
                <pPort>Port</pPort>
                <Cachable>NoCache</Cachable>
                <Sign>Signed</Sign>
                <Endianess>LittleEndian</Endianess>
            </IntReg>

            <IntReg Name="AvailableB">
                <Address>0</Address>
                <Length>4</Length>
                <AccessMode>RW</AccessMode>
                <pPort>Port</pPort>
                <Cachable>WriteThrough</Cachable>
                <Sign>Signed</Sign>
                <Endianess>LittleEndian</Endianess>
            </IntReg>

            <Port Name="Port"/>

        """

        Camera = CNodeMapRef()
        Camera._LoadXMLFromFile("GenApiTest", "EnumerationTestSuite_TestTicket778")

        EnumA = Camera.GetNode("EnumA")
        EnumEntry_EnumA_EnumValue1 = Camera.GetNode("EnumEntry_EnumA_EnumValue1")
        EnumEntry_EnumA_EnumValue2 = Camera.GetNode("EnumEntry_EnumA_EnumValue2")
        AvailableA = Camera.GetNode("AvailableA")

        EnumB = Camera.GetNode("EnumB")
        EnumEntry_EnumB_EnumValue1 = Camera.GetNode("EnumEntry_EnumB_EnumValue1")
        EnumEntry_EnumB_EnumValue2 = Camera.GetNode("EnumEntry_EnumB_EnumValue2")
        AvailableB = Camera.GetNode("AvailableB")

        self.assertEqual(NoCache, AvailableA.GetNode().GetCachingMode())
        self.assertEqual(WriteThrough, AvailableB.GetNode().GetCachingMode())

        self.assertEqual(No, EnumEntry_EnumA_EnumValue1.GetNode().IsAccessModeCacheable())
        self.assertEqual(Yes, EnumEntry_EnumB_EnumValue1.GetNode().IsAccessModeCacheable())

        self.assertEqual(Yes, EnumEntry_EnumA_EnumValue2.GetNode().IsAccessModeCacheable())
        self.assertEqual(Yes, EnumEntry_EnumB_EnumValue2.GetNode().IsAccessModeCacheable())

        self.assertEqual(No, EnumA.GetNode().IsAccessModeCacheable())
        self.assertEqual(Yes, EnumB.GetNode().IsAccessModeCacheable())

if __name__ == "__main__":
    # import sys;sys.argv = ['', 'EnumerationTestSuite.test_AccessMode_issue_711']
    unittest.main()


"""
Manage data from Google Maps.

- Ethan Jones <ejones18@sheffield.ac.uk>
- Jamie Taylor <jamie.taylor@sheffield.ac.uk>
- First Authored: 2022-10-19
"""

import os
import sys
import logging
import pickle
from pathlib import Path
from typing import Optional, Iterable, Tuple, Union, List, Dict

import numpy as np
import pandas as pd
import googlemaps

from . utilities import GenericException

SCRIPT_DIR = Path(os.path.dirname(os.path.realpath(__file__)))

class GMaps:
    """The Gmaps data manager for the Geocode class."""
    def __init__(self, cache_manager, gmaps_key_file=None):
        """The Gmaps data manager for the Geocode class."""
        self.cache_manager = cache_manager
        self.gmaps_key = None
        self.gmaps_client = None
        self.cache_file = "gmaps_cache"
        self.gmaps_key_file = gmaps_key_file if gmaps_key_file is not None \
                                  else self.cache_manager.cache_dir.joinpath("key.txt")
        self._load_cache()
        self.cache_modified = False

    def __enter__(self):
        """Context manager."""
        return self

    def __exit__(self, type, value, traceback):
        """Context manager - flush GMaps cache on exit."""
        self.flush_cache()

    def _load_key(self):
        """Load the user's GMaps API key from installation directory."""
        try:
            with open(self.gmaps_key_file) as fid:
                key = fid.read().strip()
        except FileNotFoundError:
            logging.warning("Failed to load Google Maps API key from '%s' - you "
                            "will not be able to make new queries to the Google Maps API!",
                            self.gmaps_key_file)
            return None
        return key

    def flush_cache(self):
        """Flush any new GMaps API queries to the GMaps cache."""
        if self.cache_modified:
            self.cache_manager.write(self.cache_file, self.cache)

    def geocode_postcode(self, postcode: [str],
                         address: Optional[str] = None) -> Union[Tuple[float, float], List[Tuple[float, float]]]:
        """
        Geocode several postcodes and/or addresses.

        Parameters
        ----------
        `postcodes` : iterable of strings
            The postcodes (or partial postcodes) to geocode. Must align with *addresses* if both are
            passed.
        `addresses` : iterable of strings
            The addresses to geocode. Must align with *postcodes* if both are passed.

        Returns
        -------
        tuple or list of tuples
            If a single constituency name was passed (i.e. a string), the output be a tuple
            containing: latitude (float), longitude (float). If several constituency names are
            passed (i.e. an iterable of strings), the output will be a list of tuples which aligns
            with the input iterable.
        """
        address = [None for a in address] if address is None else list(address)
        logging.debug("Geocoding %s postcodes (%s addresses)", len(postcode), len(address))
        results = []
        for pc, addr in zip(postcode, address):
            results.append(self.geocode_one(postcode=pc, address=addr))
        return results

    def geocode_one(self, postcode: str, address: Optional[str] = None) -> pd.Series:
        """
        Use the GMaps API to geocode a postcode (or partial postcode) and/or an address.

        Parameters
        ----------
        `postcode` : string
            The postcode (or partial postcode) to geocode.
        `address` : string
            The address to geocode.

        Returns
        -------
        Pandas.Series
            A Pandas Series with fields: input_postcode (str), latitude (float), longitude (float),
            match_status (int). The status code shows the quality of the postcode lookup - use the
            class attribute *self.status_codes* (a dict) to get a string representation.
        """
        if postcode is None and address is None:
            raise utils.GenericException("You must pass either postcode or address, or both.")
        if self.gmaps_key is None:
            self.gmaps_key = self._load_key()
            if self.gmaps_key is not None:
                self.gmaps_client = googlemaps.Client(key=self.gmaps_key)
        if self.cache is None:
            self._load_cache()
        sep = ", " if address and postcode else ""
        postcode = postcode if postcode is not None else ""
        address = address if address is not None else ""
        search_term = f"{address}{sep}{postcode}"
        if search_term in self.cache:
            logging.debug("Loading GMaps Geocoder API result from cache: '%s'", search_term)
            geocode_result = self.cache[search_term]
        else:
            logging.debug("Querying Google Maps Geocoder API for '%s'", search_term)
            if self.gmaps_key is None:
                return pd.Series({"latitude": np.nan, "longitude": np.nan, "match_status": 0})
            geocode_result = self.gmaps_client.geocode(search_term, region="uk")
            self.cache[search_term] = geocode_result
            self.cache_modified = True
        if not geocode_result or len(geocode_result) > 1:
            return pd.Series({"latitude": np.nan, "longitude": np.nan, "match_status": 0})
        geometry = geocode_result[0]["geometry"]
        ok_loc_types = ["ROOFTOP", "GEOMETRIC_CENTER"]
        if geometry["location_type"] in ok_loc_types or \
            geocode_result[0]["types"] == ["postal_code"]:
            return pd.Series({"latitude": geometry["location"]["lat"],
                              "longitude": geometry["location"]["lng"],
                              "match_status": 3})
        return pd.Series({"latitude": np.nan, "longitude": np.nan, "match_status": 0})

    def _load_cache(self):
        """Load the cache of prior addresses/postcodes for better performance."""
        self.cache = self.cache_manager.retrieve(self.cache_file)
        if self.cache is None:
            self.cache = {}
        return


import paddlehub as hub
from paddlenlp.data import JiebaTokenizer
from model import BoWModel

import ast
import argparse

parser = argparse.ArgumentParser(__doc__)
parser.add_argument("--hub_embedding_name", type=str, default='w2v_baidu_encyclopedia_target_word-word_dim300', help="")
parser.add_argument("--max_seq_len", type=int, default=128, help="Number of words of the longest seqence.")
parser.add_argument("--batch_size", type=int, default=64, help="Total examples' number in batch for training.")
parser.add_argument("--checkpoint", type=str, default='./checkpoint/best_model/model.pdparams', help="Model checkpoint")
parser.add_argument(
    "--use_gpu",
    type=ast.literal_eval,
    default=True,
    help="Whether use GPU for fine-tuning, input should be True or False")

args = parser.parse_args()

if __name__ == '__main__':
    # Data to be prdicted
    data = [
        ["这个宾馆比较陈旧了，特价的房间也很一般。总体来说一般"],
        ["交通方便；环境很好；服务态度很好 房间较小"],
        ["还稍微重了点，可能是硬盘大的原故，还要再轻半斤就好了。其他要进一步验证。贴的几种膜气泡较多，用不了多久就要更换了，屏幕膜稍好点，但比没有要强多了。建议配赠几张膜让用用户自己贴。"],
        ["前台接待太差，酒店有A B楼之分，本人check－in后，前台未告诉B楼在何处，并且B楼无明显指示；房间太小，根本不像4星级设施，下次不会再选择入住此店啦"],
        ["19天硬盘就罢工了~~~算上运来的一周都没用上15天~~~可就是不能换了~~~唉~~~~你说这算什么事呀~~~"],
    ]

    label_map = {0: 'negative', 1: 'positive'}

    embedder = hub.Module(name=args.hub_embedding_name)
    tokenizer = embedder.get_tokenizer()
    model = BoWModel(embedder=embedder, tokenizer=tokenizer, load_checkpoint=args.checkpoint, label_map=label_map)

    results = model.predict(
        data, max_seq_len=args.max_seq_len, batch_size=args.batch_size, use_gpu=args.use_gpu, return_result=False)
    for idx, text in enumerate(data):
        print('Data: {} \t Lable: {}'.format(text[0], results[idx]))


#def fibnocci(lmt):
lmt=int(input('Enter limit :'))
a=0
b=1
sum=0
count=1
print("Fibnocci Series :")
while count<=lmt:
        print(sum)
        count+=1
        a=b
        b=sum
        sum=a+b


import time
from dataclasses import dataclass
from fake_useragent import UserAgent

import re
from requests_html import HTML
from slugify import slugify

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.webdriver import WebDriver

def get_user_agent():
    return UserAgent(verify_ssl=False).random

def extract_price_from_string(value: str, regex=r"[\$]{1}[\d,]+\.?\d{0,2}"):
    x = re.findall(regex, value)
    val = None
    if len(x) == 1:
        val = x[0]
    return val

@dataclass
class Scraper:
    url: str = None
    asin: str = None
    endless_scroll : bool = False
    endless_scroll_time: int = 5
    driver: WebDriver = None
    html_obj: HTML = None

    def __post_init__(self):
        if self.asin:
            self.url = f"https://www.amazon.com/dp/{self.asin}/"
        if not self.asin or not self.url:
            raise Exception(f"asin or url is required.")

    def get_driver(self):
        if self.driver is None:
            user_agent = get_user_agent()
            options = Options()
            options.add_argument("--no-sandbox")
            options.add_argument("--headless")
            options.add_argument(f"user-agent={user_agent}")
            driver = webdriver.Chrome(options=options)
            self.driver = driver
        return self.driver

    def perform_endless_scroll(self, driver=None):
        if driver is None:
            return
        if self.endless_scroll:
            # driver.execute_script
            current_height = driver.execute_script("return document.body.scrollHeight")
            while True:
                driver.execute_script("window.scrollTo(0, document.body.scrollHeight)")
                time.sleep(self.endless_scroll_time)
                iter_height = driver.execute_script("return document.body.scrollHeight")
                if current_height == iter_height:
                    break
                current_height = iter_height
        return

    def extract_element_text(self, element_id):
        html_obj = self.get_html_obj()
        el =  html_obj.find(element_id, first=True)
        if not el:
            return ''
        return el.text

    def extract_tables(self):
        html_obj = self.get_html_obj()
        return html_obj.find("table")

    def extract_table_dataset(self, tables) -> dict:
        dataset = {}
        for table in tables:
            for tbody in table.element.getchildren():
                for tr in tbody.getchildren():
                    row = []
                    for col in tr.getchildren():
                        content = ""
                        try:
                            content = col.text_content()
                        except:
                            pass
                        if content != "":
                            _content = content.strip()
                            row.append(_content)
                    if len(row) != 2:
                        continue
                    key = row[0]
                    value = row[1]

                    # print(key, value)
                    data = {}
                    key = slugify(key)
                    key = key.replace("-", "_")
                    if key in dataset:
                        continue
                    else:
                        if "$" in value:
                            new_key = key
                            old_key = f'{key}_raw'
                            new_value = extract_price_from_string(value)
                            old_value = value
                            dataset[new_key] = new_value
                            dataset[old_key] = old_value
                        else:
                            dataset[key] = value
        return dataset

    def get_html_obj(self):
        if self.html_obj is None:
            html_str = self.get()
            self.html_obj = HTML(html=html_str)
        return self.html_obj

    def get(self):
        driver = self.get_driver()
        driver.get(self.url)
        if self.endless_scroll:
            self.perform_endless_scroll(driver=driver)
        else:
            time.sleep(10)
        return driver.page_source

    def scrape(self):
        html_obj = self.get_html_obj()
        price_str = self.extract_element_text('#priceblock_ourprice')
        title_str = self.extract_element_text('#productTitle')
        tables = self.extract_tables()
        dataset = self.extract_table_dataset(tables)
        return {
            "price_str": price_str,
            "title_str": title_str,
            "title": title_str,
            **dataset
        }


#****************************************#
###########    Define Node    ############
#****************************************#

class Node:
    def __init__(self,data):            #constructor of the class
        self.data = data
        self.next = None
        self.prev = None

#****************************************#
########### Define LinkedList ############
#****************************************#

class DoublyLinkedList:
    def __init__(self):
        self.head = None

    #****************************************#
    ########### Add Node @ Begining ##########
    #****************************************#

    def push(self,n1):
        new_node = Node(n1)

        new_node.next = self.head.next
        self.head = new_node
        new_node.prev = None

    #****************************************#
    ########### Append @ End #### ############
    #****************************************#

    def append(self,n1):
        new_node = Node(n1)
        new_node.next = None                    # As this node is going to be last node

        if self.head is None:
            new_node.prev = None
            self.head = new_node
            return

        last_node = self.head

        while last_node.next:
            last_node = last_node.next
        last_node.next = new_node
        new_node.prev = last_node

    #****************************************#
    ##### Add a node before a given node #####
    #****************************************#

    def insertBefore(self,next_node,n1):
        new_node = Node(n1)

        if next_node is None and self.head:
            print("This node doesn't exist in DLL")
            return

        new_node.prev = next_node.next
        next_node.prev = new_node
        new_node.next = next_node

        if new_node.prev is not None:           # what if it's None ??
            new_node.prev.next = new_node

    #****************************************#
    ##### Add a node after a given node ######
    #****************************************#

    def insertAfter(self,prev_node,n1):
        new_node = Node(n1)

        if prev_node is None and self.head:
            print("This node doesn't exist in DLL")
            return

        new_node.next = prev_node.next
        prev_node.next = new_node
        new_node.prev = prev_node

        if new_node.next is not None:
            new_node.next.prev = new_node

llist = DoublyLinkedList()
# Insert 6. So the list becomes 6->None
llist.append(6)

# Insert 7 at the beginning.
# So linked list becomes 7->6->None
llist.push(7)

# Insert 1 at the beginning.
# So linked list becomes 1->7->6->None
llist.push(1)

# Insert 4 at the end.
# So linked list becomes 1->7->6->4->None
llist.append(4)

# Insert 8, after 7.
# So linked list becomes 1->7->8->6->4->None
llist.insertAfter(llist.head.next, 8)

print ("Created DLL is: ",printList(llist.head)) # Not Working


import unittest
from KMPalgorithm import Solution

class ImplementstrStrTest(unittest.TestCase):
    def test_basic_function(self):
        temp = Solution()
        self.heystack = "hello"
        self.needle = "ll"
        self.assertEqual(temp.strStr(self.heystack,self.needle), 2)

    def test_no_needle_found(self):
        temp = Solution()
        self.heystack = "HelloWorld"
        self.needle = "aa"
        self.assertEqual(temp.strStr(self.heystack,self.needle), -1)

    def test_haystack_is_needle(self):
        temp = Solution()
        self.heystack = "needle"
        self.needle = "needle"
        self.assertEqual(temp.strStr(self.heystack,self.needle), 0)

    def test_empty_needle(self):
        temp = Solution()
        self.heystack = "aword"
        self.needle = ""
        self.assertEqual(temp.strStr(self.heystack,self.needle), 0)

    def test_needle_in_the_front(self):
        temp = Solution()
        self.heystack = "aabbccdd"
        self.needle = "aa"
        self.assertEqual(temp.strStr(self.heystack,self.needle), 0)

    def test_needle_in_the_end(self):
        temp = Solution()
        self.heystack = "aabbccdd"
        self.needle = "dd"
        self.assertEqual(temp.strStr(self.heystack,self.needle), 6)

    def test_needle_in_the_middle(self):
        temp = Solution()
        self.heystack = "aabbccddee"
        self.needle = "cc"
        self.assertEqual(temp.strStr(self.heystack,self.needle), 4)

    def test_needle_larger_than_haystack(self):
        temp = Solution()
        self.heystack = "aaa"
        self.needle = "aaaa"
        self.assertEqual(temp.strStr(self.heystack,self.needle), -1)

    def test_needle_euqal_last_letter(self):
        temp = Solution()
        self.heystack = "abcdefg"
        self.needle = "gigeo"
        self.assertEqual(temp.strStr(self.heystack,self.needle), -1)

    def test_mississippi(self):
        temp = Solution()
        self.heystack = "mississippi"
        self.needle = "issip"
        self.assertEqual(temp.strStr(self.heystack,self.needle), 4)

    def test_mississippi2(self):
        temp = Solution()
        self.heystack = "mississippi"
        self.needle = "pi"
        self.assertEqual(temp.strStr(self.heystack,self.needle), 9)

    def test_aabaaac(self):
        temp = Solution()
        self.heystack = "aabaaabaaac"
        self.needle = "aabaaac"
        self.assertEqual(temp.strStr(self.heystack,self.needle), 4)

if __name__ == "__main__":
    unittest.main()


import turtle
import random

screen = turtle.Screen()
screen.setup(width=1000, height=600)
user_bet = turtle.textinput(title='Make Your bet', prompt="Which turtle is going to win the race? Enter a color: ")
colors = ["red", "orange", "yellow", "green", "blue", "purple"]

def set_up(competitor, y, i):
    competitor.penup()
    competitor.shape('turtle')
    competitor.color(colors[i])
    competitor.setpos(-450, y)

def move_turtle(competitor):
    competitor.fd(random.randint(1, 20))
    if check_pos(competitor):
        return competitor.pencolor()

def check_pos(competitor):
    return (competitor.xcor() > 450)

tim = turtle.Turtle()
tom = turtle.Turtle()
john = turtle.Turtle()
frank = turtle.Turtle()
joe = turtle.Turtle()
fread = turtle.Turtle()
competitors = [tim, tom, john, frank, joe, fread]

i = 0
for competitor in competitors:
    set_up(competitor,y=(250 - (i * 100)), i=i)
    i += 1

winner = None
while winner == None:
    winner = move_turtle(random.choice(competitors))

result = 'Won' if user_bet.lower() == winner.lower() else 'Lost'
print(f"{winner.capitalize()} turtle has won, You've {result}")

screen.exitonclick()


import time
import datetime
# get current time
# date_time1 = time.strftime("%-I")
# date_time2 = time.strftime("%M")
# date_time3= time.strftime("%p")
from tts import *

# print(date_time1,date_time2,date_time3)

def getTime():
    val=None
    h=date_time1 = time.strftime("%-I")
    m=date_time2 = time.strftime("%M")
    ampm=date_time3= time.strftime("%p")
    if ampm=="PM":
        if int(h)==12 and int(m)==0:
            val="Noon"
        elif int(h)==12 and int(m)>0:
            val="Afternoon"
        elif int(h)<4:
            val="Afternoon"
        elif int(h)>=4 and int(h)<8:
            val="Evening"
        else:
            val="Night"
    else:
        if int(h)==12 and int(m)==0:
            val="Mid-Night"
        elif int(h)==12 and int(m)>0:
            val="Night"
        elif int(h)<4:
            val="Night"
        else:
            val="Morning"
    strTime = time.strftime("%-I:%M")
    print(strTime)
    if val=="Noon":
        speak("The time is "+strTime+" in the noon")
    elif val=="Afternoon":
        speak("The time is "+strTime+" in the afternoon")
    elif val=="Evening":
        speak("The time is "+strTime+" in the evening")
    elif val=="Night":
        speak("The time is "+strTime+" at night")
    elif val=="Mid-Night":
        speak("The time is "+strTime+" at mid-night")
    elif val=="Morning":
        speak("The time is "+strTime+" in the morning")


import os.path as osp
import numpy as np
import paddle
from paddleslim import L1NormFilterPruner

def build_yolo_transforms(params):
    from paddlex import transforms as T
    target_size = params.image_shape[0]
    use_mixup = params.use_mixup
    dt_list = []
    if use_mixup:
        dt_list.append(
            T.MixupImage(
                alpha=params.mixup_alpha,
                beta=params.mixup_beta,
                mixup_epoch=int(params.num_epochs * 25. / 27)))
    dt_list.extend([
        T.RandomDistort(
            brightness_range=params.brightness_range,
            brightness_prob=params.brightness_prob,
            contrast_range=params.contrast_range,
            contrast_prob=params.contrast_prob,
            saturation_range=params.saturation_range,
            saturation_prob=params.saturation_prob,
            hue_range=params.hue_range,
            hue_prob=params.hue_prob),
        T.RandomExpand(
            prob=params.expand_prob,
            im_padding_value=[float(int(x * 255)) for x in params.image_mean])
    ])
    crop_image = params.crop_image
    if crop_image:
        dt_list.append(T.RandomCrop())
    dt_list.extend([
        T.Resize(
            target_size=target_size, interp='RANDOM'),
        T.RandomHorizontalFlip(prob=params.horizontal_flip_prob), T.Normalize(
            mean=params.image_mean, std=params.image_std)
    ])
    train_transforms = T.Compose(dt_list)
    eval_transforms = T.Compose([
        T.Resize(
            target_size=target_size, interp='CUBIC'),
        T.Normalize(
            mean=params.image_mean, std=params.image_std),
    ])
    return train_transforms, eval_transforms

def build_rcnn_transforms(params):
    from paddlex import transforms as T
    short_size = min(params.image_shape)
    max_size = max(params.image_shape)
    train_transforms = T.Compose([
        T.RandomDistort(
            brightness_range=params.brightness_range,
            brightness_prob=params.brightness_prob,
            contrast_range=params.contrast_range,
            contrast_prob=params.contrast_prob,
            saturation_range=params.saturation_range,
            saturation_prob=params.saturation_prob,
            hue_range=params.hue_range,
            hue_prob=params.hue_prob),
        T.RandomHorizontalFlip(prob=params.horizontal_flip_prob),
        T.Normalize(
            mean=params.image_mean, std=params.image_std),
        T.ResizeByShort(
            short_size=short_size, max_size=max_size),
    ])
    eval_transforms = T.Compose([
        T.Normalize(),
        T.ResizeByShort(
            short_size=short_size, max_size=max_size),
    ])
    return train_transforms, eval_transforms

def build_pico_transforms(params):
    from paddlex import transforms as T
    target_size = params.image_shape[0]
    dt_list = []
    dt_list.extend([
        T.RandomDistort(
            brightness_range=params.brightness_range,
            brightness_prob=params.brightness_prob,
            contrast_range=params.contrast_range,
            contrast_prob=params.contrast_prob,
            saturation_range=params.saturation_range,
            saturation_prob=params.saturation_prob,
            hue_range=params.hue_range,
            hue_prob=params.hue_prob),
    ])
    crop_image = params.crop_image
    if crop_image:
        dt_list.append(T.RandomCrop())
    dt_list.extend([
        T.Resize(
            target_size=target_size, interp='RANDOM'),
        T.RandomHorizontalFlip(prob=params.horizontal_flip_prob), T.Normalize(
            mean=params.image_mean, std=params.image_std)
    ])
    train_transforms = T.Compose(dt_list)
    eval_transforms = T.Compose([
        T.Resize(
            target_size=target_size, interp='CUBIC'),
        T.Normalize(
            mean=params.image_mean, std=params.image_std),
    ])
    return train_transforms, eval_transforms

def build_voc_datasets(dataset_path, train_transforms, eval_transforms):
    import paddlex as pdx
    train_file_list = osp.join(dataset_path, 'train_list.txt')
    eval_file_list = osp.join(dataset_path, 'val_list.txt')
    label_list = osp.join(dataset_path, 'labels.txt')
    train_dataset = pdx.datasets.VOCDetection(
        data_dir=dataset_path,
        file_list=train_file_list,
        label_list=label_list,
        transforms=train_transforms,
        shuffle=True)
    eval_dataset = pdx.datasets.VOCDetection(
        data_dir=dataset_path,
        file_list=eval_file_list,
        label_list=label_list,
        transforms=eval_transforms)
    return train_dataset, eval_dataset

def build_coco_datasets(dataset_path, train_transforms, eval_transforms):
    import paddlex as pdx
    data_dir = osp.join(dataset_path, 'JPEGImages')
    train_ann_file = osp.join(dataset_path, 'train.json')
    eval_ann_file = osp.join(dataset_path, 'val.json')
    train_dataset = pdx.datasets.CocoDetection(
        data_dir=data_dir,
        ann_file=train_ann_file,
        transforms=train_transforms,
        shuffle=True)
    eval_dataset = pdx.datasets.CocoDetection(
        data_dir=data_dir, ann_file=eval_ann_file, transforms=eval_transforms)
    return train_dataset, eval_dataset

def build_optimizer(parameters, step_each_epoch, params):
    import paddle
    from paddle.regularizer import L2Decay
    learning_rate = params.learning_rate
    lr_decay_epochs = params.lr_decay_epochs
    warmup_steps = params.warmup_steps
    warmup_start_lr = params.warmup_start_lr

    boundaries = [b * step_each_epoch for b in lr_decay_epochs]
    values = [
        learning_rate * (0.1**i) for i in range(len(lr_decay_epochs) + 1)
    ]
    lr = paddle.optimizer.lr.PiecewiseDecay(
        boundaries=boundaries, values=values)
    lr = paddle.optimizer.lr.LinearWarmup(
        learning_rate=lr,
        warmup_steps=warmup_steps,
        start_lr=warmup_start_lr,
        end_lr=learning_rate)
    factor = 1e-04 if params.model in ['FasterRCNN', 'MaskRCNN'] else 5e-04
    optimizer = paddle.optimizer.Momentum(
        learning_rate=lr,
        momentum=0.9,
        weight_decay=L2Decay(factor),
        parameters=parameters)
    return optimizer

def train(task_path, dataset_path, params):
    import paddlex as pdx
    pdx.log_level = 3
    if params.model in ['YOLOv3', 'PPYOLO', 'PPYOLOTiny', 'PPYOLOv2']:
        train_transforms, eval_transforms = build_yolo_transforms(params)
    elif params.model in ['PicoDet']:
        train_transforms, eval_transforms = build_pico_transforms(params)
    elif params.model in ['FasterRCNN', 'MaskRCNN']:
        train_transforms, eval_transforms = build_rcnn_transforms(params)
    if osp.exists(osp.join(dataset_path, 'JPEGImages')) and \
        osp.exists(osp.join(dataset_path, 'train.json')) and \
        osp.exists(osp.join(dataset_path, 'val.json')):
        train_dataset, eval_dataset = build_coco_datasets(
            dataset_path=dataset_path,
            train_transforms=train_transforms,
            eval_transforms=eval_transforms)
    elif osp.exists(osp.join(dataset_path, 'train_list.txt')) and \
        osp.exists(osp.join(dataset_path, 'val_list.txt')) and \
        osp.exists(osp.join(dataset_path, 'labels.txt')):
        train_dataset, eval_dataset = build_voc_datasets(
            dataset_path=dataset_path,
            train_transforms=train_transforms,
            eval_transforms=eval_transforms)
    step_each_epoch = train_dataset.num_samples // params.batch_size
    train_batch_size = params.batch_size
    save_interval_epochs = params.save_interval_epochs
    save_dir = osp.join(task_path, 'output')
    pretrain_weights = params.pretrain_weights
    if pretrain_weights is not None and osp.exists(pretrain_weights):
        pretrain_weights = osp.join(pretrain_weights, 'model.pdparams')

    detector = getattr(pdx.det, params.model)
    num_classes = len(train_dataset.labels)
    sensitivities_path = params.sensitivities_path
    pruned_flops = params.pruned_flops
    model = detector(num_classes=num_classes, backbone=params.backbone)

    if sensitivities_path is not None:
        # load weights
        model.net_initialize(pretrain_weights=pretrain_weights)
        pretrain_weights = None
        # prune
        dataset = eval_dataset or train_dataset
        im_shape = dataset[0]['image'].shape[:2]
        if getattr(model, 'with_fpn',
                   False) or model.__class__.__name__ == 'PicoDet':
            im_shape[0] = int(np.ceil(im_shape[0] / 32) * 32)
            im_shape[1] = int(np.ceil(im_shape[1] / 32) * 32)
        inputs = [{
            "image": paddle.ones(
                shape=[1, 3] + list(im_shape), dtype='float32'),
            "im_shape": paddle.full(
                [1, 2], 640, dtype='float32'),
            "scale_factor": paddle.ones(
                shape=[1, 2], dtype='float32')
        }]
        model.net.eval()
        model.pruner = L1NormFilterPruner(
            model.net, inputs=inputs, sen_file=sensitivities_path)
        model.prune(pruned_flops=pruned_flops)

    optimizer = build_optimizer(model.net.parameters(), step_each_epoch,
                                params)
    model.train(
        num_epochs=params.num_epochs,
        train_dataset=train_dataset,
        train_batch_size=train_batch_size,
        eval_dataset=eval_dataset,
        save_interval_epochs=save_interval_epochs,
        log_interval_steps=2,
        save_dir=save_dir,
        pretrain_weights=pretrain_weights,
        optimizer=optimizer,
        use_vdl=True,
        resume_checkpoint=params.resume_checkpoint)


import os
import json
import logging
import openai
import copy
from datetime import datetime

try:
    import src.utils as utils
    import src.dialogue_manager as dialogue_manager
    import src.answer_parser as answer_parser
    from src.api_secrets import API_KEY
except ImportError:
    try:
        import utils
        import dialogue_manager
        import answer_parser
        from api_secrets import API_KEY
    except ImportError as e:
        print('ERROR:')
        print(e)
        exit(-1)

def mainloop(manager, config):
    stop = False
    while not stop:
        out = manager.call(config)
        logging.info('dm:\n%s', out)
        if config.get('stuck', 0):
            return manager
        manager, stop = interpret_dm(manager, out, config)
    return manager

def fill_chunk(cf_manager, config):
    cf_manager.dialogue = []
    stop = False
    while not stop:
        out = cf_manager.call(config)
        if config.get('stuck', 0):
            return cf_manager
        cf_manager, stop = interpret_cf(cf_manager, out, config)
    return cf_manager

def run_dialogue(a_parser, config):
    stop = False
    while not stop:
        out = a_parser.call(config)
        if config.get('stuck', 0):
            return a_parser
        a_parser, stop = interpret_parser(a_parser, out, config)
    return a_parser

def interpret_parser(parser, out, config):
    """interprets the output of the AnswerParsing module and runs the appropriate functions

    Args:
        parser (AnswerParsing): AnswerParsing object
        output (str): output given by the CFM as serialized json
        config (dict): config info

    Returns:
        parser: AnswerParsing object
        stop: boolean signaling to stop the loop (true of next action is 'return')
    """
    json_out = json.loads(out)
    json_out['next action'] = json_out["next action"].lower()

    if json_out['next action'] == 'repeat_question':
        logging.info('answer_parsing --> repeat_question')
        new_q = parser.repeat_question(config)
        json_q = json.loads(new_q)
        # print('GENERATED QUESTION:')
        print(json_q['new question'])
        if not config['autouser']:
            a = input('ANSWER: ')
        else:
            a = utils.auto_user(json_q['new question'], config)
            print('ANSWER:')
            print(a)
        interaction = {
            'module': 'user',
            'prompt': json_q['new question'],
            'output': a
        }
        utils.add_to_transcript(interaction, config)
        # TBD: check if the answer is valid (e.g. not empty)
        parser.dialogue.append({'Assistant': f'{json_q["new question"]}'})
        parser.dialogue.append({'User': a})
        logging.info('repeat_question --> answer_parsing:\n%s', json.dumps(parser.dialogue))
        return parser, False

    elif json_out['next action'] == 'follow_up_question':
        logging.info('answer_parsing --> follow_up_question')
        q = parser.follow_up_question(config)
        json_q = json.loads(q)
        # print('GENERATED QUESTION:')
        print(json_q['question'])
        if not config['autouser']:
            a = input('ANSWER: ')
        else:
            a = utils.auto_user(json_q['question'], config)
            print('ANSWER:')
            print(a)
        interaction = {
            'module': 'user',
            'prompt': json_q['question'],
            'output': a
        }
        utils.add_to_transcript(interaction, config)
        # TBD: check if the answer is valid (e.g. not empty)
        parser.dialogue.append({'Assistant': f'{json_q["question"]}'})
        parser.dialogue.append({'User': a})
        logging.info('follow_up_question --> answer_parsing:\n%s', json.dumps(parser.dialogue))
        return parser, False

    elif json_out['next action'] == 'information_extraction':
        logging.info('answer_parsing --> information_extraction')
        info = parser.information_extraction(config)
        logging.info("information_extraction --> form_filling:\n%s", info)
        filled = parser.form_filling(config)
        logging.info("form_filling --> cfm:\n%s", filled)
        return parser, True

    else:
        return parser, False

def interpret_cf(cfm, out, config):
    """interprets the output of the Chunk Filling manager module and runs the appropriate functions

    Args:
        cfm (ChunkFilling): Chunk Filling Dialogue Manger object
        output (str): output given by the CFM as serialized json
        config (dict): config info

    Returns:
        cfm: CFM object
        stop: boolean signaling to stop the loop (true of next action is 'return')
    """
    json_out = json.loads(out)
    json_out['next action'] = json_out["next action"].lower()

    if json_out['next action'] == 'question_generation':
        logging.info('cfm --> question_generation')
        q = cfm.question_generation(config)
        json_q = json.loads(q)
        flds = json_q['fields']
        if not flds:
            no_flds = True
        elif flds[0] == "":
            no_flds = True
        else:
            no_flds = False
        if json_q['question'] is None or no_flds:
            logging.warning('no new question could be generated, returning to CFM')
            logging.info('question_generation --> cfm')
            tmp = [json_out['next action']]
            if len(cfm.state['last action']) > 5:
                tmp.extend(cfm.state['last action'][:-1])
            else:
                tmp.extend(cfm.state['last action'])
            cfm.state['last action'] = tmp
            cfm.state['last question'] = "question_generation did not find a new question to ask and suggests that fill_validation be called"
            return cfm, False
        cfm.state['last question'] = json_q['question']
        # print('GENERATED QUESTION:')
        print(json_q['question'])
        if not config['autouser']:
            a = input('ANSWER: ')
        else:
            a = utils.auto_user(json_q['question'], config)
            print('ANSWER:')
            print(a)
        interaction = {
            'module': 'user',
            'prompt': json_q['question'],
            'output': a
        }
        utils.add_to_transcript(interaction, config)
        # TBD: check if the answer is valid (e.g. not empty)

        logging.info('question_generation --> answer_parsing:\n%s', q)

        chunk_copy = copy.deepcopy(cfm.chunk)
        info_copy = copy.deepcopy(cfm.info)
        open_chunk = utils.get_unanswered(chunk_copy, cfm.state['fields'])
        parser = answer_parser.AnswerParser(
            [
                {"Assistant": json_q['question']},
                {"User": a}
            ],
            json_q['fields'],
            open_chunk,
            info_copy
        )
        # call its main loop
        # get object returned as well as the filled out part and dialogue
        parser = run_dialogue(parser, config)

        # logging.info('parser returned folling chunk: %s', json.dumps(parser.chunk))

        # put filled out chunk from parser into chunk from cfm
        cfm.chunk = utils.fill_in_parts(cfm.chunk, parser.chunk)

        # logging.info('has been filled into cfm chunk: %s', json.dumps(cfm.chunk))

        # append dialogue from parser to dialogue of cfm (extend)
        cfm.dialogue.extend(parser.dialogue)
        for key, value in parser.info.items():
            cfm.info[key] = value

        cfm.state = utils.update_cf_state(cfm.state, cfm.chunk)
        tmp = [json_out['next action']]
        if len(cfm.state['last action']) > 5:
            tmp.extend(cfm.state['last action'][:-1])
        else:
            tmp.extend(cfm.state['last action'])
        cfm.state['last action'] = tmp
        return cfm, False

    elif json_out['next action'] == 'fill_validation':
        logging.info('cfm --> fill_valdiation')
        chunk = cfm.fill_validation(config)
        logging.info('fill_valdiation --> cfm:\n%s', chunk)
        tmp = [json_out['next action']]
        if len(cfm.state['last action']) > 5:
            tmp.extend(cfm.state['last action'][:-1])
        else:
            tmp.extend(cfm.state['last action'])
        cfm.state['last action'] = tmp
        return cfm, False

    elif json_out['next action'] == 'stop':
        logging.info('cfm --> stop')
        tmp = [json_out['next action']]
        if len(cfm.state['last action']) > 5:
            tmp.extend(cfm.state['last action'][:-1])
        else:
            tmp.extend(cfm.state['last action'])
        cfm.state['last action'] = tmp
        logging.info("stop --> dm")
        return cfm, True

    else:
        return cfm, False

def interpret_dm(manager, output, config):
    """interprets the output of the Dialogue manager module and runs the appropriate functions

    Args:
        manager (DialogueManager): Dialogue Manger object
        output (str): output given by the DM as serialized json
        config (dict): config info

    Returns:
        manager: DM object
        stop: boolean signaling to stop the loop (true of next action is 'stop')
    """
    if isinstance(output, str):
        json_out = json.loads(output)
    else:
        json_out = output

    json_out['next action'] = json_out["next action"].lower()

    if json_out['next action'] == 'form_chunks':
        logging.info('dm --> form_chunks')
        manager.form_chunks(config)
        tmp = [json_out['next action']]
        if len(manager.state['last action']) > 5:
            tmp.extend(manager.state['last action'][:-1])
        else:
            tmp.extend(manager.state['last action'])
        manager.state['last action'] = tmp
        return manager, False

    elif json_out['next action'] == 'fill_chunk':
        ctwo = json_out['chunk to work on']
        cf_manager = manager.cf_managers.get(ctwo, -1)
        if cf_manager == -1:
            if not manager.chunks:
                manager, _ = interpret_dm(manager, json.dumps({"next action": "form_chunks", "chunk to work on": ""}), config)
                return manager, False
            else:
                manager, _ = interpret_dm(manager, json.dumps({"next action": "stop", "chunk to work on": ""}), config)
                return manager, True
        manager.cf_managers[ctwo] = fill_chunk(cf_manager, config)
        chunk = manager.cf_managers[ctwo].chunk
        for key, value in chunk.items():
            manager.form[key] = value
        manager.dialogue.extend(manager.cf_managers[ctwo].dialogue)
        tmp = [json_out['next action']]
        if len(manager.state['last action']) > 5:
            tmp.extend(manager.state['last action'][:-1])
        else:
            tmp.extend(manager.state['last action'])
        manager.state['last action'] = tmp
        manager = utils.update_dm_state(manager)
        return manager, False

    elif json_out['next action'] == 'stop':
        tmp = [json_out['next action']]
        if len(manager.state['last action']) > 5:
            tmp.extend(manager.state['last action'][:-1])
        else:
            tmp.extend(manager.state['last action'])
        manager.state['last action'] = tmp
        return manager, True

    else:
        return manager, False

def main(config):
    form = utils.load_form(config['form'], crop = False)
    manager = dialogue_manager.Dialogue_Manager(form)
    out_dir = utils.get_out_dir()
    config['out_dir'] = out_dir
    now = datetime.now()
    date_n_time = now.strftime("%m/%d/%Y, %H:%M:%S")
    config['date and time'] = date_n_time

    manager = mainloop(manager, config)
    with open(os.path.join(config['out_dir'], 'filled-form.json'), 'w') as f:
        json.dump(manager.form, f)
    with open(os.path.join(config['out_dir'], 'dm-state.json'), 'w') as f:
        json.dump(manager.state, f)
    cfm_states = {}
    ext_info = {}
    for cfm in manager.cf_managers:
        cfm_states[cfm] = manager.cf_managers[cfm].state
        for key, val in manager.cf_managers[cfm].info.items():
            ext_info[key] = val
    with open(os.path.join(config['out_dir'], 'info.json'), 'w') as f:
        json.dump(ext_info, f)
    with open(os.path.join(config['out_dir'], 'cfm-states.json'), 'w') as f:
        json.dump(cfm_states, f)
    with open(os.path.join(config['out_dir'], 'config.json'), 'w') as f:
        json.dump(config, f)
    with open(os.path.join(config['out_dir'], 'dialogue.json'), 'w') as f:
        json.dump(manager.dialogue, f)

if __name__ == '__main__':
    logging.basicConfig(filename='logs/run.log',
                        level=logging.INFO,
                        filemode='w',
                        format='%(levelname)s: %(message)s')
    config = utils.load_config("config/config.json")
    # setting key
    openai.api_key = API_KEY
    config = utils.check_specials(config)
    for i in range(config['num_dialogues']):
        main(config)


from app import app
from flask import request, make_response, json
import psycopg2
from db.database import connect
from datetime import datetime
import logging
import os

class messages():

    def __init__(self):
        try:
            self.conn, self.cur = connect()
        except psycopg2.Error as error:
            print(error)

    def get_all_conversations(self):
        try:
            self.cur.execute("SELECT * FROM conversations")
            conv = self.cur.fetchall()

            conversation_list = []
            for conversation in conv:
                conversation_data = {
                    "conversation_id": conversation[0],
                    "conversation_name": conversation[1],
                    "created_at": conversation[2]
                }
                conversation_list.append(conversation_data)

            if conversation_list:
                return make_response({"conversations": conversation_list}, 200)
            else:
                return make_response({"message": "No conversations found!"}, 404)
        except Exception as e:
            self.conn.rollback()
            return make_response({"message": f"Error retrieving conversations: {e}"}, 500)

    def get_all_messages(self, conversation_id):
        try:
            # Get conversation name
            self.cur.execute(
                """
                SELECT conversation_name FROM conversations WHERE conversation_id = %s
                """,
                (conversation_id,),
            )
            conversation_name_result = self.cur.fetchone()
            conversation_name = conversation_name_result[0] if conversation_name_result else "Unknown"

            self.cur.execute("""SELECT * FROM messages WHERE conversation_id = %s""", (conversation_id,))
            msgs = self.cur.fetchall()

            message_list = []
            for message in msgs:
                # Get sender's name
                sender_id = message[2]
                self.cur.execute(
                    """
                    SELECT name FROM profiles WHERE user_id = %s
                    """,
                    (sender_id,),
                )
                sender_name_result = self.cur.fetchone()
                sender_name = sender_name_result[0] if sender_name_result else "Unknown"

                # Get recipient's name
                recipient_id = message[5]
                self.cur.execute(
                    """
                    SELECT name FROM profiles WHERE user_id = %s
                    """,
                    (recipient_id,),
                )
                recipient_name_result = self.cur.fetchone()
                recipient_name = recipient_name_result[0] if recipient_name_result else "Unknown"

                message_data = {
                    "message_id": message[0],
                    "conversation_id": message[1],
                    "sender_id": message[2],
                    "sender_name": sender_name,
                    "content": message[3],
                    "timestamp": message[4],
                    "recipient_id": message[5],
                    "recipient_name": recipient_name
                }
                message_list.append(message_data)

            if message_list:
                sorted_messages = sorted(message_list, key=lambda x: x['timestamp'])
                response_payload = {
                    "conversation_name": conversation_name,
                    "conversation_messages": sorted_messages
                }
                return make_response(response_payload, 200)
            else:
                return make_response({"message": f"No messages found for this conversation with id: {conversation_id}!"}, 404)
        except Exception as e:
            self.conn.rollback()
            return make_response({"message": f"Error retrieving messages: {e}"}, 500)

    def create_conversation(self, sender_id, recipient_id, conversation_name):
        try:
            # Check if sender_id and recipient_id exist in the users table
            self.cur.execute("SELECT id FROM users WHERE id = %s", (sender_id,))
            sender_exists = self.cur.fetchone()

            if not sender_exists:
                return make_response({"message": "Invalid sender_id"}, 400)

            self.cur.execute("SELECT id FROM users WHERE id = %s", (recipient_id,))
            recipient_exists = self.cur.fetchone()

            if not recipient_exists:
                return make_response({"message": "Invalid recipient_id"}, 400)

            # Get the current timestamp
            timestamp = datetime.now()

            # Insert the conversation into the databasea
            self.cur.execute("""
                INSERT INTO conversations (conversation_name, created_at)
                VALUES (%s, %s)
                RETURNING conversation_id
            """, (conversation_name, timestamp))

            conversation_id = self.cur.fetchone()[0]
            self.conn.commit()

            return make_response({"conversation_id": conversation_id}, 200)
        except Exception as e:
            self.conn.rollback()
            return make_response({"message": f"Error creating conversation: {e}"}, 500)

    def create_message(self, conversation_id, sender_id, recipient_id, content):
        try:
            # Check if sender_id exists in the users table
            self.cur.execute("SELECT id FROM users WHERE id = %s", (sender_id,))
            sender_exists = self.cur.fetchone()

            if not sender_exists:
                return make_response({"message": "Invalid sender_id"}, 400)

            # Check if recipient_id exists in the users table
            self.cur.execute("SELECT id FROM users WHERE id = %s", (recipient_id,))
            recipient_exists = self.cur.fetchone()

            if not recipient_exists:
                return make_response({"message": "Invalid recipient_id"}, 400)

            if sender_id not in sender_exists:
                return make_response({"message": "Invalid sender_id"}, 400)
            if recipient_id not in recipient_exists:
                return make_response({"message": "Invalid recipient_id"}, 400)

            # Check if content is empty
            if not content:
                return make_response({"message": "Empty content"}, 400)

            # Check if sender_id exists in the users table
            self.cur.execute("SELECT conversation_id FROM conversations WHERE conversation_id = %s", (conversation_id,))
            conversation_exists = self.cur.fetchone()

            if not conversation_exists:
                return make_response({"message": "Invalid conversation_id"}, 400)

            # Get the current timestamp
            timestamp = datetime.now()

            # Insert the message into the database
            self.cur.execute("""
                INSERT INTO messages (conversation_id, sender_id, recipient_id, content, timestamp)
                VALUES (%s, %s, %s, %s, %s)
                RETURNING message_id
            """, (conversation_id, sender_id, recipient_id, content, timestamp))

            message_id = self.cur.fetchone()[0]
            self.conn.commit()

            return make_response({"message_id": message_id}, 200)
        except Exception as e:
            self.conn.rollback()
            return make_response({"message": f"Error creating message: {e}"}, 500)

    def get_conversations(self, user_id):
        try:
            # Retrieve the list of conversations for a user
            self.cur.execute("""
                SELECT DISTINCT conversation_id
                FROM messages
                WHERE sender_id = %s
                UNION
                SELECT DISTINCT conversation_id
                FROM messages
                WHERE recipient_id = %s
            """, (user_id, user_id))

            conversation_ids = [row[0] for row in self.cur.fetchall()]

            # Retrieve all attributes from conversations for the conversation IDs
            conversations = []
            if conversation_ids:
                placeholders = ','.join(['%s'] * len(conversation_ids))
                self.cur.execute(f"""
                    SELECT *
                    FROM conversations
                    WHERE conversation_id IN ({placeholders})
                """, conversation_ids)
                rows = self.cur.fetchall()

                for row in rows:
                    conversation_id, conversation_name, created_at = row
                    created_at_formatted = created_at.strftime("%a, %d %b %Y %H:%M:%S GMT")
                    conversation_data = {
                        "conversation_id": conversation_id,
                        "conversation_name": conversation_name,
                        "created_at": created_at_formatted
                    }
                    conversations.append(conversation_data)

            return make_response({"conversations": conversations}, 200)
        except Exception as e:
            self.conn.rollback()
            return make_response({"message": f"Error retrieving conversations: {e}"}, 500)

    def get_messages(self, conversation_id):
        try:
            # Retrieve the messages for a conversation
            self.cur.execute("""
                SELECT message_id, sender_id, recipient_id, content, timestamp
                FROM messages
                WHERE conversation_id = %s
                ORDER BY timestamp ASC
            """, (conversation_id,))

            messages = []
            rows = self.cur.fetchall()
            for row in rows:
                message_id, sender_id, recipient_id, content, timestamp = row
                timestamp_formatted = timestamp.strftime("%a, %d %b %Y %H:%M:%S GMT")

                # Retrieve sender_name
                self.cur.execute("""
                    SELECT name
                    FROM profiles
                    WHERE user_id = %s
                """, (sender_id,))
                sender_name_row = self.cur.fetchone()
                sender_name = sender_name_row[0] if sender_name_row else "Unknown"

                message = {
                    "message_id": message_id,
                    "sender_id": sender_id,
                    "sender_name": sender_name,
                    "recipient_id": recipient_id,
                    "content": content,
                    "timestamp": timestamp_formatted
                }
                messages.append(message)

            # Retrieve conversation details
            self.cur.execute("""
                SELECT conversation_id, conversation_name, created_at
                FROM conversations
                WHERE conversation_id = %s
            """, (conversation_id,))
            conversation_row = self.cur.fetchone()
            conversation_id, conversation_name, created_at = conversation_row

            response_payload = {
                "conversation_id": conversation_id,
                "conversation_name": conversation_name,
                "created_at": created_at.strftime("%a, %d %b %Y %H:%M:%S GMT"),
                "conversation_messages": messages
            }

            return make_response(response_payload, 200)
        except Exception as e:
            self.conn.rollback()
            return make_response({"message": f"Error retrieving messages: {e}"}, 500)

    def mark_message_as_read(self, message_id):
        try:
            # Update the message as read in the database
            self.cur.execute("""
                UPDATE messages
                SET is_read = TRUE
                WHERE message_id = %s
            """, (message_id,))

            self.conn.commit()

            return make_response({"message": "Message marked as read"}, 200)
        except Exception as e:
            self.conn.rollback()
            return make_response({"message": f"Error marking message as read: {e}"}, 500)


import socket
import argparse

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

parser = argparse.ArgumentParser(description='Port scanner')
parser.add_argument('-s', type= str, help= 'The server you want to scan the ports in it')

args = parser.parse_args()
my_scan = args.s

def port_scan(port):                     #The function that try to conncect
    try:
        sock.connect((my_scan, port))
        return True
    except:
        return False

j = 0

for i in range (1, 65535):               #The range of the scan you wish
        if port_scan(i):                 # if the port was open
            print ('Port', i, 'is open')
            j = j + 1	                  #increase index number of open ports

print('============================')

if j == 0:
    print ('The scan is finished NO ports are open')
else:
    print('The scan is finished', j, 'ports are open')


from flask import Flask, request, render_template, redirect, session, flash, make_response
from werkzeug.exceptions import BadRequestKeyError
from surveys import surveys
from flask_debugtoolbar import DebugToolbarExtension

RESPONSES = 'responses'
CURRENT_SURVEY = 'current_survey'

app = Flask(__name__)

app.config['SECRET_KEY'] = 'its-a-secret'
app.config['DEBUG_TB_INTERCEPT_REDIRECTS'] = False
debug = DebugToolbarExtension(app)

@app.route('/')
def survey_title():
    '''Show Pick a survey form'''

    return render_template('pick_survey.html', surveys=surveys)

@app.route('/', methods=['POST'])
def pick_survey():
    '''Select a survey to start'''
    survey_id = request.form['survey_code']

    # dont let the user re-take a survey until cookie times out
    if request.cookies.get(f'completed_{survey_id}'):
        return render_template('already_done.html')

    survey = surveys[survey_id]
    session[CURRENT_SURVEY] = survey_id

    return render_template('survey_title.html', survey=survey)

@app.route('/start', methods=["POST"])
def start_survey():
    '''begin the survey and display 1st question'''

    session[RESPONSES] = []

    return redirect('/questions/0')

@app.route('/answer', methods=['POST'])
def handle_question():
    '''Save user response and redirect to the next question'''
    choice = None
    #get the user's choice
    try:
        choice = request.form['answer']
    except BadRequestKeyError:
        flash('Please select an answer!', 'error')
        return redirect('/questions/0')

    text = request.form.get('text', "")

    # add this response to the list in the session
    responses = session[RESPONSES]
    responses.append({'choice': choice, 'text': text})

    # add current response to the session
    session[RESPONSES] = responses
    survey_code = session[CURRENT_SURVEY]
    survey = surveys[survey_code]

    if(len(responses) == len(survey.questions)):
        # user answered all questions, thank the user.
        return redirect('/complete')
    else:
        return redirect(f'/questions/{len(responses)}')

@app.route('/questions/<int:questID>')
def display_question(questID):
    '''Display the current question'''

    responses = session.get(RESPONSES)
    survey_code = session[CURRENT_SURVEY]
    survey = surveys[survey_code]

    if (responses is None):
        # if the user is trying to access question page too soon
        return redirect('/')

    if (len(responses) == len(survey.questions)):
        # User answered all questions, Thank them.
        return redirect('/complete')

    if(len(responses) != questID):
        # if Trying to access questions out of order - do not allow
        # flash(f'Invalid question id: {questID}.')
        return redirect(f'/questions/{len(responses)}')

    question = survey.questions[questID]
    return render_template('questions.html', question_num=questID, question=question)

@app.route('/complete')
def complete():
    '''Survey is complete, Thank the user and list the responses.'''
    survey_id = session[CURRENT_SURVEY]
    survey = surveys[survey_id]
    responses = session[RESPONSES]

    html = render_template('complete.html', survey=survey, responses=responses)

    #set the cookie so they can't redo the survey until it's done.
    response = make_response(html)
    response.set_cookie(f'completed_{survey_id}', 'yes', max_age=0)
    return response


import numpy as np
from numpy.testing import assert_almost_equal
import pytest

from statsmodels.datasets import heart
from statsmodels.emplike.aft_el import emplikeAFT
from statsmodels.tools import add_constant

from .results.el_results import AFTRes

class GenRes:
    @classmethod
    def setup_class(cls):
        data = heart.load()
        data.endog = np.asarray(data.endog)
        data.exog = np.asarray(data.exog)
        endog = np.log10(data.endog)
        exog = add_constant(data.exog)
        cls.mod1 = emplikeAFT(endog, exog, data.censors)
        cls.res1 = cls.mod1.fit()
        cls.res2 = AFTRes()

class Test_AFTModel(GenRes):

    def test_params(self):
        assert_almost_equal(self.res1.params(), self.res2.test_params,
                            decimal=4)

    def test_beta0(self):
        assert_almost_equal(self.res1.test_beta([4], [0]),
                            self.res2.test_beta0, decimal=4)

    def test_beta1(self):
        assert_almost_equal(self.res1.test_beta([-.04], [1]),
                            self.res2.test_beta1, decimal=4)

    def test_beta_vect(self):
        assert_almost_equal(self.res1.test_beta([3.5, -.035], [0, 1]),
                            self.res2.test_joint, decimal=4)

    @pytest.mark.slow
    def test_betaci(self):
        ci = self.res1.ci_beta(1, -.06, 0)
        ll = ci[0]
        ul = ci[1]
        ll_pval = self.res1.test_beta([ll], [1])[1]
        ul_pval = self.res1.test_beta([ul], [1])[1]
        assert_almost_equal(ul_pval, .050000, decimal=4)
        assert_almost_equal(ll_pval, .05000, decimal=4)