Пример #1
0
    def __init__(self, **kwargs):
        """ setMatchPattern - defaults to '' to match everything
            match pattern examples: '^[0-9]*$' is for digits only
                                    '^[0-9,A-Z]*$' is for digits and uppercase
            setMaxLength
            setText
OB        """

        kwargs['MatchPattern'] = kwargs.pop('MatchPattern', '')
        cs = kwargs.pop('CursorStyle', "inputbox-cursor")
        gs = kwargs.pop('StyleName', 'gwt-inputbox')

        ap = AbsolutePanel(StyleName="inputbox")
        self.tp = Grid(StyleName=gs, Width="100%", Height="100%",
                       CellPadding=0, CellSpacing=0)
        self.cursor = HTML(StyleName=cs)
        ap.add(self.tp)
        ap.add(self.cursor, 0, 0)
        self.cf = self.tp.getCellFormatter()

        FocusPanel.__init__(self, Widget=ap, **kwargs)

        self.addTableListener(self)
        self.addKeyboardListener(self)
        self.addFocusListener(self)

        self.word_selected_pos = 0
        self.ctimer = Timer(notify=self.cursorFlash)
        self.focusset = False
        self.cstate = False
        self._keypressListeners = []
Пример #2
0
    def __init__(self):

        # create the label and slider
        self.__label = Label('OFF')
        self.slider = slider = HorizontalSlider(0,
                                                5,
                                                step=1,
                                                StyleName="slider")
        slider.setDragable(True)
        slider.addControlValueListener(self)

        # put them in a hpanel
        self.hpanel = hpanel = HorizontalPanel(Spacing=10)
        hpanel.add(slider)
        hpanel.add(self.__label)

        # create the color panel and give it color
        self.colorpanel = CaptionPanel('Color:',
                                       SimplePanel(StyleName='colorpanel'))
        self.randomcolor()

        # we're initially off
        self.value = 0
        # create our timer
        self.timer = Timer(notify=self)
Пример #3
0
    def __init__(self, widget, action, fps=50):
        self.widget = widget
        self.action = action
        self.fps = fps

        self.timer = Timer(0, self)
        self.timer.scheduleRepeating(int(1000.0 / fps))
Пример #4
0
    def draw(self):
        colour = "#000000"
        beta = 2 * math.pi / self.numSectors

        pathParams = {
            'stroke': colour,
            'stroke-width': self.width,
            'stroke-linecap': "round"
        }

        for i in range(self.numSectors):
            alpha = beta * i - math.pi / 2
            cos = math.cos(alpha)
            sin = math.sin(alpha)
            data = ','.join([
                'M',
                str(self.cx + self.r1 * cos),
                str(self.cy + self.r1 * sin), 'L',
                str(self.cx + self.r2 * cos),
                str(self.cy + self.r2 * sin)
            ])
            path = self.canvas.path(data=data, attrs=pathParams)
            self.opacity.append(1.0 * i / self.numSectors)
            self.sectors.append(path)

        period = 1000 / self.numSectors
        self._timer = Timer(notify=self)
        self._timer.scheduleRepeating(period)
Пример #5
0
    def onClick(self, sender):
        self.check_adjusts(sender)
        if sender == self.reset_constants:
            self.TD_CONSTS = self.ONES_CONSTS
            self.sync_consts()

        if sender == self.increase_depth:
            self.depth_limit += 1
            self.depth_label.setText("Current depth is " +
                                     str(self.depth_limit) + ".")

        if sender == self.decrease_depth:
            self.depth_limit -= 1
            self.depth_label.setText("Current depth is " +
                                     str(self.depth_limit) + ".")

        if sender == self.train_td:
            self.state = State()

            self.static_ai_str = '2'
            self.td_ai_str = '1'

            self.state.next_piece = [1, 1, 1]
            Timer(250, notify=self.td_ai_turn)

        if sender == self.train_static:
            self.state = State()

            self.static_ai_str = '1'
            self.td_ai_str = '2'

            self.state.next_piece = [1, 1, 1]
            Timer(250, notify=self.static_ai_turn)
Пример #6
0
Файл: Feed.py Проект: Afey/pyjs
class Feed:

    def __init__(self, url, callback):
        global frameId
        frame = DOM.createElement("iframe")
        frameid = "__pygwt_feedFrame%d" % frameId
        frameId += 1
        DOM.setAttribute(frame, "id", frameid)
        DOM.setAttribute(frame, "src", url)
        #DOM.setStyleAttribute(frame, 'width', '0')
        #DOM.setStyleAttribute(frame, 'height', '0')
        #DOM.setStyleAttribute(frame, 'border', '0')
        #DOM.setStyleAttribute(frame, 'position', 'absolute')
        self.frameId = frameId
        self.frame = frame
        self.timer = Timer(notify=self)
        doc().parent.body.appendChild(frame)
        self.callback = callback
        self.timer.scheduleRepeating(100)

    def getFrameTxt(self):
        return str(self.frame.contentWindow.document.body.innerHTML)

    def onTimer(self, *args):
        txt = self.getFrameTxt()
        if txt == '':
            return
        self.callback(self, txt)
        self.timer.cancel()
class Feed:
    def __init__(self, url, callback):
        global frameId
        frame = DOM.createElement("iframe")
        frameid = "__pygwt_feedFrame%d" % frameId
        frameId += 1
        DOM.setAttribute(frame, "id", frameid)
        DOM.setAttribute(frame, "src", url)
        #DOM.setStyleAttribute(frame, 'width', '0')
        #DOM.setStyleAttribute(frame, 'height', '0')
        #DOM.setStyleAttribute(frame, 'border', '0')
        #DOM.setStyleAttribute(frame, 'position', 'absolute')
        self.frameId = frameId
        self.frame = frame
        self.timer = Timer(notify=self)
        doc().parent.body.appendChild(frame)
        self.callback = callback
        self.timer.scheduleRepeating(100)

    def getFrameTxt(self):
        return str(self.frame.contentWindow.document.body.innerHTML)

    def onTimer(self, *args):
        txt = self.getFrameTxt()
        if txt == '':
            return
        self.callback(self, txt)
        self.timer.cancel()
Пример #8
0
 def __init__(self, max_tries = 10, interval = 500):
     Timer.__init__(self)
     self.interval = interval
     self.max_tries = max_tries
     self.tries = 0
     self.func = func
     self.params = params
     self.scheduleRepeating(self.interval)
Пример #9
0
 def __init__(self, symbol_shape, message_symbol_coder,
              symbol_signal_coder):
     self.timer = Timer(notify=self)
     self.setTimer(self.timer)
     self.symbol_shape = symbol_shape
     self.message_symbol_coder = message_symbol_coder
     self.symbol_signal_coder = symbol_signal_coder
     self.decoded = {}
Пример #10
0
 def __init__(self, countdown=1000):
     Timer.__init__(self)
     Label.__init__(self)
     self.countdown = countdown
     self.task_id = None
     self.wait_cnt = 0
     self.remote_py = \
         EchoServicePython(server="flask", flask_view_type="celery")
