Ejemplo n.º 1
0
class TextEditor(Editor):
    """ Base class for text style editors, which displays an editable text
        field, containing a text representation of the object trait value.
    """

    # ---------------------------------------------------------------------------
    #  Finishes initializing the editor by creating the underlying toolkit
    #  widget:
    # ---------------------------------------------------------------------------

    def init(self, parent):
        """ Finishes initializing the editor by creating the underlying toolkit
            widget.
        """
        self.control = TextBox()

        self.control.setText(self.str_value)
        self.control.addChangeListener(getattr(self, "update_object"))
        self.set_tooltip()

    # ---------------------------------------------------------------------------
    #  Handles the user changing the contents of the edit control:
    # ---------------------------------------------------------------------------

    def update_object(self, sender):
        """ Handles the user changing the contents of the edit control.
        """
        try:
            self.value = unicode(self.control.getText())
        except TraitError, excp:
            pass
Ejemplo n.º 2
0
class PreferencesDlg(DialogBox):

    fileLocation = None

    def __init__(self, left = 50, top = 50):
        DialogBox.__init__(self, modal = False)

        self.setPopupPosition(left, top)
        self.setText("Preferences")
        ftable = FlexTable()
        ftableFormatter = ftable.getFlexCellFormatter()
        row = 0

        self.fileLocation = getCookie("fileLocation")

        row += 1
        ftable.setWidget(row, 0, Label("Sheet loaded on startup", wordWrap=False))
        self.fileLocationInput = TextBox()
        self.fileLocationInput.addChangeListener(self.checkValid)
        self.fileLocationInput.addKeyboardListener(self)
        self.fileLocationInput.setVisibleLength(30)
        self.fileLocationInput.setText(self.fileLocation)
        ftable.setWidget(row, 1, self.fileLocationInput)

        row += 1
        hpanel = HorizontalPanel()
        self.saveBtn = Button("Save", self.onSave)
        self.saveBtn.setEnabled(False)
        hpanel.add(self.saveBtn)
        self.cancelBtn = Button("Cancel", self.onCancel)
        hpanel.add(self.cancelBtn)
        ftable.setWidget(row, 0, hpanel)
        ftableFormatter.setColSpan(row, 0, 2)

        self.setWidget(ftable)

    def onCancel(self, sender):
        self.hide()

    def onSave(self, sender):
        setCookie("fileLocation", self.fileLocationInput.getText(), 1000000000)
        self.hide()

    def checkValid(self, evt=None):
        if self.fileLocation != self.fileLocationInput.getText():
            self.saveBtn.setEnabled(True)
        else:
            self.saveBtn.setEnabled(False)

    def onClick(self, sender):
        pass

    def onKeyUp(self, sender, keyCode, modifiers):
        self.checkValid()

    def onKeyDown(self, sender, keyCode, modifiers):
        pass

    def onKeyPress(self, sender, keyCode, modifiers):
        pass
Ejemplo n.º 3
0
class BooleanArgument(Argument):
    def __init__(self):
        Argument.__init__(self, [Block.BOOLEAN_BLOCK])
        self.height = 20
        self.width = 15
        drawBooleanArgument(self)
        self.addInput()
        self.resize()

    def addInput(self):
        self.input = TextBox()
        self.input.setWidth(20)
        self.input.addInputListener(self)
        self.append(self.input)
        DOM.setBooleanAttribute(self.input.getElement(), "readOnly", True)
        self.input.addChangeListener(self)

    def onChange(self, sender):
        from edu.uca.util.Serializable import stateChange
        stateChange()

    def onInput(self, sender):
        if len(self.input.getText()) == 0:
            self.input.setWidth(
                20)  # nao esta usando pois nao pode digitar no input bool
        else:
            self.input.setWidth(20 + ((len(self.input.getText()) - 1) * 7))
        self.width = self.input.getWidth()
        self.resize()

    def resize(self):
        c = math.ceil(self.height / 2 + 1)
        self.tr.setStyleAttribute({
            'right': -c - 2,
            'width': c + 3,
            'height': c
        })
        self.br.setStyleAttribute({
            'right': -c - 2,
            'width': c + 3,
            'height': c
        })
        self.tl.setStyleAttribute({
            'left': -c - 2,
            'width': c + 3,
            'height': c
        })
        self.bl.setStyleAttribute({
            'left': -c - 2,
            'width': c + 3,
            'height': c
        })
        self.setStyleAttribute({'width': self.width})
        self.t.setWidth(self.width)
        self.b.setWidth(self.width)
Ejemplo n.º 4
0
 def onClick(self, sender):
     global statusbar, boxes
     statusbar.setText("Button pressed")
     pass
     if sender == self.buttonupdate:
         self.commobj = AMS.AMS_Comm()
         statusbar.setText("Updating data: Press Display list button to refesh")
     if sender == self.button:
         if AMS.sent > AMS.recv:
             statusbar.setText("Press button again: sent " + str(AMS.sent) + " recv " + str(AMS.recv))
         if (
             self.commobj.commname == "No AMS publisher running"
             or not self.commobj.commname
             or self.commobj.comm == -1
         ):
             if self.tree:
                 self.panel.remove(self.tree)
         else:
             statusbar.setText("Memories for AMS Comm: " + self.commobj.commname)
             result = self.commobj.get_memory_list()
             if self.tree:
                 self.panel.remove(self.tree)
             self.tree = Tree()
             for i in result:
                 if i == "Stack":
                     continue
                 subtree = TreeItem(i)
                 memory = self.commobj.memory_attach(i)
                 fields = memory.get_field_list()
                 if not isinstance(fields, list):
                     fields = [fields]
                 block = false
                 for j in fields:
                     field = memory.get_field_info(j)
                     if str(field[1]) == "AMS_READ":
                         if j == "Publish Block":
                             if field[4] == "true":
                                 block = true
                         else:
                             subtree.addItem(j + " = " + str(field[4]))
                     else:
                         if j == "Block" and not block:
                             continue
                         PN = HorizontalPanel()
                         PN.add(Label(Text=j + " ="))
                         tb = TextBox(Text=str(field[4]))
                         boxes[tb] = [i, j, memory]
                         tb.addChangeListener(self.textboxlistener)
                         PN.add(tb)
                         subtree.addItem(PN)
                 self.tree.addItem(subtree)
                 self.panel.add(self.tree)
