コード例 #1
0
    def OnAxisRange(self, event):
        oldBoundsTxt = "%s %s %s" % (self.bounds[0], self.bounds[1], self.tick_interval)
        boundsTxt = wx.GetTextFromUser("Specify start and end of axis and (optionally) tick interval.\nUse <space> to separate those numbers or (for each) use `f` for tight fit and `a` for auto fit", 
                                        "Axis Bounds and Tick Interval", oldBoundsTxt)
        bounds = boundsTxt.split()
        def fff(b):
            if b.startswith('a'):
                return 'auto'
            elif b.startswith('f'):
                return 'fit'
            else:
                return float(b)
        bounds = [ fff(b) for b in bounds ]
        self.bounds = list(self.bounds) # in case bounds was an ndarray before and user gave a non-float here
        if len(bounds)>2:
            self.tick_interval = bounds[2]
        if len(bounds)>1:
            self.bounds[1] = bounds[1]
        if len(bounds)>0:
            self.bounds[0] = bounds[0]

        self.plot_canvas._saveZoomHist()
        self.plot_canvas.update()            
コード例 #2
0
def wxGetNumberFromUser(message, caption, default_value, i_begin, i_end,
                        parent):
    import wx

    isError = False
    while (1):
        x = wx.GetTextFromUser(message, caption, str(default_value), parent)
        try:
            isDigits = str(x).isdigit()
            x = int(x)
        except:
            isError = True
        if (not isDigits) or (isError):
            dlg = wx.MessageDialog(
                parent,
                'The value (%s) entered is either not a number or is out of range (%s to %s).\nPlease try again...'
                % (x, i_begin, i_end), 'Data Input Error',
                wx.CANCEL | wx.ICON_ERROR)
            dlg.ShowModal()
            dlg.Destroy()
        else:
            break
    return x
コード例 #3
0
    def OnCreatePlaylist(self, event):
        text = wx.GetTextFromUser('Enter Playlist Name', 'Insert Name',
                                  'Name this')
        if text != '':
            if text in self.playlist.keys():
                val = 1
                for key in self.playlist.keys():
                    start = key.rfind('(')
                    end = key.rfind(')')
                    try:
                        temp = int(key[start + 1:end])
                    except ValueError:
                        continue
                    val = max(val, temp)
                text += f' ({val+1})'
            self.playlist[text] = set()
            choices = [item.split('$')[0] for item in self.musicList]
            dlg = wx.MultiChoiceDialog(self,
                                       'Select',
                                       'Songs',
                                       choices=choices)

            if dlg.ShowModal() == wx.ID_OK:
                songs = [self.musicList[i] for i in dlg.GetSelections()]
                self.playlist[text] = self.playlist[text].union(set(songs))

            dlg.Destroy()

        if self._listCtrl.GetColumnCount() == 2:
            self._rightPanel.Freeze()
            try:
                self._listCtrl.Destroy()
            except RuntimeError:
                pass
            self.createPlaylistPanel()
            self.GetSizer().Layout()
            self._rightPanel.Thaw()
コード例 #4
0
 def OnManageFaceClicked(self, event):
     pw = wx.GetPasswordFromUser('请输入管理密码',
                                 caption="删除",
                                 default_value="",
                                 parent=self.bmp)
     if pw == '':
         print('取消删除')
     elif pw != PASSWORD:
         wx.MessageBox(message='密码错误,退出删除', caption='警告')
     else:
         self.loadDataBase(1)
         delete_id = wx.GetTextFromUser(message='请输入删除学生的学号',
                                        caption='删除',
                                        parent=self.bmp,
                                        default_value='-1')
         delete_id = int(delete_id)
         # 取消修改
         if delete_id == -1:
             # self.infoText.AppendText(
             #     '[%s]' % getDateAndTime(hms=1) + '取消添加\r\n')
             print('取消删除')
         else:
             delete_flag = 0
             for i, j in enumerate(self.knew_id):
                 if j == delete_id:
                     dlg = wx.MessageDialog(None,
                                            '请确认删除的学生为:{}学院的{}学生吗?'.format(
                                                self.knew_unit[i],
                                                self.knew_name[i]),
                                            caption='确认',
                                            style=wx.YES_NO)
                     if dlg.ShowModal() == wx.ID_YES:
                         # 删除数据库
                         self.deleteRow(i)
                     delete_flag = 1
             if not delete_flag:
                 wx.MessageBox(message='查无此人', caption='警告')