Пример #11
0
 def __init__(self, countdown=1000):
     Timer.__init__(self)
     Label.__init__(self)
     self.countdown = countdown
     self.task_id = None
     self.wait_cnt = 0
     self.remote_py = \
         EchoServicePython(server="flask", flask_view_type="celery")
Пример #12
0
    def start_game(self, view):
        self.view = view
        self.model.start_game(view)
        self.model.reset()

        #setup a timer
        self.timer = Timer(notify=self.update)
        self.timer.scheduleRepeating(1000 / FPS)
Пример #13
0
class Spinner(SimplePanel):
    """ Our testing panel.
    """
    def __init__(self, width=600, height=300):
        """ Standard initialiser.
        """
        SimplePanel.__init__(self)

        # Taken from the "spinner" Raphael demo:
        self.width = 15
        self.r1 = 35
        self.r2 = 60
        self.cx = self.r2 + self.width
        self.cy = self.r2 + self.width
        self.numSectors = 12
        self.canvas = Raphael(self.r2 * 2 + self.width * 2,
                              self.r2 * 2 + self.width * 2)
        self.sectors = []
        self.opacity = []
        self.add(self.canvas)

    def draw(self):
        colour = "#000000"
        beta = 2 * math.pi / self.numSectors

        pathParams = {
            'stroke': colour,
            'stroke-width': self.width,
            'stroke-linecap': "round"
        }

        for i in range(self.numSectors):
            alpha = beta * i - math.pi / 2
            cos = math.cos(alpha)
            sin = math.sin(alpha)
            data = ','.join([
                'M',
                str(self.cx + self.r1 * cos),
                str(self.cy + self.r1 * sin), 'L',
                str(self.cx + self.r2 * cos),
                str(self.cy + self.r2 * sin)
            ])
            path = self.canvas.path(data=data, attrs=pathParams)
            self.opacity.append(1.0 * i / self.numSectors)
            self.sectors.append(path)

        period = 1000 / self.numSectors
        self._timer = Timer(notify=self)
        self._timer.scheduleRepeating(period)

    def onTimer(self, timerID):
        """ Respond to our timer firing.
        """
        self.opacity.insert(0, self.opacity.pop())
        for i in range(self.numSectors):
            self.sectors[i].setAttr("opacity", self.opacity[i])
Пример #14
0
class Spinner(PopupPanel):
    def __init__(self, text=''):
        PopupPanel.__init__(self)

        self.width       = 15
        self.r1          = 35
        self.r2          = 60
        self.cx          = self.r2 + self.width
        self.cy          = self.r2 + self.width
        self.numSectors  = 12
        self.size        = self.r2*2 + self.width*2
        self.speed       = 1.5  # seconds per rotation
        self._timer      = None

        self.canvas = Raphael(self.size, self.size)
        self.sectors = []
        self.opacity = []
        vp = VerticalPanel()
        vp.add(self.canvas)
        blurb = HTML(text)
        blurb.setStyleAttribute('text-align', 'center')
        vp.add(blurb)
        self.add(vp)


    def draw(self):
        colour           = "#000000"
        beta             = 2 * math.pi / self.numSectors

        pathParams = {'stroke'         : colour,
                      'stroke-width'   : self.width,
                      'stroke-linecap' : "round"}

        for i in range(self.numSectors):
            alpha = beta * i - math.pi/2
            cos   = math.cos(alpha)
            sin   = math.sin(alpha)
            data  = ','.join(['M',
                              str(self.cx + self.r1 * cos),
                              str(self.cy + self.r1 * sin),
                              'L',
                              str(self.cx + self.r2 * cos),
                              str(self.cy + self.r2 * sin)])
            path  = self.canvas.path(data=data, attrs=pathParams)
            self.opacity.append(1.0 * i / self.numSectors )
            self.sectors.append(path)

        period = (self.speed * 1000) / self.numSectors
        self._timer = Timer(notify=self)
        self._timer.scheduleRepeating(period)        


    def onTimer(self, _):
        self.opacity.insert(0, self.opacity.pop())
        for i in range(self.numSectors):
            self.sectors[i].setAttr("opacity", self.opacity[i])
Пример #15
0
def delay(s):
    if STATMODE:
        return  # NO TIME FOR SLEEP IN STATMODE
    if USING_PYGAME:
        from time import sleep

        sleep(s)
    else:
        from pyjamas.Timer import Timer

        timer = Timer(notify=update)
        timer.schedule(s * 1000)
Пример #16
0
    def __init__(self):

        # the button
        self.button = Button(listener=self)
        # set an attr on the button to keep track of its state
        self.button.stop = False
        # date label
        self.datelabel = Label(StyleName='clock')
        # the timer
        self.timer = Timer(notify=self.updateclock)
        # kick start
        self.onClick(self.button)
Пример #17
0
    def __init__(self, countdown):
        # It's a Timer, no it's a Button, WAIT!  It's BOTH!!
        Timer.__init__(self)
        Button.__init__(self)

        # save the countdown value
        self.countdown_save = countdown
        # this instance handles the clicks
        self.addClickListener(self)
        # the box the popups go into
        self.box = SimplePanel(StyleName='popupbox')
        # kickstart
        self.reset()
Пример #18
0
    def __init__(self, countdown):
        # It's a Timer, no it's a Button, WAIT!  It's BOTH!!
        Timer.__init__(self)
        Button.__init__(self)

        # save the countdown value
        self.countdown_save = countdown
        # this instance handles the clicks
        self.addClickListener(self)
        # the box the popups go into
        self.box = SimplePanel(StyleName='popupbox')
        # kickstart
        self.reset()
Пример #19
0
class TestPanel(SimplePanel):
    """ Our testing panel.
    """
    def __init__(self):
        """ Standard initialiser.
        """
        SimplePanel.__init__(self)

        # Taken from the "spinner" Raphael demo:

        colour = "#000000"
        width = 15
        r1 = 35
        r2 = 60
        cx = r2 + width
        cy = r2 + width
        self.numSectors = 12
        self.canvas = Raphael(r2 * 2 + width * 2, r2 * 2 + width * 2)
        self.sectors = []
        self.opacity = []
        beta = 2 * math.pi / self.numSectors

        pathParams = {
            'stroke': colour,
            'stroke-width': width,
            'stroke-linecap': "round"
        }

        for i in range(self.numSectors):
            alpha = beta * i - math.pi / 2
            cos = math.cos(alpha)
            sin = math.sin(alpha)
            path = self.canvas.path(data=None, attrs=pathParams)
            path.moveTo(cx + r1 * cos, cy + r1 * sin)
            path.lineTo(cx + r2 * cos, cy + r2 * sin)
            self.opacity.append(1 / self.numSectors * i)
            self.sectors.append(path)

        period = 1000 / self.numSectors

        self._timer = Timer(notify=self)
        self._timer.scheduleRepeating(period)

        self.add(self.canvas)

    def onTimer(self, timer):
        """ Respond to our timer firing.
        """
        self.opacity.insert(0, self.opacity.pop())
        for i in range(self.numSectors):
            self.sectors[i].setAttr("opacity", self.opacity[i])