Ejemplo n.º 5
0
 def onClick(self, sender):
     global statusbar, boxes
     statusbar.setText('Button pressed')
     pass
     if sender == self.buttonupdate:
         self.commobj = AMS.AMS_Comm()
         statusbar.setText(
             'Updating data: Press Display list button to refesh')
     if sender == self.button:
         if AMS.sent > AMS.recv:
             statusbar.setText('Press button again: sent ' + str(AMS.sent) +
                               ' recv ' + str(AMS.recv))
         if self.commobj.commname == 'No AMS publisher running' or not self.commobj.commname or self.commobj.comm == -1:
             if self.tree: self.panel.remove(self.tree)
         else:
             statusbar.setText('Memories for AMS Comm: ' +
                               self.commobj.commname)
             result = self.commobj.get_memory_list()
             if self.tree: self.panel.remove(self.tree)
             self.tree = Tree()
             for i in result:
                 if i == "Stack": continue
                 subtree = TreeItem(i)
                 memory = self.commobj.memory_attach(i)
                 fields = memory.get_field_list()
                 if not isinstance(fields, list): fields = [fields]
                 block = false
                 for j in fields:
                     field = memory.get_field_info(j)
                     if str(field[1]) == 'AMS_READ':
                         if j == "Publish Block":
                             if field[4] == "true": block = true
                         else:
                             subtree.addItem(j + ' = ' + str(field[4]))
                     else:
                         if j == "Block" and not block: continue
                         PN = HorizontalPanel()
                         PN.add(Label(Text=j + ' ='))
                         tb = TextBox(Text=str(field[4]))
                         boxes[tb] = [i, j, memory]
                         tb.addChangeListener(self.textboxlistener)
                         PN.add(tb)
                         subtree.addItem(PN)
                 self.tree.addItem(subtree)
                 self.panel.add(self.tree)
Ejemplo n.º 6
0
 def addRow(self, timeVO=None):
     self.rows += 1
     col = -1
     for name, maxLength, visibleLength in self.columns:
         col += 1
         textBox = TextBox()
         textBox.setText("")
         textBox.col = col
         textBox.row = self.rows
         textBox.addChangeListener(self.checkValid)
         textBox.addKeyboardListener(self)
         textBox.addFocusListener(self)
         textBox.setName(name)
         if not maxLength is None:
             textBox.setMaxLength(maxLength)
         if not visibleLength is None:
             textBox.setVisibleLength(visibleLength)
         self.setWidget(self.rows, col, textBox)
     if not timeVO is None:
         self.setRow(self.rows, timeVO)
Ejemplo n.º 7
0
 def addRow(self, timeVO = None):
     self.rows += 1
     col = -1
     for name, maxLength, visibleLength in self.columns:
         col += 1
         textBox = TextBox()
         textBox.setText("")
         textBox.col = col
         textBox.row = self.rows
         textBox.addChangeListener(self.checkValid)
         textBox.addKeyboardListener(self)
         textBox.addFocusListener(self)
         textBox.setName(name)
         if not maxLength is None:
             textBox.setMaxLength(maxLength)
         if not visibleLength is None:
             textBox.setVisibleLength(visibleLength)
         self.setWidget(self.rows, col, textBox)
     if not timeVO is None:
         self.setRow(self.rows, timeVO)
Ejemplo n.º 8
0
	def createRegisterPanel( self, registerNames ) :
		"""
		Creates panels and buttons for everything given in registerNames, and returns the main panel.
		"""
		flowPanel=FlowPanel()
		for buttonName in registerNames :
			newPanel=HorizontalPanel()
			label=Label(buttonName)
			newPanel.add( label )
			newTextBox=TextBox()
			newTextBox.setEnabled(False)
			newTextBox.setWidth(80)
			statusBox=TextBox()
			statusBox.setEnabled(False)
			statusBox.setWidth(30)
			newPanel.add(newTextBox)
			newPanel.add(statusBox)
			newPanel.setCellHorizontalAlignment( newTextBox, HasHorizontalAlignment.ALIGN_RIGHT )
			newPanel.setCellHorizontalAlignment( statusBox, HasHorizontalAlignment.ALIGN_RIGHT )
			newPanel.setCellWidth( statusBox, "20px" )
			newPanel.setWidth("100%")
			#newPanel.setStyleName("areaStyle");
			#newPanel.setBorderWidth(5);
			
			newTextBox.setText("select chip...")
			newTextBox.addChangeListener(self)
			newTextBox.setTitle(buttonName) # This isn't displayed, but it's useful to have stored
			
			self.i2cValueEntries[buttonName]=newTextBox	
			
			self.statusValueEntries[buttonName]=statusBox
			statusBox.setTitle(buttonName)
			statusBox.setText("...")
			
			flowPanel.add(newPanel)


		return flowPanel
Ejemplo n.º 9
0
class DateField(Composite, DateSelectedHandler):

    img_base = None
    icon_img = None

    icon_style = "calendar-img"
    today_text = "Today"
    today_style = "calendar-today-link"

    def __init__(self, format='%d-%m-%Y'):
        DateSelectedHandler.__init__(self)
        if self.img_base is None:
            self.img_base = pygwt.getImageBaseURL(True)
        if self.icon_img is None:
            self.icon_img = self.img_base + 'icon_calendar.gif'
        self.format = format
        self.tbox = TextBox()
        self.tbox.setVisibleLength(10)
        # assume valid sep is - / . or nothing
        if format.find('-') >= 0:
            self.sep = '-'
        elif format.find('/') >= 0:
            self.sep = '/'
        elif format.find('.') >= 0:
            self.sep = '.'
        else:
            self.sep = ''
        # self.sep = format[2] # is this too presumptious?
        self.calendar = Calendar()
        self.img = Image(self.icon_img)
        self.img.addStyleName(self.icon_style)
        self.calendarLink = HyperlinkImage(self.img)
        self.todayLink = Hyperlink(self.today_text)
        self.todayLink.addStyleName(self.today_style)
        #
        # lay it out
        #
        hp = HorizontalPanel()
        hp.setSpacing(2)
        vp = VerticalPanel()
        hp.add(self.tbox)
        vp.add(self.calendarLink)
        vp.add(self.todayLink)
        #vp.add(self.calendar)
        hp.add(vp)

        Composite.__init__(self)
        self.initWidget(hp)
        #
        # done with layout, so now set up some listeners
        #
        self.tbox.addFocusListener(self) # hook to onLostFocus
        self.calendar.addSelectedDateListener(getattr(self, "onDateSelected"))
        self.todayLink.addClickListener(getattr(self, "onTodayClicked"))
        self.calendarLink.addClickListener(getattr(self, "onShowCalendar"))

        self.tbox.addChangeListener(getattr(self, "onFieldChanged"))
        self.tbox.addInputListener(getattr(self, "onFieldChanged"))

        self._last_date = None

    def emitSelectedDate(self):
        _d = self.getDate()
        if _d == self._last_date:
            return
        self._last_date = _d
        self.fireDateSelectedEvent(_d)

    def onFieldChanged(self, event):
        self.emitSelectedDate()

    def getTextBox(self):
        return self.tbox

    def getCalendar(self):
        return self.calendar

    def getDate(self):
        """ returns datetime.date object or None if empty/unparsable by current format"""
        _sdate = self.tbox.getText()
        try:
            return datetime.strptime(_sdate, self.format).date()
        except ValueError:
            return None

    def setID(self, id):
        self.tbox.setID(id)

    def onDateSelected(self, yyyy, mm, dd):
        secs = time.mktime((int(yyyy), int(mm), int(dd), 0, 0, 0, 0, 0, -1))
        d = time.strftime(self.format, time.localtime(secs))
        self.tbox.setText(d)
        self.emitSelectedDate()

    def onLostFocus(self, sender):
        #
        text = self.tbox.getText().strip()
        # if blank - leave it alone
        if text and len(text) == 8:
            # ok what format do we have? assume ddmmyyyy --> dd-mm-yyyy
            txt = text[0:2] + self.sep + text[2:4] + self.sep + text[4:8]
            self.tbox.setText(txt)
        self.emitSelectedDate()

    def onFocus(self, sender):
        pass

    def onTodayClicked(self, event):
        today = time.strftime(self.format)
        self.tbox.setText(today)
        self.emitSelectedDate()

    def onShowCalendar(self, sender):
        txt = self.tbox.getText().strip()
        try:
            if txt:
                _d = datetime.strptime(txt, self.format).date()
                self.calendar.setDate(_d)
        except ValueError: pass

        p = CalendarPopup(self.calendar)
        x = self.tbox.getAbsoluteLeft() + 10
        y = self.tbox.getAbsoluteTop() + 10
        p.setPopupPosition(x, y)
        p.show()