コード例 #5
0
    def OnPerspectiveMenu(self, evt):
        """Handles menu events generated by the managers control
        menu.
        @param evt: event that called this handler
        
        """
        e_id = evt.GetId()
        if e_id in [ID_SAVE_PERSPECTIVE, ID_DELETE_PERSPECTIVE]:
            if e_id == ID_SAVE_PERSPECTIVE:
                name = wx.GetTextFromUser(_("Perspective Name"), \
                                          _("Save Perspective"))
                if name:
                    self.AddPerspective(name, p_data=None)
                    self.SavePerspectives()

                    for mainw in wx.GetApp().GetMainWindows():
                        mainw.AddPerspective(name, self._viewset[name])

            elif e_id == ID_DELETE_PERSPECTIVE:
                name = wx.GetSingleChoice(_("Perspective to Delete"),
                                          _("Delete Perspective"),
                                          self._viewset.keys())
                if name:
                    self.RemovePerspective(name)
                    self.SavePerspectives()
                    for mainw in wx.GetApp().GetMainWindows():
                        mainw.RemovePerspective(name)
            else:
                pass

            # Update all windows data sets
            for mainw in wx.GetApp().GetMainWindows():
                mainw.LoadPerspectives()
        elif e_id in self._ids:
            self.SetPerspectiveById(e_id)
        else:
            evt.Skip()
コード例 #6
0
    def find(self, ev):
        # Ask user what to look for, find it and point at it ...  (Jezmy)
        S = self.e.GetStringSelection()
        if not S:
            S = "Z"
        FindValue = wx.GetTextFromUser('Please enter a search string:',
                                       caption="Search",
                                       default_value=S,
                                       parent=None)
        somecode = self.e.GetValue()
        position = somecode.find(FindValue, self.e.GetInsertionPoint())
        if position == -1:
            #   ShowMessage(self,-1,  "Not found!")
            self.titletext.SetLabel(_("Not Found!"))
        else:
            # self.title.SetValue("Position : "+str(position))

            self.titletext.SetLabel(str(position))

            # ananswer = wx.MessageBox(str(numLines)+" Lines detected in file\n"+str(position), "OK")
            self.e.SetFocus()
            self.e.SetInsertionPoint(position)
            self.e.SetSelection(position, position + len(FindValue))
            self.e.ShowPosition(position)
コード例 #7
0
    def OnAddChannel(self, event: wx.CommandEvent) -> None:
        """Add current channel configuration to list."""
        name = wx.GetTextFromUser('Enter name for new channel:',
                                  caption='Add new channel',
                                  parent=self)
        if not name:
            return
        new_channel = {}
        events.publish('save exposure settings', new_channel)

        if name not in self._channels:
            menu = event.GetEventObject()
            self.Bind(wx.EVT_MENU, self.OnApplyChannel,
                      menu.Append(wx.ID_ANY, item=name))
        else:
            answer = wx.MessageBox('There is already a channel named "%s".'
                                   ' Replace it?' % name,
                                   caption='Channel already exists',
                                   parent=self,
                                   style=wx.YES_NO)
            if answer != wx.YES:
                return

        self._channels[name] = new_channel
コード例 #8
0
ファイル: wxmtxy_root.py プロジェクト: APS-USAXS/wxmtxy
 def OnMenuPageChoicechangetabtitleMenu(self, event):
     '''user requested to rename tab
        @param event: wxPython event object'''
     pagenum = self.pagebook.GetSelection()
     if pagenum < 0:
         self.SetStatusText('No pages now!  Cannot rename a tab.')
         return      # early
     pair = self.pagebook.GetPage(pagenum)
     tabnum = pair.GetSelection()
     if tabnum < 0:
         self.SetStatusText('No tab to rename.')
         return
     text = pair.GetTabText(tabnum)
     self.SetStatusText('requested tab name change')
     response = wx.GetTextFromUser(parent=self,
         message='Rename this tab:', 
         caption='Rename this tab',
         default_value=text)
     if len(response) > 0:
         self.SetStatusText('New tab name: %s' % response)
         pair.SetTabText(tabnum, response)
         self._dirty()
     else:
         self.SetStatusText('Rename tab was canceled')