Пример #20
0
Файл: test.py Проект: Afey/pyjs
class TestPanel(SimplePanel):
    """ Our testing panel.
    """
    def __init__(self):
        """ Standard initialiser.
        """
        SimplePanel.__init__(self)

        # Taken from the "spinner" Raphael demo:

        colour           = "#000000"
        width            = 15
        r1               = 35
        r2               = 60
        cx               = r2 + width
        cy               = r2 + width
        self.numSectors  = 12
        self.canvas      = Raphael(r2*2 + width*2, r2*2 + width*2)
        self.sectors     = []
        self.opacity     = []
        beta             = 2 * math.pi / self.numSectors

        pathParams = {'stroke'         : colour,
                      'stroke-width'   : width,
                      'stroke-linecap' : "round"}

        for i in range(self.numSectors):
            alpha = beta * i - math.pi/2
            cos   = math.cos(alpha)
            sin   = math.sin(alpha)
            path  = self.canvas.path(data=None, attrs=pathParams)
            path.moveTo(cx + r1 * cos, cy + r1 * sin)
            path.lineTo(cx + r2 * cos, cy + r2 * sin)
            self.opacity.append(1 / self.numSectors * i)
            self.sectors.append(path)

        period = 1000/self.numSectors

        self._timer = Timer(notify=self)
        self._timer.scheduleRepeating(period)

        self.add(self.canvas)


    def onTimer(self, timer):
        """ Respond to our timer firing.
        """
        self.opacity.insert(0, self.opacity.pop())
        for i in range(self.numSectors):
            self.sectors[i].setAttr("opacity", self.opacity[i])
Пример #21
0
def queuereduce(sender, maxlines=1000):
    showOutputMeta("Reducing...")

    outputPanel.add(HTML(" "))
    outputPanel.add(HTML(" "))
    outputPanel.add(
        HTML("""
    <p>Takes too long? Try the <a href="https://bitbucket.org/bgeron
    </continuation-calculus-paper/">Python evaluator.</a>.</p>
    """.strip()))

    # Schedule reduceterm(maxlines) really soon.
    timer = Timer(notify=functools.partial(reduceterm, maxlines=maxlines))
    timer.schedule(50)  # after 50 milliseconds
Пример #22
0
class Animate(object):
    def __init__(self, widget, action, fps=50):
        self.widget = widget
        self.action = action
        self.fps = fps

        self.timer = Timer(0, self)
        self.timer.scheduleRepeating(int(1000.0 / fps))

    def onTimer(self, sender):
        params = self.action(self.widget)
        if not params:
            self.timer.cancel()
            return
Пример #23
0
 def __init__(self):
     self.dropTargets = []
     self.dragging = NOT_DRAGGING
     self.dragBusy = False
     self._currentTargetElement = None
     self.previousDropTarget = None
     self.draggingImage = None
     self.origMouseX = 0
     self.origMouseY = 0
     self.currentDragOperation = 'none'
     self.data = None
     self.returnTimer = Timer(notify=self.onReturningWidget)
     self.mouseEvent = None
     self.dragDataStore = None
Пример #24
0
class Animate(object):

    def __init__(self, widget, action, fps=50):
        self.widget = widget
        self.action = action
        self.fps = fps

        self.timer = Timer(0, self)
        self.timer.scheduleRepeating(int(1000.0/fps))

    def onTimer(self, sender):
        params = self.action(self.widget)
        if not params:
            self.timer.cancel()
            return
Пример #25
0
class Clock:

    # pyjamas doesn't generate __doc__
    __doc__ = '''This demonstrates using Timer instantiated with the
    notify keyword, as in:<pre> timer = Timer(notify=func) </pre>When
    the timer fires it will call func() with no arguments (or
    <code>self</code> if it is a bound method as in this example).
    This timer is scheduled with the <code>scheduleRepeating()</code>
    method, so after func() is called, it is automatically rescheduled
    to fire again after the specified period.  The timer can be
    cancelled by calling the <code>cancel()</code> method; this
    happens when you click on the button.
    '''

    
    start_txt = 'Click to start the clock'
    stop_txt = 'Click to stop the clock'
    
    def __init__(self):

        # the button
        self.button = Button(listener=self)
        # set an attr on the button to keep track of its state
        self.button.stop = False
        # date label
        self.datelabel = Label(StyleName='clock')
        # the timer
        self.timer = Timer(notify=self.updateclock)
        # kick start
        self.onClick(self.button)

    def onClick(self, button):
        if self.button.stop:
            # we're stopping the clock
            self.button.stop = False
            self.timer.cancel()
            self.button.setText(self.start_txt)
        else:
            # we're starting the clock
            self.button.stop = True
            self.timer.scheduleRepeating(1000)
            self.button.setText(self.stop_txt)

    def updateclock(self, timer):

        # the callable attached to the timer with notify
        dt = datetime.now().replace(microsecond=0)
        self.datelabel.setText(dt.isoformat(' '))
Пример #26
0
 def __init__(self, symbol_shape, message_symbol_coder, symbol_signal_coder):
   self.timer = Timer(notify=self)
   self.setTimer(self.timer)
   self.symbol_shape = symbol_shape
   self.message_symbol_coder = message_symbol_coder
   self.symbol_signal_coder = symbol_signal_coder
   self.decoded = {}
Пример #27
0
 def initElement(self):
     # Most browsers don't like setting designMode until slightly _after_
     # the iframe becomes attached to the DOM. Any non-zero timeout will do
     # just fine.
     print "initElement"
     self.onElementInitializing()
     Timer(50, self)
Пример #28
0
    def __init__(self, widget, action, fps=50):
        self.widget = widget
        self.action = action
        self.fps = fps

        self.timer = Timer(0, self)
        self.timer.scheduleRepeating(int(1000.0/fps))
Пример #29
0
    def td_ai_turn(self):
        print "\n\nTD AI player starting turn. TD AI places the piece:", self.state.next_piece[
            2]
        print "TD_CONSTS after being adjusted are: ", self.TD_CONSTS

        # print, alpha-beta search etc.:
        (expectedUtility, state) = ab(self.state,
                                      self.TD_CONSTS,
                                      depth_limit=self.depth_limit)
        terminal_state = expectedUtility.terminal
        self.TD_CONSTS = td_learning(terminal_state, self.TD_CONSTS,
                                     self.state)
        self.sync_consts()  # reflect the new TD_CONSTS in the game.

        last_position = find_last_move(self.state, state)

        self.state = state

        state.printInfo()

        print "TD_CONSTS after being adjusted are: ", self.TD_CONSTS

        over = self.check_is_win(last_position)
        print "back in td"
        print "Is over ", over
        if not over:
            return Timer(250, notify=self.static_ai_turn)
        else:
            return True
Пример #30
0
    def draw(self):
        colour           = "#000000"
        beta             = 2 * math.pi / self.numSectors

        pathParams = {'stroke'         : colour,
                      'stroke-width'   : self.width,
                      'stroke-linecap' : "round"}

        for i in range(self.numSectors):
            alpha = beta * i - math.pi/2
            cos   = math.cos(alpha)
            sin   = math.sin(alpha)
            data  = ','.join(['M',
                              str(self.cx + self.r1 * cos),
                              str(self.cy + self.r1 * sin),
                              'L',
                              str(self.cx + self.r2 * cos),
                              str(self.cy + self.r2 * sin)])
            path  = self.canvas.path(data=data, attrs=pathParams)
            self.opacity.append(1.0 * i / self.numSectors )
            self.sectors.append(path)

        period = (self.speed * 1000) / self.numSectors
        self._timer = Timer(notify=self)
        self._timer.scheduleRepeating(period)        