Ejemplo n.º 10
0
class LatBuilderWeb:
    def setStyleSheet(self, sheet):
        e = DOM.createElement('link')
        e.setAttribute('rel', 'stylesheet')
        e.setAttribute('type', 'text/css')
        e.setAttribute('href', sheet)
        html = Window.getDocumentRoot().parentElement
        head = html.getElementsByTagName('head').item(0)
        head.appendChild(e)

    def includeMathJax(self, config):
        html = Window.getDocumentRoot().parentElement
        head = html.getElementsByTagName('head').item(0)

        e = DOM.createElement('script')
        e.setAttribute('type', 'text/javascript')
        e.setAttribute(
            'src', 'http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=' +
            config)
        head.appendChild(e)

        e = DOM.createElement('script')
        e.setAttribute('type', 'text/javascript')
        e.textContent = 'function Typeset() { MathJax.Hub.Queue(["Typeset",MathJax.Hub]); }'
        head.appendChild(e)

    def onModuleLoad(self):

        self.current_request = None

        Window.setTitle("Lattice Builder Web Interface")
        self.setStyleSheet("./LatBuilderWeb.css")
        self.includeMathJax('TeX-AMS-MML_HTMLorMML')

        self.TEXT_WAITING = "Lattice Builder is working..."
        self.TEXT_ERROR = "Server Error"
        self.FIGURES_OF_MERIT = [
            # (key, name)
            ('{cs}P2', 'P2'),
            ('{cs}P4', 'P4'),
            ('{cs}P6', 'P6'),
            ('{cs}R{alpha}', 'R_alpha'),
            ('spectral', 'spectral'),
        ]
        self.CONSTRUCTION_METHODS = [
            ('explicit:{genvec}', "Explicit (Evaluation)",
             "Evaluates the figure of merit for a given generating vector.<br/>"
             "<strong>Please specify the generating vector in the Lattice "
             "Properties panel above.</strong>"),
            ('exhaustive', "Exhaustive",
             "Examines all generating vectors and retains the best one."),
            ('random:{samples}', "Random",
             "Examines a number of randomly selected generating vectors and "
             "retains the best one."),
            ('Korobov', "Korobov",
             "Examines all generating vectors of the form (1, a, a^2 mod n, "
             "..., a^s mod n) and retains the best one."),
            ('random-Korobov:{samples}', "Random Korobov",
             "Examines a number of randomly selected generating vectors of "
             "the form (1, a, a^2 mod n, ..., a^s mod n) and retains the "
             "best one."),
            ('CBC', "Component-by-Component",
             "Examines all possible values of the components of the "
             "generating vector and selects the best ones, one coordinate "
             "at a time."),
            ('random-CBC:{samples}', "Random Component-by-Component",
             "Examines a number of randomly selected values of the "
             "components of the generating vector and selects the best "
             "ones, one coordinate at a time."),
            ('fast-CBC', "Fast Component-by-Component",
             "Examines all possible values of the components of the "
             "generating vector and selects the best ones, one coordinate "
             "at a time.  Computation is accelerated by using fast "
             "Fourier transforms."),
        ]
        self.COMBINER_TYPES = [
            ('level:max', 'highest level'),
            ('sum', 'weighted sum'),
            ('max', 'maximum weighted value'),
        ]
        self.NORMALIZATION_TYPES = [
            ('norm:P{alpha}-SL10', 'SL10 P-alpha'),
            ('norm:P{alpha}-DPW08', 'DPW08 P-alpha'),
        ]

        captionstyle = {
            'Width': '10em',
            'HorizontalAlignment': 'right',
        }

        self.remote = LatBuilderService()
        WeightValuesArray.REMOTE = self.remote

        main_panel = VerticalPanel(Spacing=30)

        # information

        info = """<h2>Lattice Builder Web Interface</h2>
        <p>This Web interface allows
        <a href="https://github.com/mungerd/latbuilder#readme">Lattice Builder</a>
        users to call the executable program without having to construct the
        command line explicitly.
        </p>
        <p>Enter the construction parameters below, and press the <em>Search for
        Good Lattices</em> button.  The results will show at the bottom.
        </p>"""

        main_panel.add(HTML(info))

        self.version_label = HTML()
        main_panel.add(self.version_label)
        self.remote.backend_version(self)

        params_panel = VerticalPanel(Spacing=15)
        main_panel.add(params_panel)

        # lattice type and size and dimension

        lat_panel = VerticalPanel()
        params_panel.add(CaptionPanel("Lattice Properties", lat_panel))
        lat_panel.add(
            HTML(
                r'\[ P_n = \left\{ (i \boldsymbol a \bmod n) / n \::\: i = 0, \dots, n \right\} \qquad (\boldsymbol a \in \mathbb Z^s) \]',
                StyleName='DisplayMath'))

        self.size = TextBox(Text="2^10")
        self.size.addChangeListener(self)

        self.embedded = CheckBox("embedded")
        self.embedded.addClickListener(self)

        panel = HorizontalPanel(Spacing=8)
        panel.add(HTML(r"Size (\(n\)): ", StyleName="CaptionLabel"))
        panel.add(self.size)
        panel.add(self.embedded)
        lat_panel.add(panel)

        self.dimension = TextBox(Text="3")
        self.dimension.addChangeListener(self)

        panel = HorizontalPanel(Spacing=8)
        panel.add(HTML(r"Dimension (\(s\)): ", StyleName="CaptionLabel"))
        panel.add(self.dimension)
        lat_panel.add(panel)

        self.generating_vector = GeneratingVector(self.size)
        self.generating_vector.panel.setVisible(False)
        lat_panel.add(self.generating_vector.panel)

        # figure of merit

        merit_panel = VerticalPanel()
        params_panel.add(CaptionPanel("Figure of Merit", merit_panel))
        merit_panel.add(
            HTML(
                r"\[ \left[ \mathcal D_q(P_n) \right]^q = "
                r"\sum_{\emptyset \neq u \subseteq \{1,\dots,s\}}"
                r"\gamma_u^q \, \left[\mathcal D_u(P_n)\right]^q"
                r"\qquad (q > 0) \]",
                StyleName='DisplayMath'))

        self.norm_type = TextBox(Text="2")
        self.norm_type.addChangeListener(self)

        panel = HorizontalPanel(Spacing=8)
        panel.add(
            HTML(r"Norm type (\(q\) or <b>inf</b>): ",
                 StyleName="CaptionLabel"))
        panel.add(self.norm_type)
        merit_panel.add(panel)

        self.merit = ListBox()
        self.merit.addChangeListener(self)
        for key, name in self.FIGURES_OF_MERIT:
            self.merit.addItem(name)

        self.merit_cs = CheckBox("Use coordinate-symmetric implementation",
                                 Checked=True)

        panel = HorizontalPanel(Spacing=8)
        panel.add(HTML("Figure of merit: ", StyleName="CaptionLabel"))
        panel.add(self.merit)
        panel.add(self.merit_cs)
        merit_panel.add(panel)

        self.merit_alpha_panel = HorizontalPanel(Spacing=8)
        self.merit_alpha = TextBox(Text="2")
        self.merit_alpha_panel.add(
            HTML("Value of alpha: ", StyleName="CaptionLabel"))
        self.merit_alpha_panel.add(self.merit_alpha)
        merit_panel.add(self.merit_alpha_panel)

        # filters and combiner

        multilevel_panel = VerticalPanel(Spacing=8)
        self.multilevel_panel = CaptionPanel("Multilevel Filters and Combiner",
                                             multilevel_panel,
                                             Visible=False)
        params_panel.add(self.multilevel_panel)

        self.ml_normalization_enable = CheckBox("Normalization")
        self.ml_normalization_enable.addClickListener(self)
        multilevel_panel.add(self.ml_normalization_enable)

        self.ml_normalization_panel = VerticalPanel(Spacing=4,
                                                    Visible=False,
                                                    StyleName='SubPanel')
        multilevel_panel.add(self.ml_normalization_panel)

        panel = HorizontalPanel(Spacing=8)
        panel.add(HTML("Normalization type: ", StyleName="CaptionLabel"))
        self.ml_normalization_type = ListBox()
        for key, name in self.NORMALIZATION_TYPES:
            self.ml_normalization_type.addItem(name, value=key)
        panel.add(self.ml_normalization_type)
        self.ml_normalization_panel.add(panel)

        panel = HorizontalPanel(Spacing=8)
        panel.add(HTML("Minimum level: ", StyleName="CaptionLabel"))
        self.ml_min_level = TextBox(Text="1")
        panel.add(self.ml_min_level)
        self.ml_normalization_panel.add(panel)

        panel = HorizontalPanel(Spacing=8)
        panel.add(HTML("Maximum level: ", StyleName="CaptionLabel"))
        self.ml_max_level = TextBox(Text="1")
        panel.add(self.ml_max_level)
        self.ml_normalization_panel.add(panel)

        self.ml_lowpass_enable = CheckBox("Low-pass filter")
        self.ml_lowpass_enable.addClickListener(self)
        multilevel_panel.add(self.ml_lowpass_enable)

        self.ml_lowpass_panel = VerticalPanel(Spacing=4,
                                              Visible=False,
                                              StyleName='SubPanel')
        multilevel_panel.add(self.ml_lowpass_panel)

        self.ml_lowpass = TextBox(Text="1.0")
        panel = HorizontalPanel(Spacing=8)
        panel.add(HTML("Low-pass threshold: ", StyleName="CaptionLabel"))
        panel.add(self.ml_lowpass)
        self.ml_lowpass_panel.add(panel)

        self.combiner_type = ListBox()
        for key, name in self.COMBINER_TYPES:
            self.combiner_type.addItem(name, value=key)
        panel = HorizontalPanel(Spacing=8)
        panel.add(HTML("Combiner: ", StyleName="CaptionLabel"))
        panel.add(self.combiner_type)
        multilevel_panel.add(panel)

        # weights

        self.weights = CompoundWeights()
        weights_panel = VerticalPanel()
        params_panel.add(CaptionPanel("Weights", weights_panel))
        weights_panel.add(
            HTML(r"\[ \gamma_u^p \qquad (u \subseteq \{1, \dots, s\}) \]",
                 StyleName='DisplayMath'))

        self.weights_power = TextBox(Text="2")
        panel = HorizontalPanel(Spacing=8)
        panel.add(HTML(r"Weights power (\(p\)): ", StyleName="CaptionLabel"))
        panel.add(self.weights_power)

        weights_panel.add(panel)
        weights_panel.add(self.weights.panel)
        self.weights.add_weights(ProductWeights)

        # construction method

        cons_panel = VerticalPanel()
        params_panel.add(CaptionPanel("Construction Method", cons_panel))

        self.construction = ListBox()
        self.construction.addChangeListener(self)
        for key, name, desc in self.CONSTRUCTION_METHODS:
            self.construction.addItem(name, value=key)
        self.construction_desc = HTML()

        panel = HorizontalPanel(Spacing=8)
        panel.add(self.construction)
        panel.add(self.construction_desc)
        cons_panel.add(panel)

        self.construction_samples_panel = HorizontalPanel(Spacing=8)
        self.construction_samples = TextBox(Text="30")
        self.construction_samples_panel.add(
            HTML("Random samples: ", StyleName="CaptionLabel"))
        self.construction_samples_panel.add(self.construction_samples)
        cons_panel.add(self.construction_samples_panel)

        # execute button

        panel = VerticalPanel(Spacing=8,
                              Width="100%",
                              HorizontalAlignment='center')
        main_panel.add(panel)

        button_panel = HorizontalPanel()
        panel.add(button_panel)
        self.button_search = Button("Search", self)
        button_panel.add(self.button_search)
        self.button_abort = Button("Abort", self, Visible=False)
        button_panel.add(self.button_abort)

        self.status = Label()
        panel.add(self.status)

        # results

        results_panel = VerticalPanel()
        self.results_panel = CaptionPanel("Results",
                                          results_panel,
                                          Visible=False)
        main_panel.add(self.results_panel)

        self.results_size = Label()
        panel = HorizontalPanel(Spacing=8)
        panel.add(HTML("Lattice size: ", StyleName="ResultsCaptionLabel"))
        panel.add(self.results_size)
        results_panel.add(panel)

        self.results_gen = Label()
        panel = HorizontalPanel(Spacing=8)
        panel.add(HTML("Generating vector: ", StyleName="ResultsCaptionLabel"))
        panel.add(self.results_gen)
        results_panel.add(panel)

        self.results_merit = Label()
        panel = HorizontalPanel(Spacing=8)
        panel.add(HTML("Merit value: ", StyleName="ResultsCaptionLabel"))
        panel.add(self.results_merit)
        results_panel.add(panel)

        self.results_cpu_time = Label()
        panel = HorizontalPanel(Spacing=8)
        panel.add(HTML("CPU time: ", StyleName="ResultsCaptionLabel"))
        panel.add(self.results_cpu_time)
        results_panel.add(panel)

        self.results_cmd = Label(StyleName='Command', Visible=False)
        panel = HorizontalPanel(Spacing=8)

        self.results_cmd_link = Hyperlink("Command line: ",
                                          StyleName="ResultsCaptionLabel")
        self.results_cmd_link.addClickListener(self)
        panel.add(self.results_cmd_link)
        panel.add(self.results_cmd)
        results_panel.add(panel)

        # update selections

        self.construction.selectValue('CBC')

        self.onChange(self.size)
        self.onChange(self.construction)
        self.onChange(self.merit)
        self.onChange(self.dimension)
        self.onClick(self.embedded)
        self.onChange(self.ml_normalization_enable)
        self.onChange(self.ml_lowpass_enable)

        RootPanel().add(main_panel)

    def onChange(self, sender):

        if sender == self.construction:
            key, name, desc = \
                    self.CONSTRUCTION_METHODS[self.construction.getSelectedIndex()]
            self.construction_desc.setHTML(desc)
            self.construction_samples_panel.setVisible('{samples}' in key)
            if key.startswith('explicit'):
                self.generating_vector.panel.setVisible(True)
                self.button_search.setText("Evaluate Figure of Merit")
            else:
                self.generating_vector.panel.setVisible(False)
                self.button_search.setText("Search for Good Lattices")

        elif sender == self.merit:
            key, name = \
                    self.FIGURES_OF_MERIT[self.merit.getSelectedIndex()]
            self.merit_alpha_panel.setVisible('{alpha}' in key)
            self.merit_cs.setVisible('{cs}' in key)

        elif sender == self.size:
            max_level = LatSize(self.size.getText()).max_level
            if int(self.ml_min_level.getText()) > max_level:
                self.ml_min_level.setText(max_level)
            self.ml_max_level.setText(max_level)

        elif sender == self.dimension:
            # resize weights
            dimension = int(self.dimension.getText())
            self.generating_vector.dimension = dimension
            self.weights.dimension = dimension

        elif sender == self.norm_type:
            q = self.norm_type.getText().strip()
            self.merit_cs.setVisible(q == '2')
            if q == 'inf':
                self.weights_power.setText('1')
            else:
                self.weights_power.setText(q)

    def onClick(self, sender):
        if sender == self.embedded:
            self.multilevel_panel.setVisible(self.embedded.getChecked())

        elif sender == self.ml_normalization_enable:
            self.ml_normalization_panel.setVisible(
                self.ml_normalization_enable.getChecked())

        elif sender == self.ml_lowpass_enable:
            self.ml_lowpass_panel.setVisible(
                self.ml_lowpass_enable.getChecked())

        elif sender == self.results_cmd_link:
            self.results_cmd.setVisible(not self.results_cmd.getVisible())

        elif sender == self.button_search:

            self.results_panel.setVisible(False)
            self.button_search.setVisible(False)
            self.button_abort.setVisible(True)

            lattype = self.embedded.getChecked() and 'embedded' or 'ordinary'
            size = self.size.getText()
            dimension = self.dimension.getText()

            norm_type = self.norm_type.getText()
            merit, merit_name = \
                    self.FIGURES_OF_MERIT[self.merit.getSelectedIndex()]
            alpha = self.merit_alpha.getText()
            cs = norm_type == 2 and self.merit_cs.getChecked() and 'CS:' or ''

            weights_power = self.weights_power.getText()
            weights = [w.as_arg() for w in self.weights.weights]

            construction, construction_name, desc = \
                    self.CONSTRUCTION_METHODS[self.construction.getSelectedIndex()]
            samples = self.construction_samples.getText()
            genvec = ','.join(self.generating_vector.values)

            mlfilters = []
            combiner_type = None

            if self.embedded.getChecked():
                if self.ml_normalization_enable.getChecked():
                    ml_normalization_type, ml_normalization_name = \
                            self.NORMALIZATION_TYPES[self.ml_normalization_type.getSelectedIndex()]
                    ml_normalization_type += ':even:{},{}'.format(
                        self.ml_min_level.getText(),
                        self.ml_max_level.getText())
                    mlfilters.append(ml_normalization_type.format(alpha=alpha))
                if self.ml_lowpass_enable.getChecked():
                    mlfilters.append('low-pass:{}'.format(
                        self.ml_lowpass.getText()))

                combiner_type, combiner_name = \
                        self.COMBINER_TYPES[self.combiner_type.getSelectedIndex()]

            self.status.setText(self.TEXT_WAITING)

            self.current_request = self.remote.latbuilder_exec(
                lattype, size, dimension, norm_type,
                merit.format(alpha=alpha, cs=cs),
                construction.format(samples=samples, genvec=genvec), weights,
                weights_power, None, mlfilters, combiner_type, self)

        elif sender == self.button_abort:
            # Need to patch JSONService.sendRequest():
            #
            # return HTTPRequest().asyncPost(self.url, msg_data,
            #                                JSONResponseTextHandler(request_info)
            #                                False, self.content_type,
            #                                self.headers)
            if self.current_request:
                self.current_request.abort()
                self.current_request = None
            self.button_abort.setVisible(False)
            self.button_search.setVisible(True)

        elif sender == self.product_weights_expr_link:
            self.showDialog(self._product_weights_expr_dialog)

        elif sender == self.order_weights_expr_link:
            self.showDialog(self._order_weights_expr_dialog)

    def onRemoteResponse(self, response, request_info):
        try:
            if request_info.method == 'latbuilder_exec':
                self.button_search.setVisible(True)
                self.button_abort.setVisible(False)
                cmd, points, gen, merit, seconds = eval(response)
                self.results_size.setText(points)
                self.results_gen.setText(', '.join(gen))
                self.results_merit.setText(merit)
                self.results_cpu_time.setText(format_time(seconds=seconds))
                self.results_cmd.setText(cmd)
                self.results_panel.setVisible(True)
                self.status.setText("")
            elif request_info.method == 'backend_version':
                version = response
                self.version_label.setHTML(
                    "<b>Backend:</b> {}".format(version))
        except:
            self.status.setText(response.replace('\n', '  |  '))

    def onRemoteError(self, code, errobj, request_info):
        if request_info.method == 'latbuilder_exec':
            self.button_search.setVisible(True)
            self.button_abort.setVisible(False)
        message = errobj['message']
        if code != 0:
            self.status.setText("HTTP error %d: %s" % (code, message['name']))
        else:
            code = errobj['code']
            if code == -32603:
                self.status.setText("Aborted.")
            else:
                self.status.setText("JSONRPC Error %s: %s" % (code, message))