コード例 #9
0
ファイル: setup.py プロジェクト: pablorocad/gestionlibre.gui
def set_values(web2py_path, gui2py_path, gui_based = GUI_BASED, \
client = CLIENT, legacy_db = LEGACY_DB, hmac_key = HMAC_KEY, \
language = LANGUAGE, no_web2py_app = NO_WEB2PY_APP):

    try:
        login = os.getlogin()
    except (AttributeError, OSError):
        login = ""

    WEB2PY_PATH = web2py_path
    GUI2PY_PATH = gui2py_path

    if no_web2py_app:
        web2py_app_folder = ""
    else:
        web2py_app_folder = os.path.join(WEB2PY_PATH, \
        "applications", WEB2PY_APP_NAME)

    # set default paths (templates, example_db, ...)

    ini_values = dict(APP_NAME=APP_NAME,
                      SYSTEM_USER_NAME=login,
                      GUI2PY_APP_FOLDER=CWD,
                      GUI2PY_APP_CLIENT=client,
                      WEB2PY_APP_NAME=WEB2PY_APP_NAME,
                      WEB2PY_FOLDER=WEB2PY_PATH,
                      GUI2PY_FOLDER=GUI2PY_PATH,
                      WEB2PY_APP_FOLDER=web2py_app_folder,
                      DATABASES_FOLDER=os.path.join(CWD, "databases"),
                      TEMPLATES_FOLDER=os.path.join(CWD, "views"),
                      PDF_TEMPLATES_FOLDER=os.path.join(CWD, "pdf_templates"),
                      OUTPUT_FOLDER=os.path.join(CWD, "output"),
                      DB_URI=r'sqlite://storage.sqlite',
                      DB_TIMEOUT=-1,
                      HMAC_KEY=hmac_key,
                      LEGACY_DB=legacy_db,
                      LANGUAGE=language)

    # confirm db_uri or change it interactively

    # present a modal widget with connection string confirmation
    confirm_text = "Please confirm db connection string %s" % ini_values[
        "DB_URI"]

    if gui_based:
        retCode = wx.MessageBox(confirm_text, "db URI Srinng",
                                wx.YES_NO | wx.ICON_QUESTION)
        if retCode == wx.YES:
            confirm_uri_string = "y"
        else:
            confirm_uri_string = "n"
    else:
        confirm_uri_string = raw_input(confirm_text + " (y/n):")

    if not confirm_uri_string in ("\n", "Y", "y", None, ""):
        # if change uri is requested
        # prompt for uri

        prompt_for_db_uri = "Type a valid web2py db connection URI and press Enter"

        if GUI_BASED:
            new_uri_string = wx.GetTextFromUser(
                prompt_for_db_uri,
                caption="Input text",
                default_value=ini_values["DB_URI"],
                parent=None)
        else:
            new_uri_string = raw_input(prompt_for_db_uri + " :")

        ini_values["DB_URI"] = str(new_uri_string)
        if ini_values["DB_URI"] in ("", None):
            print "Installation cancelled. Db conection string was not specified"
            exit(1)

    demo_key = "sha512:3f00b793-28b8-4b3c-8ffb-081b57fac54a"

    if hmac_key is None:
        confirm_text = "Do you want to keep the demo hmac key? %s :" % demo_key

        if gui_based:
            retCode = wx.MessageBox(confirm_text, "HMAC KEY",
                                    wx.YES_NO | wx.ICON_QUESTION)
            if retCode == wx.YES:
                confirm_hmac = "y"
            else:
                confirm_hmac = "n"
        else:
            confirm_hmac = raw_input(confirm_text + " (y/n):")

        if not confirm_hmac.strip() in ("\n", "Y", "y", None, ""):
            # if change hmac is requested
            # prompt for hmac

            prompt_for_hmac = "You can use the random key, type a custom key or type \"new\" to retry"

            user_input_loop = True
            while user_input_loop == True:
                new_random_key = create_hmac_key()
                if GUI_BASED:
                    new_hmac = wx.GetTextFromUser(prompt_for_hmac,
                                                  caption="Input text",
                                                  default_value=new_random_key,
                                                  parent=None)
                else:
                    new_hmac = raw_input(prompt_for_hmac + " " +
                                         new_random_key + " (Enter):").strip()

                if new_hmac == "new":
                    # new key requested
                    continue
                elif new_hmac in (None, ""):
                    if not gui_based:
                        # terminal input accepts the random key
                        ini_values["HMAC_KEY"] = new_random_key
                        user_input_loop = False
                    else:
                        print "Installation cancelled. hmac key was not specified"
                        exit(1)
                else:
                    # store wathever was entered
                    ini_values["HMAC_KEY"] = new_hmac
                    user_input_loop = False

        else:
            # demo key
            ini_values["HMAC_KEY"] = demo_key

    # Change db_timeout for postgres connections
    if "postgres" in ini_values["DB_URI"].lower():
        # for remote db connection closed issue
        # ini_values["DB_TIMEOUT"] = 120000
        pass

    # write config values to config.ini
    print "Writing config values to config.ini"

    with open("config.ini", "w") as config:
        for k, v in ini_values.iteritems():
            config.write(k + "=" + str(v) + "\n")

    # write config values to webappconfig.ini
    # for path search purposes mostly
    if not NO_WEB2PY_APP:
        print "Writing config values to web2py app"
        if ini_values["WEB2PY_APP_FOLDER"] != "":
            # TODO: and ...FOLDER has a valid path
            with open(
                    os.path.join(ini_values["WEB2PY_APP_FOLDER"], "private",
                                 "webappconfig.ini"), "wb") as webappconfig:
                for k, v in ini_values.iteritems():
                    webappconfig.write(k + "=" + str(v) + "\n")

    # exit with status 0 and message
    print "Installation finished."
    print "You can run GestionLibre from %s with >python main.py" \
    % CWD

    return True
コード例 #10
0
ファイル: randterm.py プロジェクト: tcpaiva/randterm
 def OnSetPort(self, event):
     self.portName = wx.GetTextFromUser('Port: ', 'Select Port Name',
                                        self.portName)