Пример #31
0
    def onDrop(self, event):
        dt = event.dataTransfer

        item = dt.getData("Text")
        data = json.decode(item)
        if 'name' in data and 'age' in data:
            age = data['age']
            name = data['name']
            self.removeStyleName('dragover')
            if self.age_is_ok(age):
                self.addStudent(name, age)
                dt.dropEffect = 'copy'

                self.addStyleName('flash')

                def removeFlash(timer):
                    self.removeStyleName('flash')

                Timer(250, notify=removeFlash)
            else:
                dt.dropEffect = 'none'
                self.addMessage('student could not be added')
                # setting dropEffect to 'none' should be sufficient to notify
                # that the drop failed, but
                # we need to cheat a bit for now...
                # this is the only reason for parent id in data
                item_parent_id = data['parent']
                item_parent = self.parent.containerFromId(item_parent_id)
                item_parent.addStyleName('drop_fail')
            # prevent default allows onDragEnd to see the dropEffect we set here
        DOM.eventPreventDefault(event)
Пример #32
0
class Spinner(SimplePanel):
    """ Our testing panel.
    """
    def __init__(self,width=600,height=300):
        """ Standard initialiser.
        """
        SimplePanel.__init__(self)

        # Taken from the "spinner" Raphael demo:
        self.width            = 15
        self.r1               = 35
        self.r2               = 60
        self.cx               = self.r2 + self.width
        self.cy               = self.r2 + self.width
        self.numSectors  = 12
        self.canvas      = Raphael(self.r2*2 + self.width*2, self.r2*2 + self.width*2)
        self.sectors     = []
        self.opacity     = []
        self.add(self.canvas)

    def draw(self):
        colour           = "#000000"
        beta             = 2 * math.pi / self.numSectors

        pathParams = {'stroke'         : colour,
                      'stroke-width'   : self.width,
                      'stroke-linecap' : "round"}

        for i in range(self.numSectors):
            alpha = beta * i - math.pi/2
            cos   = math.cos(alpha)
            sin   = math.sin(alpha)
            data=','.join(['M',str(self.cx + self.r1 * cos),str(self.cy + self.r1 * sin),'L',str(self.cx + self.r2 * cos),str(self.cy + self.r2 * sin)])
            path  = self.canvas.path(data=data,attrs=pathParams)
            self.opacity.append(1.0 * i / self.numSectors )
            self.sectors.append(path)

        period = 1000/self.numSectors
        self._timer = Timer(notify=self)
        self._timer.scheduleRepeating(period)        

    def onTimer(self, timerID):
        """ Respond to our timer firing.
        """
        self.opacity.insert(0, self.opacity.pop())
        for i in range(self.numSectors):
            self.sectors[i].setAttr("opacity", self.opacity[i])
Пример #33
0
class Clock:

    # pyjamas doesn't generate __doc__
    __doc__ = '''This demonstrates using Timer instantiated with the
    notify keyword, as in:<pre> timer = Timer(notify=func) </pre>When
    the timer fires it will call func() with no arguments (or
    <code>self</code> if it is a bound method as in this example).
    This timer is scheduled with the <code>scheduleRepeating()</code>
    method, so after func() is called, it is automatically rescheduled
    to fire again after the specified period.  The timer can be
    cancelled by calling the <code>cancel()</code> method; this
    happens when you click on the button.
    '''

    start_txt = 'Click to start the clock'
    stop_txt = 'Click to stop the clock'

    def __init__(self):

        # the button
        self.button = Button(listener=self)
        # set an attr on the button to keep track of its state
        self.button.stop = False
        # date label
        self.datelabel = Label(StyleName='clock')
        # the timer
        self.timer = Timer(notify=self.updateclock)
        # kick start
        self.onClick(self.button)

    def onClick(self, button):
        if self.button.stop:
            # we're stopping the clock
            self.button.stop = False
            self.timer.cancel()
            self.button.setText(self.start_txt)
        else:
            # we're starting the clock
            self.button.stop = True
            self.timer.scheduleRepeating(1000)
            self.button.setText(self.stop_txt)

    def updateclock(self, timer):

        # the callable attached to the timer with notify
        dt = datetime.now().replace(microsecond=0)
        self.datelabel.setText(dt.isoformat(' '))
def queuereduce(sender, maxlines=1000):
    showOutputMeta("Reducing...")

    outputPanel.add(HTML("&nbsp;"))
    outputPanel.add(HTML("&nbsp;"))
    outputPanel.add(
        HTML(
            """
    <p>Takes too long? Try the <a href="https://bitbucket.org/bgeron
    </continuation-calculus-paper/">Python evaluator.</a>.</p>
    """.strip()
        )
    )

    # Schedule reduceterm(maxlines) really soon.
    timer = Timer(notify=functools.partial(reduceterm, maxlines=maxlines))
    timer.schedule(50)  # after 50 milliseconds
Пример #35
0
class Tooltip(PopupPanel):
    def __init__(self, sender, offsetX, offsetY, contents,
                       show_delay, hide_delay, styleName, **kwargs):
        """ contents may be a text string or it may be a widget
        """
        PopupPanel.__init__(self, True, **kwargs)
        self.show_delay = show_delay
        self.hide_delay = hide_delay
        
        if isinstance(contents, basestring):
            contents = HTML(contents)
        self.add(contents)

        left = sender.getAbsoluteLeft() + offsetX
        top = sender.getAbsoluteTop() + offsetY

        self.setPopupPosition(left, top)
        self.setStyleName(styleName)

        if tooltip_hide_timer:
            self.tooltip_show_timer = Timer(1, self)
        else:
            self.tooltip_show_timer = Timer(self.show_delay, self)
        
    def show(self):
        global tooltip_hide_timer
        
        # activate fast tooltips
        tooltip_hide_timer = Timer(self.hide_delay, self)
        PopupPanel.show(self)

    def hide(self, autoClosed=False):
        self.tooltip_show_timer.cancel()
        PopupPanel.hide(self, autoClosed)

    def onTimer(self, timer):
        global tooltip_hide_timer

        # deactivate fast tooltips on last timer
        if timer is tooltip_hide_timer:
            tooltip_hide_timer = None

        if timer is self.tooltip_show_timer:
            self.show()
        else:
            self.hide()
Пример #36
0
 def onTimer(self, t):
     count = 0
     while count < 10 and self.index < len(self.items):
         self._add_items(self.index)
         self.index += 1
         count += 1
     if self.index < len(self.items):
         Timer(1, self)
 def __init__(self, url, callback):
     global frameId
     frame = DOM.createElement("iframe")
     frameid = "__pygwt_feedFrame%d" % frameId
     frameId += 1
     DOM.setAttribute(frame, "id", frameid)
     DOM.setAttribute(frame, "src", url)
     #DOM.setStyleAttribute(frame, 'width', '0')
     #DOM.setStyleAttribute(frame, 'height', '0')
     #DOM.setStyleAttribute(frame, 'border', '0')
     #DOM.setStyleAttribute(frame, 'position', 'absolute')
     self.frameId = frameId
     self.frame = frame
     self.timer = Timer(notify=self)
     doc().parent.body.appendChild(frame)
     self.callback = callback
     self.timer.scheduleRepeating(100)