Ejemplo n.º 11
0
class UserForm(AbsolutePanel):

    MODE_ADD    = "modeAdd";
    MODE_EDIT   = "modeEdit";

    user = None
    mode = None

    usernameInput = None
    firstInput = None
    lastInput = None
    emailInput = None
    passwordInput = None
    confirmInput = None
    departmentCombo = None
    addBtn = None
    cancelBtn = None

    def __init__(self,parent):
        AbsolutePanel.__init__(self)
        ftable = FlexTable()

        ftable.setWidget(0, 0, Label("First Name", wordWrap=False))
        ftableFormatter = ftable.getFlexCellFormatter()
        self.firstInput = TextBox()
        self.firstInput.addChangeListener(self.checkValid)
        self.firstInput.addKeyboardListener(self)
        ftable.setWidget(0, 1, self.firstInput)

        ftable.setWidget(1, 0, Label("Last Name", wordWrap=False))
        self.lastInput = TextBox()
        self.lastInput.addChangeListener(self.checkValid)
        self.lastInput.addKeyboardListener(self)
        ftable.setWidget(1, 1, self.lastInput)

        ftable.setWidget(2, 0, Label("Email", wordWrap=False))
        self.emailInput = TextBox()
        self.emailInput.addChangeListener(self.checkValid)
        self.emailInput.addKeyboardListener(self)
        ftable.setWidget(2, 1, self.emailInput)

        w = Label("* Username", wordWrap=False)
        w.addMouseListener(TooltipListener("Required, not changable"))
        ftable.setWidget(3, 0, w)
        self.usernameInput = TextBox()
        self.usernameInput.addChangeListener(self.checkValid)
        self.usernameInput.addKeyboardListener(self)
        ftable.setWidget(3, 1, self.usernameInput)

        w = Label("* Password", wordWrap=False)
        w.addMouseListener(TooltipListener("Required"))
        ftable.setWidget(4, 0, w)
        self.passwordInput = PasswordTextBox()
        self.passwordInput.addChangeListener(self.checkValid)
        self.passwordInput.addKeyboardListener(self)
        ftable.setWidget(4, 1, self.passwordInput)

        w = Label("* Confirm", wordWrap=False)
        w.addMouseListener(TooltipListener("Required"))
        ftable.setWidget(5, 0, w)
        self.confirmInput = PasswordTextBox()
        self.confirmInput.addChangeListener(self.checkValid)
        self.confirmInput.addKeyboardListener(self)
        ftable.setWidget(5, 1, self.confirmInput)

        w = Label("* Department", wordWrap=False)
        w.addMouseListener(TooltipListener("Required"))
        ftable.setWidget(6, 0, w)
        self.departmentCombo = ListBox()
        self.departmentCombo.addChangeListener(self.checkValid)
        self.departmentCombo.addKeyboardListener(self)
        ftable.setWidget(6, 1, self.departmentCombo)

        hpanel = HorizontalPanel()
        self.addBtn = Button("Add User")
        self.addBtn.setEnabled(False)
        hpanel.add(self.addBtn)
        self.cancelBtn = Button("Cancel")
        hpanel.add(self.cancelBtn)
        ftable.setWidget(7, 0, hpanel)
        ftableFormatter.setColSpan(7, 0, 2)

        self.add(ftable)
        self.clearForm()
        return

    def clearForm(self):
        self.user = None
        self.usernameInput.setText('')
        self.firstInput.setText('')
        self.lastInput.setText('')
        self.emailInput.setText('')
        self.passwordInput.setText('')
        self.confirmInput.setText('')
        self.departmentCombo.setItemTextSelection(None)
        self.updateMode(self.MODE_ADD)
        self.checkValid()

    def updateUser(self, user):
        def setText(elem, value):
            if value:
                elem.setText(value)
            else:
                elem.setText("")
        self.user = user
        setText(self.usernameInput, self.user.username)
        setText(self.firstInput, self.user.fname)
        setText(self.lastInput, self.user.lname)
        setText(self.emailInput, self.user.email)
        setText(self.passwordInput, self.user.password)
        setText(self.confirmInput, self.user.password)
        self.departmentCombo.setItemTextSelection([self.user.department])
        self.checkValid()

    def updateDepartmentCombo(self,choices, default_):
        self.departmentCombo.clear()
        for choice in choices:
            self.departmentCombo.addItem(choice)
        self.departmentCombo.selectValue(default_)

    def updateMode(self, mode):
        self.mode = mode
        if self.mode == self.MODE_ADD:
            self.addBtn.setText("Add User")
        else:
            self.addBtn.setText("Update User")

    def checkValid(self, evt=None):
        if self.enableSubmit(self.usernameInput.getText(),self.passwordInput.getText(),self.confirmInput.getText(), self.departmentCombo.getSelectedItemText(True)):
            self.addBtn.setEnabled(True)
        else:
            self.addBtn.setEnabled(False)

    def enableSubmit(self, u, p, c, d):
        return (len(u) > 0 and len(p) >0 and p == c and len(d) > 0)

    def onClick(self, sender):
        pass

    def onKeyUp(self, sender, keyCode, modifiers):
        self.checkValid()

    def onKeyDown(self, sender, keyCode, modifiers):
        pass

    def onKeyPress(self, sender, keyCode, modifiers):
        pass