コード例 #11
0
ファイル: setSliceOpacity.py プロジェクト: nagyistoce/devide
import vtk
import wx

className = obj.__class__.__name__
if className == 'slice3dVWR':

    sds = obj.sliceDirections.getSelectedSliceDirections()

    if len(sds) > 0:

        opacityText = wx.GetTextFromUser(
            'Enter a new opacity value (0.0 to 1.0) for all selected '
            'slices.')

        opacity = -1.0
        try:
            opacity = float(opacityText)
        except ValueError:
            pass

        if opacity < 0.0 or opacity > 1.0:
            print "Invalid opacity."

        else:
            for sd in sds:
                for ipw in sd._ipws:
                    prop = ipw.GetTexturePlaneProperty()
                    prop.SetOpacity(opacity)

    else:
        print "Please select the slices whose opacity you want to set."
コード例 #12
0
    def __init__(self, *args, **kwargs):
        wx.Frame.__init__(self, *args, **kwargs)
        self.SetBackgroundColour(wx.Colour(255, 255, 255))

        sizerPrincipal = wx.BoxSizer(wx.VERTICAL)

        self.nomeUsuario = wx.GetTextFromUser("Insira o nome do jogador:",
                                              "",
                                              default_value="Jogador 1")
        while not self.nomeUsuario:
            self.nomeUsuario = wx.GetTextFromUser("Insira o nome do jogador:",
                                                  "",
                                                  default_value="Jogador 1")

        self.textoBemVindo = wx.Button(
            self, style=wx.BORDER_NONE | wx.BU_EXACTFIT,
            size=(-1, 45))  #label="Seja bem Vindo, "+self.nomeUsuario+"!")
        self.corPadraoDeBotao = wx.Colour(255, 255, 255)
        self.textoBemVindo.SetBackgroundColour(wx.Colour(255, 255, 255))
        textoMarkup = ''
        textoMarkup = (
            "<span foreground='black'>Seja bem-vindo,</span> <b>{nome}</b>!\n"
            "Placar atual é: {nome}={pontuacaoUsuario} x PC={pontuacaoPC}"
        ).format(nome=self.nomeUsuario,
                 pontuacaoUsuario=self.pontuacaoUsuario,
                 pontuacaoPC=self.pontuacaoPC)
        self.textoBemVindo.SetLabelMarkup(textoMarkup)
        self.textoBemVindo.Disable()
        sizerPrincipal.Add(self.textoBemVindo, 0,
                           wx.CENTER | wx.EXPAND | wx.ALL ^ wx.BOTTOM, 6)

        self.dicionarioVez = {
            "X": wx.Bitmap("x.png", wx.BITMAP_TYPE_PNG),
            "O": wx.Bitmap("o.png", wx.BITMAP_TYPE_PNG),
            "BLANK": wx.Bitmap('blank.png', wx.BITMAP_TYPE_PNG)
        }

        self.vezDe = "X"

        _00 = wx.BitmapButton(self, size=(32, 32), style=wx.BU_NOTEXT)
        _01 = wx.BitmapButton(self, size=(32, 32), style=wx.BU_NOTEXT)
        _02 = wx.BitmapButton(self, size=(32, 32), style=wx.BU_NOTEXT)

        _10 = wx.BitmapButton(self, size=(32, 32), style=wx.BU_NOTEXT)
        _11 = wx.BitmapButton(self, size=(32, 32), style=wx.BU_NOTEXT)
        _12 = wx.BitmapButton(self, size=(32, 32), style=wx.BU_NOTEXT)

        _20 = wx.BitmapButton(self, size=(32, 32), style=wx.BU_NOTEXT)
        _21 = wx.BitmapButton(self, size=(32, 32), style=wx.BU_NOTEXT)
        _22 = wx.BitmapButton(self, size=(32, 32), style=wx.BU_NOTEXT)

        self.botoes = [[_00, _01, _02], [_10, _11, _12], [_20, _21, _22]]

        self.posicoesDisponiveis = []

        for linha in self.botoes:
            sizerLinha = wx.BoxSizer(wx.HORIZONTAL)
            for botao in linha:
                botao.SetLabelText('')
                botao.SetBackgroundColour(wx.Colour(255, 255, 255))
                botao.SetBitmap(self.dicionarioVez['BLANK'])
                botao.SetWindowStyle(wx.BU_NOTEXT | wx.BORDER_NONE)
                botao.SetCursor(wx.Cursor(wx.CURSOR_HAND))

                self.posicoesDisponiveis.append(botao)
                botao.Bind(wx.EVT_BUTTON, self.marcar_jogada_do_usuario)
                botao.Bind(wx.EVT_ENTER_WINDOW, self.mudar_cor_botao)
                botao.Bind(wx.EVT_LEAVE_WINDOW, self.mudar_cor_botao)
                sizerLinha.Add(botao, 1, wx.CENTER | wx.EXPAND)
                if botao != linha[-1]:
                    sizerLinha.Add(
                        wx.StaticLine(self, size=(1, 95),
                                      style=wx.LI_VERTICAL), 0,
                        wx.CENTER | wx.LEFT, 5)

            sizerPrincipal.Add(sizerLinha, 1,
                               wx.CENTER | wx.EXPAND | wx.ALL ^ wx.BOTTOM, 5)
            if linha != self.botoes[-1]:
                sizerPrincipal.Add(wx.StaticLine(self, size=(430, 1)), 0,
                                   wx.CENTER | wx.TOP, 5)

        textoNivelDeDificuldade = wx.StaticText(self,
                                                label="Nível de dificuldade:")
        nivelDeDificuldade = wx.Choice(self,
                                       choices=['Fácil', 'Médio', 'Difícil'])
        nivelDeDificuldade.SetSelection(1)

        botaoResetarJogo = wx.Button(self, label="Resetar")
        # BINDS
        nivelDeDificuldade.Bind(wx.EVT_CHOICE, self.mudar_dificuldade)
        botaoResetarJogo.Bind(wx.EVT_BUTTON, self.resetar_jogo)
        # BINDS

        sizerConfiguracoes = wx.BoxSizer(wx.HORIZONTAL)

        sizerConfiguracoes.Add(textoNivelDeDificuldade, 0,
                               wx.CENTER | wx.RIGHT, 6)
        sizerConfiguracoes.Add(nivelDeDificuldade, 0,
                               wx.CENTER | wx.RIGHT | wx.EXPAND, 6)
        sizerConfiguracoes.Add(botaoResetarJogo, 0, wx.CENTER | wx.EXPAND)

        sizerPrincipal.Add(sizerConfiguracoes, 0, wx.ALIGN_RIGHT | wx.ALL, 10)

        self.SetSizer(sizerPrincipal)
        self.SetAutoLayout(1)
        self.Center()
        # sizerPrincipal.Fit(self)
        self.Show()