Пример #38
0
    def start_game(self, view):
        self.view = view
        self.model.start_game(view)
        self.model.reset()

        #setup a timer
        self.timer = Timer(notify=self.update)
        self.timer.scheduleRepeating(1000/FPS)
Пример #39
0
    def __init__(self):
        Composite.__init__(self)

        self.albums = []
        self.photos = []
        self.grid = Grid(4, 4, CellPadding=4, CellSpacing=4)
        self.grid.addTableListener(self)
        self.drill = 0
        self.pos = 0
        self.up = Button("Up", self)
        self.next = Button("Next", self)
        self.prev = Button("Prev", self)
        self.timer = Timer(notify=self)
        self.userid = "jameskhedley"
        self.album_url = "http://picasaweb.google.com/data/feed/base/user/" + self.userid + "?alt=json-in-script&kind=album&hl=en_US&callback=restCb"
        self.doRESTQuery(self.album_url, self.timer)

        self.vp = VerticalPanel()
        self.disclosure = DisclosurePanel(
            "Click for boring technical details.")
        self.disclosure.add(
            HTML(
                '''<p>OK so you want to write client JS to do a RESTful HTTP query from picasa right?
				 Well you can't because of the Same Origin Policy. Basically this means that
				 because the domain of the query and the domain of the hosted site are different,
				 then that could well be a cross-site scripting (XSS) attack. So, the workaround is to
				 do the call from a script tag so the JSON we get back is part of the document.
				 But since we don't know what URL to hit yet, once we find out then we have to inject
				 a new script tag dynamically which the browser will run as soon as we append it.
				 To be honest I'm not 100% why Google use RESTful services and not JSON-RPC or somesuch,
				 which would be easier. Well, easier for me.'''))

        self.IDPanel = HorizontalPanel()
        self.IDPanel.add(Label("Enter google account:"))
        self.IDButton = Button("Go", self)

        self.IDBox = TextBox()
        self.IDBox.setText(self.userid)
        self.IDPanel.add(self.IDBox)
        self.IDPanel.add(self.IDButton)
        self.vp.add(self.IDPanel)
        self.vp.add(self.disclosure)
        self.vp.add(self.grid)

        self.initWidget(self.vp)
Пример #40
0
    def transfer_tinymce(self):

        new_script = DOM.createElement("script")
        new_script.innerHTML = """
var ed = tinyMCE.get('%s');
var data = ed.getContent({'format': 'raw'});
frame = document.getElementById('__edit_%s');
frame.innerText = data;
ed.save();
ed.remove();
""" % (self.editor_id, self.editor_id)

        self.editor_created = False

        DOM.setElemAttribute(new_script, "type","text/javascript")
        doc().body.appendChild(new_script)
        self.hide()
        t = Timer(notify=self)
        t.scheduleRepeating(1000)
Пример #41
0
    def transfer_tinymce(self):

        new_script = DOM.createElement("script")
        new_script.innerHTML = """
var ed = tinyMCE.get('%s');
var data = ed.getContent({'format': 'raw'});
frame = document.getElementById('__edit_%s');
frame.innerText = data;
ed.save();
ed.remove();
""" % (self.editor_id, self.editor_id)

        self.editor_created = False

        DOM.setElemAttribute(new_script, "type", "text/javascript")
        doc().body.appendChild(new_script)
        self.hide()
        t = Timer(notify=self)
        t.scheduleRepeating(1000)
Пример #42
0
    def onTimer(self, tid):
        for i in range(10):
            if self.test_idx >= len(self.test_methods):
                self.displayStats()
                self.test_idx = 'DONE'
                self.start_next_test()
                return

            self._run_test(self.test_methods[self.test_idx])
            self.test_idx += 1
        Timer(1, self)
Пример #43
0
 def check_start_next_test(self):
     if self.tests_outstanding is None:
         return
     if self.tests_outstanding == 0:
         if hasattr(self, 'lastTestsCheck'):
             self.lastTestsCheck()
         self.displayStats()
         self.start_next_test()
         return
     # do it again.
     Timer(100, self)
 def run(self):
     self.getTestMethods()
     if not IN_BROWSER:
         for test_method_name in self.test_methods:
             self._run_test(test_method_name)
         self.displayStats()
         if hasattr(self, "start_next_test"):
             self.start_next_test()
         return
     self.test_idx = 0
     Timer(10, self)
Пример #45
0
    def onDragEnd(self, event):
        dt = event.dataTransfer
        self.addMessage('Drop effect is "%s"' % dt.dropEffect)
        if dt.dropEffect != 'none':
            self.remove(self.movingWidget)
        else:
            # Restore widget visibility. Allow 0.5 seconds for the fly-back.
            def ontimer(timer):
                self.movingWidget.removeStyleName('invisible')

            Timer(500, notify=ontimer)
Пример #46
0
 def onSplitterResize(self, px):
     """ IE6/7 has event priority issues that will prevent
         the repaints from happening quickly enough causing the
         interaction to seem unresponsive.  The following is simply
         a poor man's mouse event coalescing.
     """
     resizeUpdatePeriod = 20  # ms
     if not self.isResizeInProgress:
         self.isResizeInProgress = True
         Timer(resizeUpdatePeriod, self)
     self.splitPosition = px
Пример #47
0
    def __init__(self):

        # the button
        self.button = Button(listener=self)
        # set an attr on the button to keep track of its state
        self.button.stop = False
        # date label
        self.datelabel = Label(StyleName='clock')
        # the timer
        self.timer = Timer(notify=self.updateclock)
        # kick start
        self.onClick(self.button)
Пример #48
0
class Controller:
    def __init__(self, model):
        self.model = model
        self.key_up = False
        self.key_down = False
        self.key_left = False
        self.key_right = False
        self.key_fire = False

    def start_game(self, view):
        self.view = view
        self.model.start_game(view)
        self.model.reset()

        #setup a timer
        self.timer = Timer(notify=self.update)
        self.timer.scheduleRepeating(1000/FPS)

    def update(self):
        self.keyboard_updates()
        self.model.update()

    def keyboard_updates(self):
        ship = self.model.ship

        drot = 0
        if self.key_left:
            drot -= ROTATE_SPEED
        if self.key_right:
            drot += ROTATE_SPEED
        if drot:
            ship.rotate_ship(drot)

        if self.key_up:
            ship.thrust()
        else:
            ship.friction()

        if self.key_fire:
            self.model.trigger_fire()
Пример #49
0
    def __init__(self, sender, offsetX, offsetY, contents,
                       show_delay, hide_delay, styleName, **kwargs):
        """ contents may be a text string or it may be a widget
        """
        PopupPanel.__init__(self, True, **kwargs)
        self.show_delay = show_delay
        self.hide_delay = hide_delay
        
        if isinstance(contents, basestring):
            contents = HTML(contents)
        self.add(contents)

        left = sender.getAbsoluteLeft() + offsetX
        top = sender.getAbsoluteTop() + offsetY

        self.setPopupPosition(left, top)
        self.setStyleName(styleName)

        if tooltip_hide_timer:
            self.tooltip_show_timer = Timer(1, self)
        else:
            self.tooltip_show_timer = Timer(self.show_delay, self)
