Beispiel #1
0
def main():
    print "test line 5"
    a1 = Singleton(2)
    print "test line 7"
    a2 = Singleton(3)
    print "test line 9"
    print a1, a1.x, a1.a
    print a2, a1.x, a1.a
def main():
    s = Singleton()
    print s

    s = Singleton.get_instance()
    print s

    s = Singleton.get_instance()
    print s
def main():
    s1 = Singleton()
    s1._instance.first_name = 'William'
    s1._instance.last_name = 'Murphy'
    s1._instance.age = 31

    s2 = Singleton()
    print(s1.__dict__)
    print(s1, s2)
Beispiel #4
0
def main():
    s1 = Singleton('aaa')
    s2 = Singleton('bbb')
    if s1 is s2:
        print(id(s1), id(s2))
        print(s1.get_name())
        print(s2.get_name())
    else:
        print('s1 is NOT s2')
Beispiel #5
0
    def operacion(self):
        print("Ejemplo Singleton")
        x = Singleton.get_instance()
        y = Singleton.get_instance()

        print(x is y)

        y.set_value(10)

        print(x.get_value())
Beispiel #6
0
    def CalculateOrderQuantity(self, symbol, target):
        Singleton.readjust_allocation()
        global_current = Singleton.Portfolio[symbol].Quantity
        local_current = self.Portfolio[symbol].Quantity
        global_order = Singleton.CalculateOrderQuantity(
            symbol, self.Allocation * target)
        global_target = global_order + global_current
        local_order = global_target - local_current

        return local_order
    def __init__(self):
        Singleton.__init__(self)
        self.__models__ = {}
        self.__logic__ = {}
        self.__sensors__ = {}
        self.users = {}
        self.__notification_data__ = []
        self.__t__ = None

        self.default_sensor_logic = SensorLogic
 def test_inheritance(self):
     main_singleton1 = Singleton()
     main_singleton2 = Singleton()
     next_singleton1 = SubSingleton1()
     next_singleton2 = SubSingleton1()
     last_singleton1 = SubSingleton2()
     last_singleton2 = SubSingleton2()
     self.assertTrue(main_singleton1 is not next_singleton1)
     self.assertTrue(main_singleton1 is not last_singleton1)
     self.assertTrue(next_singleton1 is not last_singleton1)
     self.assertTrue(main_singleton1 is main_singleton2)
     self.assertTrue(next_singleton1 is next_singleton2)
     self.assertTrue(last_singleton1 is last_singleton2)
Beispiel #9
0
    def set_operacion(self):
        print("Ejmeplo con Singleton")
        x = Singleton.get_instance()
        y = Singleton.get_instance()

        print(x is y)

        y.set_value(10)

        print(x.get_value())

        print(y.get_value())

        print(x is y)
Beispiel #10
0
 def AddOrder(self, order):
     Singleton.Debug(f"Portfolio.AddOrder: {order}")
     Singleton.Log(f"Order size: {order.Quantity}")
     Singleton.Log(
         f"isclose({order.Quantity}, 0, abs_tol={Singleton.Securities[order.Symbol].SymbolProperties.LotSize})"
     )
     if isclose(order.Quantity,
                0,
                abs_tol=Singleton.Securities[
                    order.Symbol].SymbolProperties.LotSize):
         Singleton.Log(
             "Warning: Avoiding submitting order that has zero quantity.")
         return
     Singleton.Debug(f"AddOrder: {order}")
     self.__orders.append(order)
        def create_singleton(self):
            print("\nbefore creating singleton")
            new_singleton = Singleton()
            time.sleep(1)
            print("\nafter creating singleton")

            return new_singleton
Beispiel #12
0
    def OnWarmupFinished(self):
        Singleton.Debug("OnWarmupFinished")

        if self.LiveMode:
            Singleton.Broker.ImportFromBroker()

            self.__initial_value = Singleton.Portfolio.TotalPortfolioValue
            self.Log(f"setting initial value to {self.__initial_value}")

        self.__cost = 0.0
        for i in self.__algorithms:
            # TypeError : unsupported operand type(s) for -=: 'Cash' and 'CashAmount'
            Singleton.Broker.Portfolio.Cash -= i.Portfolio.Cash
            for symbol, position in i.Portfolio.items():
                Singleton.Broker.Portfolio[
                    symbol].Quantity -= position.Quantity

            cost = i.Allocation * self.__initial_value
            i.Portfolio.SetCash(cost)
            self.__cost += i.Portfolio.TotalPortfolioValue

        self.__initial_cost = self.__cost

        for i in self.__algorithms:
            i.OnWarmupFinished()
Beispiel #13
0
 def testInherited(self):
     s = Singleton()
     ss1 = SubSingleton()
     ss2 = SubSingleton()
     self.assertEquals(id(ss1), id(ss2))
     self.assertEquals(id(ss1), id(s))
     self.assertTrue(ss1 is ss2)
     self.assertTrue(ss1 is s)