コード例 #13
0
 def _ask_for_text(self, prompt):
     """vraagt om tekst en retourneert het antwoord"""
     return wx.GetTextFromUser(prompt, self.title)
コード例 #14
0
 def onClick_GetTextFromUser(self, event):
     name = wx.GetTextFromUser(message="Input your name : ",
                               caption="GetTextFromUser")
     print("Your name is", name)
コード例 #15
0
def change_gmdbowner_password():

    title = _('Changing GNUmed database owner password')

    dbo_account = wx.GetTextFromUser(
        message=_("Enter the account name of the GNUmed database owner:"),
        caption=title,
        default_value='')

    if dbo_account.strip() == '':
        return False

    dbo_conn = get_dbowner_connection(procedure=title, dbo_account=dbo_account)
    if dbo_conn is None:
        return False

    dbo_pwd_new_1 = wx.GetPasswordFromUser(
        message=_("Enter the NEW password for the GNUmed database owner:"),
        caption=title)
    if dbo_pwd_new_1.strip() == '':
        return False

    gmLog2.add_word2hide(dbo_pwd_new_1)

    dbo_pwd_new_2 = wx.GetPasswordFromUser(message=_(
        """Enter the NEW password for the GNUmed database owner, again.

(This will protect you from typos.)
		"""),
                                           caption=title)
    if dbo_pwd_new_2.strip() == '':
        return False

    if dbo_pwd_new_1 != dbo_pwd_new_2:
        return False

    # pwd2 == pwd1 at this point so no need to hide (again)
    """	On Mon, Mar 13, 2017 at 12:19:22PM -0400, Tom Lane wrote:
		> Date: Mon, 13 Mar 2017 12:19:22 -0400
		> From: Tom Lane <*****@*****.**>
		> To: Adrian Klaver <*****@*****.**>
		> cc: Schmid Andreas <*****@*****.**>,
		>  "'*****@*****.**'" <*****@*****.**>
		> Subject: Re: [GENERAL] createuser: How to specify a database to connect to
		> 
		> Adrian Klaver <*****@*****.**> writes:
		> > On 03/13/2017 08:52 AM, Tom Lane wrote:
		> >> If by "history" you're worried about the server-side statement log, this
		> >> is merest fantasy: the createuser program is not magic, it just constructs
		> >> and sends a CREATE USER command for you.  You'd actually be more secure
		> >> using psql, where (if you're superuser) you could shut off log_statement
		> >> for your session first.
		> 
		> > There is a difference though:
		> 
		> > psql> CREATE USER:
		> 
		> > postgres-2017-03-13 09:03:27.147 PDT-0LOG:  statement: create user 
		> > dummy_user with login password '1234';
		> 
		> Well, what you're supposed to do is
		> 
		> postgres=# create user dummy_user;
		> postgres=# \password dummy_user
		> Enter new password: 
		> Enter it again: 
		> postgres=# 
		> 
		> which will result in sending something like
		> 
		> ALTER USER dummy_user PASSWORD 'md5c5e9567bc40082671d02c654260e0e09'
		> 
		> You can additionally protect that by wrapping it into one transaction
		> (if you have a setup where the momentary existence of the role without a
		> password would be problematic) and/or shutting off logging beforehand.
	"""

    # this REALLY should be prefixed with md5 and the md5sum sent rather than the pwd
    cmd = """ALTER ROLE "%s" ENCRYPTED PASSWORD '%s';""" % (dbo_account,
                                                            dbo_pwd_new_2)
    gmPG2.run_rw_queries(link_obj=dbo_conn,
                         queries=[{
                             'cmd': cmd
                         }],
                         end_tx=True)

    return True