Пример #50
0
 def __init__(self):
     self.dropTargets = []
     self.dragging = NOT_DRAGGING
     self.dragBusy = False
     self._currentTargetElement = None
     self.previousDropTarget = None
     self.draggingImage = None
     self.origMouseX = 0
     self.origMouseY = 0
     self.currentDragOperation = 'none'
     self.data = None
     self.returnTimer = Timer(notify=self.onReturningWidget)
     self.mouseEvent = None
     self.dragDataStore = None
	def __init__(self) :
		# Since this is a singleton, throw an exception if the constructor is called
		# explicitly.
		if DataRunManager._onlyInstance!=None :
			raise Exception( "DataRunManager is a singleton class. Call 'DataRunManager.instance()' to get the only running instance" )
		self.rpcService=GlibRPCService.instance()
		self.pollingTimer=Timer( notify=self.pollRPCService )
		self.eventHandlers = []
		self.fractionComplete = 1
		self.statusString = "Not taking data"
		self.firstRun = True
		# I'll poll once immediately on startup just in case the user is connecting to an
		# already running service. The code that handles the response to this starts the
		# timer running.
		self.pollRPCService()
Пример #52
0
Файл: Feed.py Проект: Afey/pyjs
 def __init__(self, url, callback):
     global frameId
     frame = DOM.createElement("iframe")
     frameid = "__pygwt_feedFrame%d" % frameId
     frameId += 1
     DOM.setAttribute(frame, "id", frameid)
     DOM.setAttribute(frame, "src", url)
     #DOM.setStyleAttribute(frame, 'width', '0')
     #DOM.setStyleAttribute(frame, 'height', '0')
     #DOM.setStyleAttribute(frame, 'border', '0')
     #DOM.setStyleAttribute(frame, 'position', 'absolute')
     self.frameId = frameId
     self.frame = frame
     self.timer = Timer(notify=self)
     doc().parent.body.appendChild(frame)
     self.callback = callback
     self.timer.scheduleRepeating(100)
Пример #53
0
    def __init__(self):
        Composite.__init__(self)

        self.albums = []
        self.photos = []
        self.grid = Grid(4, 4, CellPadding=4, CellSpacing=4)
        self.grid.addTableListener(self)
        self.drill = 0
        self.pos = 0
        self.up = Button("Up", self) 
        self.next = Button("Next", self) 
        self.prev = Button("Prev", self) 
        self.timer = Timer(notify=self)
        self.userid = "jameskhedley"
        self.album_url = "http://picasaweb.google.com/data/feed/base/user/" + self.userid + "?alt=json-in-script&kind=album&hl=en_US&callback=restCb"
        self.doRESTQuery(self.album_url, self.timer)

        self.vp = VerticalPanel()
        self.disclosure = DisclosurePanel("Click for boring technical details.") 
        self.disclosure.add(HTML('''<p>OK so you want to write client JS to do a RESTful HTTP query from picasa right?
				 Well you can't because of the Same Origin Policy. Basically this means that
				 because the domain of the query and the domain of the hosted site are different,
				 then that could well be a cross-site scripting (XSS) attack. So, the workaround is to
				 do the call from a script tag so the JSON we get back is part of the document. 
				 But since we don't know what URL to hit yet, once we find out then we have to inject
				 a new script tag dynamically which the browser will run as soon as we append it.
				 To be honest I'm not 100% why Google use RESTful services and not JSON-RPC or somesuch,
				 which would be easier. Well, easier for me.'''))
        
        self.IDPanel = HorizontalPanel()
        self.IDPanel.add(Label("Enter google account:"))
        self.IDButton = Button("Go", self)
        
        self.IDBox = TextBox()
        self.IDBox.setText(self.userid)
        self.IDPanel.add(self.IDBox)
        self.IDPanel.add(self.IDButton)
        self.vp.add(self.IDPanel)
        self.vp.add(self.disclosure)
        self.vp.add(self.grid)

        self.initWidget(self.vp)
Пример #54
0
    def __init__(self):
        """ Standard initialiser.
        """
        SimplePanel.__init__(self)

        # Taken from the "spinner" Raphael demo:

        colour           = "#000000"
        width            = 15
        r1               = 35
        r2               = 60
        cx               = r2 + width
        cy               = r2 + width
        self.numSectors  = 12
        self.canvas      = Raphael(r2*2 + width*2, r2*2 + width*2)
        self.sectors     = []
        self.opacity     = []
        beta             = 2 * math.pi / self.numSectors

        pathParams = {'stroke'         : colour,
                      'stroke-width'   : width,
                      'stroke-linecap' : "round"}

        for i in range(self.numSectors):
            alpha = beta * i - math.pi/2
            cos   = math.cos(alpha)
            sin   = math.sin(alpha)
            path  = self.canvas.path(pathParams)
            path.moveTo(cx + r1 * cos, cy + r1 * sin)
            path.lineTo(cx + r2 * cos, cy + r2 * sin)
            self.opacity.append(1 / self.numSectors * i)
            self.sectors.append(path)

        period = 1000/self.numSectors

        self._timer = Timer(listener=self)
        self._timer.scheduleRepeating(period)

        self.add(self.canvas)
Пример #55
0
    def __init__(self):

        # create the label and slider
        self.__label = Label('OFF')
        self.slider = slider = HorizontalSlider(0, 5, step=1,
                                                StyleName="slider")
        slider.setDragable(True)
        slider.addControlValueListener(self)

        # put them in a hpanel
        self.hpanel = hpanel = HorizontalPanel(Spacing=10)
        hpanel.add(slider)
        hpanel.add(self.__label)

        # create the color panel and give it color
        self.colorpanel = CaptionPanel('Color:',
                                       SimplePanel(StyleName='colorpanel'))
        self.randomcolor()

        # we're initially off
        self.value = 0
        # create our timer
        self.timer = Timer(notify=self)