Ejemplo n.º 12
0
class MechOptionPanel(HorizontalPanel):
    def __init__(self, handle, idx, checkOptions = [False, True]):
        HorizontalPanel.__init__(self)
        self.log = logging.getConsoleLogger(type(self).__name__, lev)
        self.log.disabled = False
        self.log.debug('__init__: Instantiation')
        self.idx = idx
        self._handle = handle
        self._checkOptions = checkOptions
        self.setStyleName('os-mech-checkbox-options')
        #checkbox = CheckBox('symbol')
        #checkbox.setChecked(checkOptions[0])
        #checkbox.addClickListener(self.onClickOption)
        #checkbox.setID('CBSY%d'%idx)
        #self.append(checkbox)
        #checkbox = CheckBox('value')
        #checkbox.setChecked(checkOptions[1])
        #checkbox.addClickListener(self.onClickOption)
        #checkbox.setID('CBVA%d'%idx)
        #self.append(checkbox)
        
        self._textBoxRatio = TextBox('1:1')
        self._ratioCache = self._textBoxRatio.getText()
        self._textBoxRatio.setTitle('Ratio')
        self._ratioCache = self._textBoxRatio.getText()
        
        self._textBoxRatio.addChangeListener(self.onRatioChange) 
        self._textBoxRatio.setID('TXRT%d'%idx)
        self._textBoxRatio.setStyleName('os-mech-textbox-ratio')
        
        self._listBoxSize = ListBox()
        self._listBoxSize.addChangeListener(self.onSizeSet)
        self._listBoxSize.setVisibleItemCount(1)
        self._listBoxSize.setStyleName('os-mech-listbox-size')

        self._listBoxUnit = ListBox()
        self._listBoxUnit.addChangeListener(self.onUnitSet)
        self._listBoxUnit.setVisibleItemCount(1)
        self._listBoxUnit.setStyleName('os-mech-listbox-unit')

        self.append(Label('Ratio'))
        self.append(self._textBoxRatio)
        self.append(Label('Size'))
        self.append(self._listBoxSize)
        self.append(Label('Unit'))
        self.append(self._listBoxUnit)
    def onSizeSet(self, sender, event):
        value = sender.getSelectedItemText()[0]
        self.log.debug('Change size to %s'%value)
        self._handle.remoteService.mech_options_set(self._handle._handle, self.idx, 'size', value)
    def onUnitSet(self, sender, event):
        value = sender.getSelectedValues()[0]
        self._handle.remoteService.mech_options_set(self._handle._handle, self.idx, 'unit',int(value))
    def onRatioChange(self, sender, event):
        #validate ratio change
        matches = re.findall(r'^\d{1,4}:\d{1,4}$', self._textBoxRatio.getText())
        if len(matches) == 1: # correct
            self._ratioCache = self._textBoxRatio.getText()
            self._handle.remoteService.mech_options_set(self._handle._handle, self.idx, 'ratio', self._ratioCache)
        else: # invalid
            self._textBoxRatio.setText(self._ratioCache)
    def actSizeFill(self, options, value = 0):
        for idx, option in enumerate(options, idx):
            self._listBoxSize.addItem(option, idx)
        self._listBoxSize.setSelectedIndex(value)
    def actUnitFill(self, options, value = 0):
        for number, name in options.items():
            self._listBoxUnit.addItem(name, number)
        if value < 100000:
            self._listBoxUnit.setSelectedIndex(value)
        else:
            self._listBoxUnit.selectValue(value)
    def actSizeSet(self, value):
        self.log.debug('actSizeSet, setting value %s'%value)
        self._listBoxSize.selectValue(value)
    def actRatioChange(self, ratio):
        self._textBoxRatio.setText(ratio)
        self._ratioCache = ratio
    def onClickOption(self, sender, event):
        sendId = int(sender.getID()[4:])
        if sendId == 0:
            self._checkOptions[0] = sender.isChecked()
            self._checkOptions[1] = not(sender.isChecked())
        else:
            self._checkOptions[0] = not(sender.isChecked())
            self._checkOptions[1] = sender.isChecked()
        checkbox = self.getWidget(0)
        checkbox.setChecked(self._checkOptions[0])
        checkbox = self.getWidget(1)
        checkbox.setChecked(self._checkOptions[1])
        self._handle.remoteService.mech_options_set(self._handle._handle, self.idx,  'checkOptions', self._checkOptions)