コード例 #16
0
 def on_search(self, event):
     word = wx.GetTextFromUser('Enter a word to search up', 'Insert dialog')
     if word != '':
         self.listbox.Append(word)
コード例 #17
0
 def ask_for_text(self, prompt, value=''):
     """vraagt om tekst en retourneert het antwoord"""
     return wx.GetTextFromUser(prompt, self.editor.title, value)
コード例 #18
0
 def Add(self, e):
     text = wx.GetTextFromUser('Enter your TODO', 'Insert Dialog')
     if text != '':
         mytodo_cli.add(text, self.user['user'], self.user['token'])
     self.Reload()
コード例 #19
0
ファイル: randterm.py プロジェクト: denghongcai/SD_spi
 def OnSetPort(self, event):
     self.portName = wx.GetTextFromUser('Port: ', 'Select Port Name',
                                        self.portName)
     self.displayPortName.Clear()
     self.displayPortName.write(self.portName)
コード例 #20
0
 def OnButtonAppend(self, evt):
     str = wx.GetTextFromUser('Enter new item:', 'Append', '', self)
     self.list.Append(str)
コード例 #21
0
class ThunderbirdImapReader(object):
    def __init__(self, url):
        mt = _RX_IMAP.search(url)
        if mt is None:
            mt = _RX_IMAP_MESSAGE.search(url)
            if mt is None:
                raise ThunderbirdError(
                    _('Unrecognized URL scheme: "%s"') % url)

        self.url = url

        self.user = unquote(mt.group(1))
        self.server = mt.group(2)
        port = None
        if ':' in self.server:
            self.server, port = self.server.split(':')
            port = int(port)
        self.box = mt.group(3)
        self.uid = int(mt.group(4))

        config = loadPreferences()

        stype = None
        # We iterate over a maximum of 100 mailservers. You'd think that
        # mailservers would be numbered consecutively, but apparently
        # that is not always the case, so we cannot assume that because
        # serverX does not exist, serverX+1 won't either.
        for serverIndex in range(100):
            name = 'mail.server.server%d' % serverIndex
            if config.has_key(name + '.hostname') and \
                self.__equal_servers(config[name + '.hostname'], self.server) \
                and config[name + '.type'] == 'imap':
                if config.has_key(name + '.port'):
                    port = int(config[name + '.port'])
                if config.has_key(name + '.socketType'):
                    stype = config[name + '.socketType']
                break
        self.ssl = (stype == 3)

        if self.server in ('imap.google.com', 'imap.googlemail.com'):
            # When dragging mail from Thunderbird that uses Gmail via IMAP the
            # server reported is imap.google.com, but for a direct connection we
            # need to connect with imap.gmail.com:
            self.server = 'imap.gmail.com'
        elif config.has_key(name + '.realhostname'):
            self.server = config[name + '.realhostname']
        self.port = port or {True: 993, False: 143}[self.ssl]

    @staticmethod
    def __equal_servers(server1, server2):
        ''' Return whether the servers are the same. '''
        gmail_servers = ('imap.gmail.com', 'imap.google.com',
                         'imap.googlemail.com')
        if server1 in gmail_servers and server2 in gmail_servers:
            return True
        else:
            return server1 == server2

    def _getMail(self):
        ''' Retrieve the email message from the IMAP server as specified by
            the dropped URL. '''
        imap_class = imaplib.IMAP4_SSL if self.ssl else imaplib.IMAP4
        try:
            imap = imap_class(self.server, self.port)
        except socket.gaierror, reason:
            error_message = _('Could not open an IMAP connection to '
                              '%(server)s:%(port)s\nto retrieve Thunderbird '
                              'email message:\n%(reason)s') % \
                              dict(server=self.server, port=self.port,
                                   reason=reason)
            raise ThunderbirdError(error_message)

        password_domain = '%s:%d' % (self.server, self.port)
        pwd = GetPassword(password_domain, self.user)
        if pwd is None:
            raise ThunderbirdCancelled('User canceled')

        while True:
            try:
                if 'AUTH=CRAM-MD5' in imap.capabilities:
                    response, dummy = imap.login_cram_md5(
                        str(self.user), str(pwd))
                elif 'AUTH=NTLM' in imap.capabilities:
                    domain = wx.GetTextFromUser( \
                        _('Please enter the domain for user %s') % self.user)
                    domain_username = '******'.join(
                        [domain.upper(), str(self.user)])
                    response, dummy_parameters = imap.authenticate('NTLM',
                        IMAPNtlmAuthHandler.IMAPNtlmAuthHandler( \
                            domain_username, str(pwd)))
                else:
                    response, dummy_parameters = imap.login(self.user, pwd)
            except imap.error, reason:
                response = 'KO'
                error_message, = reason.args

            if response == 'OK':
                break

            pwd = GetPassword(password_domain, self.user, reset=True)
            if pwd is None:
                raise ThunderbirdCancelled('User canceled')