Пример #56
0
class RandomColor:

    __doc__ = '''This last example demonstrates what most pyjamas
    programmers currently do with timers: create a Timer instance
    specifying <code>notify</code> with an object that has an
    <code>onTimer</code> attribute that is callable.  The slider on
    the left will adjust how often the middle panel changes color; it
    is either OFF or a value of seconds from 1 to 5.  Changing the
    slider immediately cancels the current timer and starts a new
    timer to change the color in the newly specified time.  Like the
    previous example, this timer reschedules itself (if it wasn't
    turned off) at the end of the call to <code>onTimer()</code>.
    '''

    def __init__(self):

        # create the label and slider
        self.__label = Label('OFF')
        self.slider = slider = HorizontalSlider(0, 5, step=1,
                                                StyleName="slider")
        slider.setDragable(True)
        slider.addControlValueListener(self)

        # put them in a hpanel
        self.hpanel = hpanel = HorizontalPanel(Spacing=10)
        hpanel.add(slider)
        hpanel.add(self.__label)

        # create the color panel and give it color
        self.colorpanel = CaptionPanel('Color:',
                                       SimplePanel(StyleName='colorpanel'))
        self.randomcolor()

        # we're initially off
        self.value = 0
        # create our timer
        self.timer = Timer(notify=self)

    def initialize(self):

        # this method solves an apparent bug with the slider: the
        # slider doesn't draw its handle if the position is set before
        # showing, so instead of doing this in __init__ (where I
        # originally had it), this method gets called after it is
        # shown on the root panel.  See below when it gets called.
        self.slider.setValue(self.value)
        self.slider.setControlPos(self.value)

    def onTimer(self, timer):

        # when the timer fires we randomize the color and (maybe)
        # reschedule ourselves.
        self.randomcolor()
        v = self.value * 1000
        if v:
            self.timer.schedule(v)

    def onControlValueChanged(self, sender, old, new):

        # event handler for when the slider is moved.
        if new == self.value:
            return
        self.value = new

        # is it being turned off?
        if new == 0:
            self.__label.setText('OFF')
            self.timer.cancel()
        else:
            # no it's being reset
            self.__label.setText(str(new) + ' sec')
            self.onTimer(self.timer)
            
    def randomcolor(self):

        # randomize the color and set the panel accordingly
        r = random()*256
        g = random()*256
        b = random()*256
        e = self.colorpanel.getWidget().getElement()
        color = '#%02x%02x%02x' % (r, g, b)
        self.colorpanel.setCaption('Color: %s' % color)
        DOM.setStyleAttribute(e, "background", color)
Пример #57
0
class Photos(Composite):
    def __init__(self):
        Composite.__init__(self)

        self.albums = []
        self.photos = []
        self.grid = Grid(4, 4, CellPadding=4, CellSpacing=4)
        self.grid.addTableListener(self)
        self.drill = 0
        self.pos = 0
        self.up = Button("Up", self) 
        self.next = Button("Next", self) 
        self.prev = Button("Prev", self) 
        self.timer = Timer(notify=self)
        self.userid = "jameskhedley"
        self.album_url = "http://picasaweb.google.com/data/feed/base/user/" + self.userid + "?alt=json-in-script&kind=album&hl=en_US&callback=restCb"
        self.doRESTQuery(self.album_url, self.timer)

        self.vp = VerticalPanel()
        self.disclosure = DisclosurePanel("Click for boring technical details.") 
        self.disclosure.add(HTML('''<p>OK so you want to write client JS to do a RESTful HTTP query from picasa right?
				 Well you can't because of the Same Origin Policy. Basically this means that
				 because the domain of the query and the domain of the hosted site are different,
				 then that could well be a cross-site scripting (XSS) attack. So, the workaround is to
				 do the call from a script tag so the JSON we get back is part of the document. 
				 But since we don't know what URL to hit yet, once we find out then we have to inject
				 a new script tag dynamically which the browser will run as soon as we append it.
				 To be honest I'm not 100% why Google use RESTful services and not JSON-RPC or somesuch,
				 which would be easier. Well, easier for me.'''))
        
        self.IDPanel = HorizontalPanel()
        self.IDPanel.add(Label("Enter google account:"))
        self.IDButton = Button("Go", self)
        
        self.IDBox = TextBox()
        self.IDBox.setText(self.userid)
        self.IDPanel.add(self.IDBox)
        self.IDPanel.add(self.IDButton)
        self.vp.add(self.IDPanel)
        self.vp.add(self.disclosure)
        self.vp.add(self.grid)

        self.initWidget(self.vp)

    def doRESTQuery(self, url, timer):
        """this is a totally different from an RPC call in that we have to
           dynamically add script tags to the DOM when we want to query the 
           REST API. These rely on callbacks in the DOM so we can either add 
           them dynamically or pre-define them in public/Main.html. 
           Once we've done that have to wait for the response.
           Which means we need to provide a listener for the timer"""

        JS("$wnd.receiver = 'wait'")
        new_script = DOM.createElement("script")
        DOM.setElemAttribute(new_script, "src", url)
        DOM.setElemAttribute(new_script, "type","text/javascript")
        JS("$wnd.document.body.appendChild(@{{new_script}})")
        self.timer.schedule(100)

    def onCellClicked(self, sender, row, col):
        if self.drill==0:
            self.drill += 1 
            self.vp.clear()
            self.grid.clear()
            self.vp.add(self.up)
            self.vp.add(self.grid)
            gridcols = self.grid.getColumnCount()
            album = self.albums[row+col+(row*(gridcols-1))]
            url = "http://picasaweb.google.com/data/feed/base/user/" + self.userid + "/albumid/" + album["id"] + "?alt=json-in-script&kind=photo&hl=en_US&callback=restCb"
            self.doRESTQuery(url, self.timer)
        elif self.drill==1:
            self.drill += 1
            gridcols = self.grid.getColumnCount()
            self.pos =row+col+(row*(gridcols-1))
            photo = self.photos[self.pos]
            self.vp.clear()
            self.fullsize = HTML('<img src="' + photo["full"] + '"/>')
            hp = HorizontalPanel()
            hp.add(self.up)
            hp.add(self.prev)
            hp.add(self.next)
            hp.setSpacing(8)
            self.vp.add(hp)
            self.vp.add(self.fullsize)

    def onClick(self, sender):
        if sender == self.IDButton:
            self.userid = self.IDBox.getText()
            if self.userid == "" or self.userid.isdigit():
                return
            self.drill = 0
            self.album_url = "http://picasaweb.google.com/data/feed/base/user/" + self.userid + "?alt=json-in-script&kind=album&hl=en_US&callback=restCb"
            self.grid.clear()
            self.doRESTQuery(self.album_url, self.timer)
        else:
            if self.drill == 2:
                if sender == self.up:
                    self.drill=1
                    self.vp.clear()
                    self.vp.add(self.up)
                    self.vp.add(self.grid)
                    self.fillGrid(self.photos, "photos")
                else:
                    if sender == self.next:
                        if self.pos >= len(self.photos):
                            return
                        self.pos +=1
                    elif sender == self.prev:
                        if self.pos < 1:
                            return
                        self.pos -=1
                    photo = self.photos[self.pos]
                    self.fullsize.setHTML('<img src="' + photo["full"] + '"/>')
            elif self.drill == 1:
                self.drill=0
                self.vp.clear()
                self.vp.add(self.IDPanel)
                self.vp.add(self.disclosure)
                self.vp.add(self.grid)
                self.fillGrid(self.albums, "albums")
            
    def onTimer(self, timer):
        receiver = JS("$wnd.receiver")

        if receiver == 'wait':
           self.timer.schedule(1000)
           return

        JS("$wnd.receiver = 'wait'")

        if self.drill == 0:
            self.parseAlbums(receiver)
            self.fillGrid(self.albums, "albums")
        elif self.drill == 1:
            self.parsePhotos(receiver)
            self.fillGrid(self.photos, "photos")

    def fillGrid(self, items, type):
        self.grid.clear()
        cols = self.grid.getColumnCount()
        self.grid.resizeRows((len(items)/cols)+1)
        rows = self.grid.getRowCount()
        for i in range(len(items)):
            vp = VerticalPanel()
            if type == 'photos':
                vp.add(items[i]['thumb'])
            else:
                vp.add(items[i]['thumb'])
                vp.add(items[i]['title'])
            self.grid.setWidget(int(i/cols), i%cols, vp)

    def parsePhotos(self, items):
        photo_list = JSONParser().jsObjectToPyObject(items)
        self.photos = []
        for i in range(len(photo_list)):
            index = "%s" % i
            aphoto = {}
            aphoto['thumb'] = HTML('<img src="' + photo_list[index]["media$group"]["media$thumbnail"]["1"]["url"] + '"/>')
            aphoto['full'] = photo_list[index]["media$group"]["media$content"]["0"]["url"] 
            self.photos.append(aphoto)

    def parseAlbums(self, items):
        album_list = JSONParser().jsObjectToPyObject(items)
        self.albums = []
        for i in range(len(album_list)):
            index = "%s" % i
            analbum = {}
            analbum['title'] = HTML(album_list[index]["title"]["$t"])
            analbum['thumb'] = HTML('<img src="' + album_list[index]["media$group"]["media$thumbnail"]["0"]["url"] + '"/>')
            url = album_list[index]["id"]["$t"]
            analbum['id'] = url.split('albumid/')[1].split('?alt')[0]
            self.albums.append(analbum)