Ejemplo n.º 13
0
class PreferencesDlg(DialogBox):

    fileLocation = None

    def __init__(self, left=50, top=50):
        DialogBox.__init__(self, modal=False)

        self.setPopupPosition(left, top)
        self.setText("Preferences")
        ftable = FlexTable()
        ftableFormatter = ftable.getFlexCellFormatter()
        row = 0

        try:
            self.fileLocation = getCookie("fileLocation")
        except:
            self.fileLocation = None

        row += 1
        ftable.setWidget(row, 0,
                         Label("Sheet loaded on startup", wordWrap=False))
        self.fileLocationInput = TextBox()
        self.fileLocationInput.addChangeListener(self.checkValid)
        self.fileLocationInput.addKeyboardListener(self)
        self.fileLocationInput.setVisibleLength(30)
        self.fileLocationInput.setText(self.fileLocation)
        ftable.setWidget(row, 1, self.fileLocationInput)

        row += 1
        hpanel = HorizontalPanel()
        self.saveBtn = Button("Save", self.onSave)
        self.saveBtn.setEnabled(False)
        hpanel.add(self.saveBtn)
        self.cancelBtn = Button("Cancel", self.onCancel)
        hpanel.add(self.cancelBtn)
        ftable.setWidget(row, 0, hpanel)
        ftableFormatter.setColSpan(row, 0, 2)

        self.setWidget(ftable)

    def onCancel(self, sender):
        self.hide()

    def onSave(self, sender):
        try:
            setCookie("fileLocation", self.fileLocationInput.getText(),
                      1000000000)
        except:
            pass
        self.hide()

    def checkValid(self, evt=None):
        if self.fileLocation != self.fileLocationInput.getText():
            self.saveBtn.setEnabled(True)
        else:
            self.saveBtn.setEnabled(False)

    def onClick(self, sender):
        pass

    def onKeyUp(self, sender, keyCode, modifiers):
        self.checkValid()

    def onKeyDown(self, sender, keyCode, modifiers):
        pass

    def onKeyPress(self, sender, keyCode, modifiers):
        pass