コード例 #22
0
ファイル: ui.py プロジェクト: Calm-wy/kwc-ros-pkg
 def on_fail(self, event):
     failure_reason = wx.GetTextFromUser("Input the reason for failure:",
                                         "Input failure reason", "", self)
     self._manager.subtest_failed(self._msg, failure_reason)
コード例 #23
0
ファイル: func.py プロジェクト: duolabmeng6/pyefun
def 组件_普通对话框(提示="", 标题="请输入", 默认文本='', 父窗口=None):
    "弹出一个对话框输入文本,确认后返回输入的文本,取消返回空"
    return wx.GetTextFromUser(message=提示,
                              caption=标题,
                              default_value=默认文本,
                              parent=父窗口)
コード例 #24
0
ファイル: browser.py プロジェクト: wangdyna/wxPython
    def OnMenu(self, evt):
        """Handle the context menu events for performing
        filesystem operations

        """
        e_id = evt.Id
        path = self._menu.GetUserData('active_node')
        paths = self._menu.GetUserData('selected_nodes')

        def Opener(paths):
            """File opener job
            @param paths: list of paths

            """
            for fname in paths:
                subprocess.call([FILEMAN_CMD, fname])

        if e_id == ID_EDIT:
            self.OpenFiles(paths)
        elif e_id == ID_OPEN:
            ed_thread.EdThreadPool().QueueJob(Opener, paths)
        elif e_id == ID_REVEAL:
            dpaths = [os.path.dirname(fname) for fname in paths]
            dpaths = list(set(dpaths))
            ed_thread.EdThreadPool().QueueJob(Opener, dpaths)
        elif e_id == wx.ID_REFRESH:
            # Refresh the view
            self.RefreshView()
        elif e_id == ID_SEARCH_DIR:
            if len(paths):
                path = paths[0]  # Go off of the first selected item
                if not os.path.isdir(path):
                    path = os.path.dirname(path)
                mdata = dict(mainw=self._mw, lookin=path)
                ed_msg.PostMessage(ed_msg.EDMSG_FIND_SHOW_DLG, mdata)
        elif e_id == ID_GETINFO:
            last = None
            for fname in paths:
                info = ed_mdlg.EdFileInfoDlg(self.TopLevelParent, fname)
                if last is None:
                    info.CenterOnParent()
                else:
                    lpos = last.GetPosition()
                    info.SetPosition((lpos[0] + 14, lpos[1] + 14))
                info.Show()
                last = info
        elif e_id == ID_RENAME:
            item = self._menu.GetUserData('item_id')
            self.EditLabel(item)
        elif e_id == ID_NEW_FOLDER:
            name = wx.GetTextFromUser(_("Enter folder name:"),
                                      _("New Folder"),
                                      parent=self.TopLevelParent)
            if name:
                err, msg = ebmlib.MakeNewFolder(path, name)
                if not err:
                    wx.MessageBox(msg,
                                  _("Failed to create folder"),
                                  style=wx.OK | wx.CENTER | wx.ICON_ERROR)

        elif e_id == ID_NEW_FILE:
            name = wx.GetTextFromUser(_("Enter file name:"),
                                      _("New File"),
                                      parent=self.TopLevelParent)
            if name:
                err, msg = ebmlib.MakeNewFile(path, name)
                if not err:
                    wx.MessageBox(msg,
                                  _("Failed to create file"),
                                  style=wx.OK | wx.CENTER | wx.ICON_ERROR)
        elif e_id == ID_DUPLICATE:
            for fname in paths:
                DuplicatePath(fname)
        elif e_id == ID_ARCHIVE:
            MakeArchive(path)
        elif e_id == ID_DELETE:
            ebmlib.MoveToTrash(paths)
        else:
            evt.Skip()
            return
コード例 #25
0
    def NewItem(self, event):

        text = wx.GetTextFromUser('Enter a new item', 'Insert dialog')
        if text != '':
            self.listbox.Append(text)
コード例 #26
0
 def OnLabelActivate(self, event):
     newLabel = wx.GetTextFromUser("Enter new category name", "Rename")
     if not newLabel == '':
         self.SetStringItem(event.m_itemIndex, 1, newLabel)