class DataRunManager(object) :
	"""
	@brief Class to take care of all the data taking runs. Starts them and
	polls the RPC service to see when it's finished.
	
	Implemented as a singleton. Call the DataRunManager.instance() static
	method to get the only running instance.
	"""
	pollingTime=1000
	idlePollingTime=4000 # Longer polling time when I don't think I'm taking data.
	_onlyInstance=None
	# The following members are used as an enum to describe what the event is
	DataTakingStartedEvent=0
	DataTakingFinishedEvent=1
	DataTakingStatusEvent=3
	
	@staticmethod
	def instance() : # static method so no "self" parameter
		if DataRunManager._onlyInstance==None :
			DataRunManager._onlyInstance=DataRunManager()
		return DataRunManager._onlyInstance
	
	def __init__(self) :
		# Since this is a singleton, throw an exception if the constructor is called
		# explicitly.
		if DataRunManager._onlyInstance!=None :
			raise Exception( "DataRunManager is a singleton class. Call 'DataRunManager.instance()' to get the only running instance" )
		self.rpcService=GlibRPCService.instance()
		self.pollingTimer=Timer( notify=self.pollRPCService )
		self.eventHandlers = []
		self.fractionComplete = 1
		self.statusString = "Not taking data"
		self.firstRun = True
		# I'll poll once immediately on startup just in case the user is connecting to an
		# already running service. The code that handles the response to this starts the
		# timer running.
		self.pollRPCService()

	def onRemoteResponse(self, response, request_info):
		"""
		The method that gets called after a successful RPC call.
		"""
		#ErrorMessage( "Response to method '"+request_info.method+"'='"+str(response)+"'" )
		if request_info.method=="getDataTakingStatus" : self._onGetDataTakingStatusResponse(response)
		elif request_info.method=="startSCurveRun" : self._startRunResponse(response,"S-curve run")
		elif request_info.method=="startOccupancyCheck" : self._startRunResponse(response,"Occupancy check")
		elif request_info.method=="startTrimCalibration" : self._startRunResponse(response,"Trim calibration")
		elif request_info.method=="stopTakingData" : pass
		else : ErrorMessage( "Received an unexpected response for method "+request_info.method )
	
	def onRemoteError(self, code, message, request_info):
		"""
		The method that gets called after an unsuccessful RPC call.
		"""
		ErrorMessage( "Unable to contact server: "+str(message) )

	def _onGetDataTakingStatusResponse( self, response ) :
		"""
		Handles the response to a getDataTakingStatus RPC call. Separate method for code layout only.
		"""
		newFraction=response["fractionComplete"]
		newStatus=response["statusString"]
		statusHasChanged=False
		if (self.fractionComplete!=newFraction) or (self.statusString!=newStatus) :
			statusHasChanged=True
			if self.firstRun :
				# If something is already running on initialisation, tell everything
				for handler in self.eventHandlers :
					handler.onDataTakingEvent( DataRunManager.DataTakingStartedEvent, None )
		self.firstRun=False
		self.fractionComplete=newFraction
		self.statusString=newStatus
		# only want to inform the listening classes if there is a change in the status
		if statusHasChanged :
			if self.fractionComplete>=1 :
				eventCode=DataRunManager.DataTakingFinishedEvent
				details=None
			else :
				eventCode=DataRunManager.DataTakingStatusEvent
				details={"fractionComplete":self.fractionComplete,"statusString":self.statusString}
			# Inform all the registered handlers what is going on
			for handler in self.eventHandlers :
				handler.onDataTakingEvent( eventCode, details )

		if self.fractionComplete<1 :
			# If data hasn't finished then set the timer to fire again.
			self.pollingTimer.schedule( DataRunManager.pollingTime )
		else :
			# I'll constantly poll to make sure it's not taking data, in case something/someone
			# else connects and tells the RPC service to do something. I'll use a longer time
			# though.
			if self.idlePollingTime>0 : self.pollingTimer.schedule( DataRunManager.idlePollingTime )

	def _startRunResponse( self, reponse, runType ) :
		"""
		Handles the response to a RPC call. Separate method for code layout only.
		"""
		self.statusString=runType+" started"
		# Start polling the RPC service to see how the run is going
		self.pollingTimer.schedule( DataRunManager.pollingTime )
		# inform all registered handlers that data taking has started
		for handler in self.eventHandlers :
			handler.onDataTakingEvent( DataRunManager.DataTakingStartedEvent, None )

	def pollRPCService( self ) :
		"""
		Method that polls the RPC service to see what the state of data taking is.
		This method is bound to a Timer so that it will periodically be called.
		"""
		self.rpcService.getDataTakingStatus( None, self )

	def registerEventHandler( self, handler ) :
		"""
		Registers an event handler that will be notified when certain things happen, e.g.
		data taking started, data taking finished.
		"""
		self.eventHandlers.append( handler )
	
	def startSCurveRun( self, thresholds ) :
		if self.fractionComplete!=1 : raise AlreadyTakingDataError()
		
		self.fractionComplete=0
		self.statusString="Initiating s-curve run"
		self.rpcService.startSCurveRun( thresholds, self )
	
	def startOccupancyCheck( self ) :
		if self.fractionComplete!=1 : raise AlreadyTakingDataError()
		
		self.fractionComplete=0
		self.statusString="Initiating occupancy check"
		self.rpcService.startOccupancyCheck( None, self )

	def startTrimCalibration( self,  midPointTarget, maxLoops ) :
		if self.fractionComplete!=1 : raise AlreadyTakingDataError()
		
		self.fractionComplete=0
		self.statusString="Initiating trim calibration"
		self.rpcService.startTrimCalibration( {'midPointTarget':midPointTarget,'maxLoops':maxLoops}, self )
		
	def stopTakingData( self ) :
		self.rpcService.stopTakingData( None, self )