Ejemplo n.º 14
0
class UserForm(AbsolutePanel):

    MODE_ADD = "modeAdd"
    MODE_EDIT = "modeEdit"

    user = None
    mode = None

    usernameInput = None
    firstInput = None
    lastInput = None
    emailInput = None
    passwordInput = None
    confirmInput = None
    departmentCombo = None
    addBtn = None
    cancelBtn = None

    def __init__(self, parent):
        AbsolutePanel.__init__(self)
        ftable = FlexTable()

        ftable.setWidget(0, 0, Label("First Name", wordWrap=False))
        ftableFormatter = ftable.getFlexCellFormatter()
        self.firstInput = TextBox()
        self.firstInput.addChangeListener(self.checkValid)
        self.firstInput.addKeyboardListener(self)
        ftable.setWidget(0, 1, self.firstInput)

        ftable.setWidget(1, 0, Label("Last Name", wordWrap=False))
        self.lastInput = TextBox()
        self.lastInput.addChangeListener(self.checkValid)
        self.lastInput.addKeyboardListener(self)
        ftable.setWidget(1, 1, self.lastInput)

        ftable.setWidget(2, 0, Label("Email", wordWrap=False))
        self.emailInput = TextBox()
        self.emailInput.addChangeListener(self.checkValid)
        self.emailInput.addKeyboardListener(self)
        ftable.setWidget(2, 1, self.emailInput)

        w = Label("* Username", wordWrap=False)
        w.addMouseListener(TooltipListener("Required, not changable"))
        ftable.setWidget(3, 0, w)
        self.usernameInput = TextBox()
        self.usernameInput.addChangeListener(self.checkValid)
        self.usernameInput.addKeyboardListener(self)
        ftable.setWidget(3, 1, self.usernameInput)

        w = Label("* Password", wordWrap=False)
        w.addMouseListener(TooltipListener("Required"))
        ftable.setWidget(4, 0, w)
        self.passwordInput = PasswordTextBox()
        self.passwordInput.addChangeListener(self.checkValid)
        self.passwordInput.addKeyboardListener(self)
        ftable.setWidget(4, 1, self.passwordInput)

        w = Label("* Confirm", wordWrap=False)
        w.addMouseListener(TooltipListener("Required"))
        ftable.setWidget(5, 0, w)
        self.confirmInput = PasswordTextBox()
        self.confirmInput.addChangeListener(self.checkValid)
        self.confirmInput.addKeyboardListener(self)
        ftable.setWidget(5, 1, self.confirmInput)

        w = Label("* Department", wordWrap=False)
        w.addMouseListener(TooltipListener("Required"))
        ftable.setWidget(6, 0, w)
        self.departmentCombo = ListBox()
        self.departmentCombo.addChangeListener(self.checkValid)
        self.departmentCombo.addKeyboardListener(self)
        ftable.setWidget(6, 1, self.departmentCombo)

        hpanel = HorizontalPanel()
        self.addBtn = Button("Add User")
        self.addBtn.setEnabled(False)
        hpanel.add(self.addBtn)
        self.cancelBtn = Button("Cancel")
        hpanel.add(self.cancelBtn)
        ftable.setWidget(7, 0, hpanel)
        ftableFormatter.setColSpan(7, 0, 2)

        self.add(ftable)
        self.clearForm()
        return

    def clearForm(self):
        self.user = None
        self.usernameInput.setText('')
        self.firstInput.setText('')
        self.lastInput.setText('')
        self.emailInput.setText('')
        self.passwordInput.setText('')
        self.confirmInput.setText('')
        self.departmentCombo.setItemTextSelection(None)
        self.updateMode(self.MODE_ADD)
        self.checkValid()

    def updateUser(self, user):
        def setText(elem, value):
            if value:
                elem.setText(value)
            else:
                elem.setText("")

        self.user = user
        setText(self.usernameInput, self.user.username)
        setText(self.firstInput, self.user.fname)
        setText(self.lastInput, self.user.lname)
        setText(self.emailInput, self.user.email)
        setText(self.passwordInput, self.user.password)
        setText(self.confirmInput, self.user.password)
        self.departmentCombo.setItemTextSelection([self.user.department])
        self.checkValid()

    def updateDepartmentCombo(self, choices, default_):
        self.departmentCombo.clear()
        for choice in choices:
            self.departmentCombo.addItem(choice)
        self.departmentCombo.selectValue(default_)

    def updateMode(self, mode):
        self.mode = mode
        if self.mode == self.MODE_ADD:
            self.addBtn.setText("Add User")
        else:
            self.addBtn.setText("Update User")

    def checkValid(self, evt=None):
        if self.enableSubmit(self.usernameInput.getText(),
                             self.passwordInput.getText(),
                             self.confirmInput.getText(),
                             self.departmentCombo.getSelectedItemText(True)):
            self.addBtn.setEnabled(True)
        else:
            self.addBtn.setEnabled(False)

    def enableSubmit(self, u, p, c, d):
        return (len(u) > 0 and len(p) > 0 and p == c and len(d) > 0)

    def onClick(self, sender):
        pass

    def onKeyUp(self, sender, keyCode, modifiers):
        self.checkValid()

    def onKeyDown(self, sender, keyCode, modifiers):
        pass

    def onKeyPress(self, sender, keyCode, modifiers):
        pass