コード例 #27
0
 def OnReference(self, evt):
     '''Create reference to an existing object.'''
     ref = wx.GetTextFromUser('Create reference to:', 'Create reference')
     if not ref: return
     Presenter.createRef(ref)
コード例 #28
0
 def four_play(self, event):
     data = wx.GetTextFromUser("plase input you dota:", "one and one")
     print data
コード例 #29
0
def _text_query(label, initial_value=""):
    result = wx.GetTextFromUser(label, "Query", initial_value)
    return result or None
コード例 #30
0
def mail_log(parent=None, comment=None, helpdesk=None, sender=None):

    if (comment is None) or (comment.strip() == ''):
        comment = wx.GetTextFromUser(message=_(
            'Please enter a short note on what you\n'
            'were about to do in GNUmed:'),
                                     caption=_('Sending bug report'),
                                     parent=parent)
        if comment.strip() == '':
            comment = '<user did not comment on bug report>'

    receivers = []
    if helpdesk is not None:
        receivers = regex.findall('[\S]+@[\S]+',
                                  helpdesk.strip(),
                                  flags=regex.UNICODE)
    if len(receivers) == 0:
        if _is_public_database:
            receivers = ['*****@*****.**']

    receiver_string = wx.GetTextFromUser(message=_(
        'Edit the list of email addresses to send the\n'
        'bug report to (separate addresses by spaces).\n'
        '\n'
        'Note that <*****@*****.**> refers to\n'
        'the public (!) GNUmed bugs mailing list.'),
                                         caption=_('Sending bug report'),
                                         default_value=','.join(receivers),
                                         parent=parent)
    if receiver_string.strip() == '':
        return

    receivers = regex.findall('[\S]+@[\S]+',
                              receiver_string,
                              flags=regex.UNICODE)

    dlg = gmGuiHelpers.c2ButtonQuestionDlg(
        parent,
        -1,
        caption=_('Sending bug report'),
        question=_('Your bug report will be sent to:\n'
                   '\n'
                   '%s\n'
                   '\n'
                   'Make sure you have reviewed the log file for potentially\n'
                   'sensitive information before sending out the bug report.\n'
                   '\n'
                   'Note that emailing the report may take a while depending\n'
                   'on the speed of your internet connection.\n') %
        '\n'.join(receivers),
        button_defs=[{
            'label': _('Send report'),
            'tooltip': _('Yes, send the bug report.')
        }, {
            'label': _('Cancel'),
            'tooltip': _('No, do not send the bug report.')
        }],
        show_checkbox=True,
        checkbox_msg=_('include log file in bug report'))
    dlg._CHBOX_dont_ask_again.SetValue(_is_public_database)
    go_ahead = dlg.ShowModal()
    if go_ahead == wx.ID_NO:
        dlg.DestroyLater()
        return

    include_log = dlg._CHBOX_dont_ask_again.GetValue()
    if not _is_public_database:
        if include_log:
            result = gmGuiHelpers.gm_show_question(
                _('The database you are connected to is marked as\n'
                  '"in-production with controlled access".\n'
                  '\n'
                  'You indicated that you want to include the log\n'
                  'file in your bug report. While this is often\n'
                  'useful for debugging the log file might contain\n'
                  'bits of patient data which must not be sent out\n'
                  'without de-identification.\n'
                  '\n'
                  'Please confirm that you want to include the log !'),
                _('Sending bug report'))
            include_log = (result is True)

    if sender is None:
        sender = _('<not supplied>')
    else:
        if sender.strip() == '':
            sender = _('<not supplied>')

    msg = """\
Report sent via GNUmed's handler for unexpected exceptions.

user comment  : %s

client version: %s

system account: %s
staff member  : %s
sender email  : %s

 # enable Launchpad bug tracking
 affects gnumed
 tag automatic-report
 importance medium

""" % (comment, _client_version, _local_account, _staff_name, sender)
    if include_log:
        _log.error(comment)
        _log.warning('syncing log file for emailing')
        gmLog2.flush()
        attachments = [[_logfile_name, 'text/plain', 'quoted-printable']]
    else:
        attachments = None

    dlg.DestroyLater()

    wx.BeginBusyCursor()
    _cfg = gmCfg2.gmCfgData()
    try:
        gmNetworkTools.compose_and_send_email(
            sender='%s <%s>' %
            (_staff_name, gmNetworkTools.default_mail_sender),
            receiver=receivers,
            subject='<bug>: %s' % comment,
            message=msg,
            server=gmNetworkTools.default_mail_server,
            auth={
                'user': gmNetworkTools.default_mail_sender,
                'password': '******'
            },
            debug=_cfg.get(option='debug'),
            attachments=attachments)
        gmDispatcher.send(signal='statustext',
                          msg=_('Bug report has been emailed.'))
    except:
        _log.exception('cannot send bug report')
        gmDispatcher.send(signal='statustext',
                          msg=_('Bug report COULD NOT be emailed.'))
    wx.EndBusyCursor()