Beispiel #14
0
    def __init__(self):
        Singleton.__init__(self)
        # self.config = {}
        # self.task_thread = TaskThread()
        self.taskMng = TaskMng()
        self.eventMng = EventMngr()

        self.tid = thread.get_ident()
        # self.workers =
        # 工作计算成员 池
        # 分配器、调度器
        # 注意它的执行线程
        self.subjectTask = Subject()
        self.__taskId = 0
        self.__valid = True
        self.__event = threading.Event()
        self.__retList = []
Beispiel #15
0
def main():
    chess = Singleton().chess

    root = tk.Tk()
    root.title("Chess")
    gui = GUI(root, chess)
    gui.pack()
    root.mainloop()
    def test_serialization(self):
        def deserializable(self):
            with open("object", 'rb') as file:
                return pickle.load(file)

        singleton = Singleton()

        with open("object", 'wb') as file:
            pickle.dump(singleton, file, pickle.DEFAULT_PROTOCOL)

        singleton.variable = 2

        pool = ThreadPool(2)
        instances = pool.map(deserializable, range(2))

        self.assertTrue(instances[0] is instances[1])
        self.assertTrue(singleton.variable == None)
Beispiel #17
0
    def HandleOrderEvent(self, order_event):
        Singleton.Debug(f"> HandleOrderEvent (1): OrderEvent: {order_event}")
        order = self._submitted.pop(order_event.OrderId, None)
        if not order:
            Singleton.Debug(
                f"Could not find order id {order_event.OrderId} in queue: {self._submitted}"
            )
            return

        Singleton.Debug(f"> HandleOrderEvent (2): Order: {order}")
        if Helper.is_order_done(order_event.Status):
            order.Portfolio.ProcessFill(order_event, order)
            order.Portfolio.Algorithm.OnOrderEvent(order_event)
            order.Portfolio.Algorithm.TotalOrders += 1

        else:
            # Re-add orders that are still open.
            self._submitted[order_event.OrderId] = order
Beispiel #18
0
    def test_Singleton(self):

        s = Singleton()
        self.assertEqual(s.cid, None)
        s.set_id(1)
        self.assertEqual(s.cid, 1)

        s2 = Singleton()
        self.assertEqual(s2.cid, 1)

        s2.set_id(2)
        self.assertEqual(s.cid, 2)
Beispiel #19
0
def SetupSingleton(securities=None,
                   brokerage_portfolio=None,
                   default_order_status=OrderStatus.Submitted):
    qc = QCAlgorithm(default_order_status=default_order_status)
    if securities is not None:
        qc.Securities = InternalSecurityManager(securities)

    if brokerage_portfolio is not None:
        qc.Portfolio = brokerage_portfolio

    Singleton.Setup(qc, broker=Broker())
Beispiel #20
0
    def setUp(self):
        self.qc = QCAlgorithm()
        Singleton.Setup(self.qc)
        self.qc.Initialize()
        self.qc.Securities = InternalSecurityManager([(FOO, 5), (BAR, 50)])

        self.algorithm1 = Algorithm(name="alg1", allocation=1.0)
        foo = self.algorithm1.AddEquity(FOO, Resolution.Daily).Symbol
        bar = self.algorithm1.AddEquity(BAR, Resolution.Daily).Symbol
        self.algorithm1.Portfolio.SetCash(200)
        self.algorithm1.Portfolio[foo] = Position(FOO, 10, 5)
        self.algorithm1.Portfolio[bar] = Position(BAR, 3, 50)
Beispiel #21
0
class Database:

    #values needed to establish connection
    database_name = None
    database_user = None
    database_pass = None
    database_host = None
    database_handle = None

    def __init__(self, name=None, user=None, password=None, host=None):
        self.database_name = name
        self.database_user = user
        self.database_pass = password
        self.database_host = host
        self.database_handle = Singleton()

    def connect(self):
        conn = MySQLdb.connect(self.database_host, self.database_user, self.database_pass, self.database_name)
        self.database_handle.setInstance(conn)

    def execute(self, querybuilder):
        results = None
        director = QueryDirector(querybuilder)
        
        self.database_handle.getInstance().query(director.getQuery().strip())
        if (querybuilder.commitMethod() == 'commit'):
            results = self.database_handle.getInstance().commit()
        else:
            results = self.database_handle.getInstance().store_result()
        return results
Beispiel #22
0
def test_singleton_increment_and_decrement():
    """
        Test if the value inside the single will be the only one
        incremented or decremented.
    """

    base_singleton = Singleton()
    _singleton1 = Singleton()
    _singleton2 = Singleton()

    tests = [
        (_singleton1.increment, 1),
        (_singleton2.increment, 2),
        (_singleton1.decrement, 1),
        (_singleton2.decrement, 0),
        (_singleton1.decrement, 0),
        (_singleton2.increment, 1),
        (_singleton1.increment, 2),
        (_singleton2.increment, 2)
    ]

    for operation, value in tests:
        operation()
        assert base_singleton.value == value