Ejemplo n.º 15
0
class GeocodingSimple(DockPanel):
    def __init__(self):
        DockPanel.__init__(self)
        self.setSize('100%', '100%')

        self.geocoder = Geocoder()

        # widgets

        topPanel = HorizontalPanel()
        self.add(topPanel, DockPanel.NORTH)

        self.address = TextBox()
        self.address.setText("Sydney, NSW")
        self.address.addChangeListener(self.codeAddress)

        topPanel.add(self.address)

        button = Button("Geocode")
        button.addClickListener(self.codeAddress)

        topPanel.add(button)

        # now, the map

        mapPanel = SimplePanel()
        mapPanel.setSize('600', '400')
        self.add(mapPanel, DockPanel.CENTER)

        options = MapOptions(zoom=8,
                             center=LatLng(-34.397, 150.644),
                             mapTypeId=MapTypeId.ROADMAP)

        self.map = Map(mapPanel.getElement(), options)

    def codeAddress(self):
        address = self.address.getText()

        print "codeAddress ", address

        if self.geocoder:
            request = GeocoderRequest(address=address)
            self.geocoder.geocode(request, self.geocodeResult)

    def geocodeResult(self, results, status):
        print "geocodeResult"

        if status == GeocoderStatus.OK:

            for res in results:
                print res.formatted_address
                print res.geometry.location.lat()
                print res.geometry.location.lng()
                for compo in res.address_components:
                    print "- " + compo.short_name
                print ""

            self.map.setCenter(results[0].geometry.location)

            marker = Marker(
                MarkerOptions(map=self.map,
                              position=results[0].geometry.location))

        else:
            Window.alert(
                "Geocode was not successful for the following reason: " +
                status)
Ejemplo n.º 16
0
class GeocodingSimple(DockPanel):

    def __init__(self):
        DockPanel.__init__(self)
        self.setSize('100%', '100%')

        self.geocoder = Geocoder()

        # widgets

        topPanel = HorizontalPanel()
        self.add(topPanel, DockPanel.NORTH)

        self.address = TextBox()
        self.address.setText("Sydney, NSW")
        self.address.addChangeListener(self.codeAddress)

        topPanel.add(self.address)

        button = Button("Geocode")
        button.addClickListener(self.codeAddress)

        topPanel.add(button)

        # now, the map

        mapPanel = SimplePanel()
        mapPanel.setSize('600', '400')
        self.add(mapPanel, DockPanel.CENTER)

        options = MapOptions(zoom=8, center=LatLng(-34.397, 150.644),
                           mapTypeId=MapTypeId.ROADMAP)

        self.map = Map(mapPanel.getElement(), options)

    def codeAddress(self):
        address = self.address.getText()

        print "codeAddress ", address

        if self.geocoder:
            request = GeocoderRequest(address=address)
            self.geocoder.geocode(request, self.geocodeResult)

    def geocodeResult(self, results, status):
        print "geocodeResult"

        if status == GeocoderStatus.OK:

            for res in results:
                print res.formatted_address
                print res.geometry.location.lat()
                print res.geometry.location.lng()
                for compo in res.address_components:
                    print "- " + compo.short_name
                print ""

            self.map.setCenter(results[0].geometry.location)

            marker = Marker(MarkerOptions(map=self.map,
                position=results[0].geometry.location))

        else:
            Window.alert(
                "Geocode was not successful for the following reason: " +
                status)