Beispiel #23
0
    def OnEndOfDay(self):
        Singleton.Debug("OnEndOfDay: {}".format(Singleton.Time))
        for i in self.__algorithms:
            i.OnEndOfDay()

        is_new_year = self.Time.year != self.__year
        if is_new_year:
            self.__year = self.Time.year

        is_new_month = self.Time.month != self.__month
        if is_new_month:
            self.__month = self.Time.month

        if self.__plot_orders and is_new_month:
            for i in self.__algorithms:
                self.Plot('Orders', i.Name, i.TotalOrders)

        if is_new_year:
            self.ResetOrders()
            if self.__reset:
                self.ResetPlot()

        if self.__plot_every_n_days_i % self.__plot_every_n_days == 0:
            if self._benchmark:
                self.Plot('Annual Saw Tooth Returns', self._benchmark.Name,
                          self._benchmark.Performance)
                self.Plot('Strategy Equity', self._benchmark.Name,
                          self._benchmark.Performance * self.__initial_cost)

            accum = 0.0
            pos = 0
            for i in self.__algorithms:
                accum += i.Portfolio.TotalPortfolioValue
                pos += 1
                self.Plot('Annual Saw Tooth Returns', i.Name, i.Performance)
                if self.__plot_value:
                    self.Plot("Value", i.Name, i.Portfolio.TotalPortfolioValue)
                if self.__plot_allocation:
                    self.Plot("Allocation", i.Name,
                              round(100.0 * i.Allocation, 1))

        self.__plot_every_n_days_i += 1

        if self.__email_address:
            for i in self.__algorithms:
                if i.Email.HasContent:
                    i.Email.Send(f"{i.Name} (OnEndOfDay)")
Beispiel #24
0
    def testThreadSerialization(self):
        def deserializable():
            with open(fileName, 'rb') as f:
                return pickle.load(f)

        fileName = 'data.pickle'

        s1 = Singleton()

        with open(fileName, 'wb') as f:
            pickle.dump(s1, f, pickle.HIGHEST_PROTOCOL)

        t1 = ThreadPool(processes=1)
        t2 = ThreadPool(processes=1)

        self.assertTrue(
            t1.apply_async(deserializable).get() is t2.apply_async(
                deserializable).get())
Beispiel #25
0
 def SetWarmUp(self, period, resolution=Resolution.Daily):
     Singleton.SetWarmUpFromAlgorithm(period)
Beispiel #26
0
 def __init__(self, *args, **kwargs):
    Singleton.__init__( self )
Beispiel #27
0
 def __init__(self, name=None, user=None, password=None, host=None):
     self.database_name = name
     self.database_user = user
     self.database_pass = password
     self.database_host = host
     self.database_handle = Singleton()
Beispiel #28
0
 def test_qc_set_warmup_from_main(self):
     Singleton.SetWarmUp(444)
     self.assertEqual(Singleton._warm_up, 444)
Beispiel #29
0
 def test_qc_set_warmup_should_not_override_algorithm(self):
     self.algorithm1.SetWarmUp(123)
     self.algorithm2.SetWarmUp(321)
     Singleton.SetWarmUp(444)
     self.assertEqual(Singleton._warm_up, 321)
Beispiel #30
0
 def destroy(self):
     """
     destroys the existing configuration singleton object
     :return:
     """
     Singleton.purge(mkcfg)
Beispiel #31
0
 def Error(self, message):
     Singleton.Error("[%s] %s" % (self.Name, message))
Beispiel #32
0
 def Debug(self, message):
     Singleton.Debug("[%s] %s" % (self.Name, message))
Beispiel #33
0
 def Log(self, message):
     Singleton.Log("[%s] %s" % (self.Name, message))
Beispiel #34
0
def main():
  instance = Singleton.instance()
  print type(instance)
  instance = SpecializedSingleton.instance()
  print type(instance)
  return
Beispiel #35
0
 def OnOrderEvent(self, order_event):
     Singleton.Debug(f"> OnOrderEvent: {order_event}")
     Singleton.Broker.HandleOrderEvent(order_event)
Beispiel #36
0
 def OnSecuritiesChanged(self, changes):
     Singleton.Debug(f"OnSecuritiesChanged {changes}")
     for i in self.__algorithms:
         # Only call if there's a relevant stock in i
         i.OnSecuritiesChanged(changes)
Beispiel #37
0
 def OnDividend(self):
     Singleton.Debug("OnDividend")
     for i in self.__algorithms:
         i.OnDividend()