Пример #1
0
    def run(self):

        from dialog import Dialog

        dlg = Dialog(self.iface)
        dlg.show()
        dlg.exec_()
Пример #2
0
    def main_screen():

        d = Dialog(dialog="dialog")
        d.set_background_title(Menu.background_title)

        choices = [
            ("1", "Debug"),
            ("2", "Projeto"),
            ("3", "ESP32"),
            ("4", "Configuração"),
        ]

        options = {
            "1": GDB_Screen.debug_screen,
            "2": Project_Screen.project_screen,
            "3": ESP32_Screen.esp32_screen,
            "4": ESP32.config,
        }

        code, tag = d.menu(
            "Selecione uma das opções abaixo\n\nInterface:%s\nTarget:%s" %
            (GDB.interface, GDB.target),
            height=30,
            width=100,
            choices=choices)

        if code == d.OK:
            Menu.show(options[tag])

        return code
Пример #3
0
def ask_repo_desc(git_remote=None):
    """
    Ask user what description to set for the repo on the remote provided by
    git_remote parameter
    """
    if not "repo_desc" in GIT_REMOTE["repo"]:
        GIT_REMOTE["repo"]["repo_desc"] = ""
    title = "Local repo description"
    msg = "Description of the repo, will be used for all remote"

    dial = Dialog(dialog="dialog", autowidgetsize=True)
    dial.set_background_title("Git remote selection")
    code, tags = dial.inputbox(msg,
                               title=title,
                               init=GIT_REMOTE["repo"]["repo_desc"],
                               width=DIAL_MAXSIZE["width"],
                               height=10)
    # pylint: disable=no-else-return
    if not code == dial.OK:
        return False
    elif not git_remote:
        GIT_REMOTE["repo"]["repo_desc"] = tags
    else:
        git_remote["repo_desc"] = tags
    return True
Пример #4
0
def print_final_config():
    if not control_final_config():
        return False
    dial = Dialog(dialog="dialog", autowidgetsize=True)
    dial.set_background_title("Final configuration")
    msg = "Use [j/k] to go up and down \n" \
        + "Here is the final configuration that will be deploied\n" \
        + repeat_to_length("=", 45) + "\n\n"

    for i_remote in GIT_REMOTE['remote']:
        if 'main' in i_remote:
            msg += "Your main remote is " + i_remote['url'] + "/" \
                + i_remote["namespace"] + "/" \
                + i_remote["repo_config"]["name"] + ".git \n" \
                + print_final_repo_config(i_remote)  + "\n" \
                + repeat_to_length("=", 45) + "\n\n"

    for i_remote in GIT_REMOTE['remote']:
        if 'main' not in i_remote:
            msg += "One of your mirror remote is " + i_remote['url'] + "/" \
                + i_remote["namespace"] + "/" \
                + i_remote["repo_config"]["name"] + ".git \n" \
                + print_final_repo_config(i_remote)  + "\n" \
                + repeat_to_length("=", 45) + "\n\n"

    code = dial.yesno(msg,
                      title="Final Config",
                      width=DIAL_MAXSIZE["width"],
                      height=DIAL_MAXSIZE["height"])

    eprint(yaml.dump(GIT_REMOTE))
    if not code == dial.OK:
        return False
    return True
Пример #5
0
def config_main_remote(git_remote, api_options):
    git_remote["repo_config"] = {}
    choices = []
    title = git_remote["type"] + " repo configuration"
    dial = Dialog(dialog="dialog", autowidgetsize=True)
    dial.set_background_title(title)
    for i_choice in api_options:
        code, choice = config_remote_option(git_remote, api_options, i_choice,
                                            False)
        if isinstance(code, bool) and not code:
            return False
        if choice:
            choices += [choice]
    code, tags = dial.checklist("Which git remote to use as main remote ?",
                                choices=choices,
                                title=title,
                                width=DIAL_MAXSIZE["width"])
    for i_choice in choices:
        if i_choice[0] in tags:
            git_remote["repo_config"][i_choice[0]] = True
        else:
            git_remote["repo_config"][i_choice[0]] = False

    if git_remote["type"] == "github" and (
            not ("allow_rebase_merge" in tags or "allow_merge_commit" in tags
                 or "allow_squash_merge" in tags)):
        return github_config_merge_option(git_remote)

    GIT_REMOTE["repo"]["main_remote"] = git_remote["url"] + "/" \
        + git_remote["namespace"] + "/" \
        + git_remote["repo_config"]["name"] + ".git"
    return True
Пример #6
0
def ask_repo_name(git_remote=None):
    """
    Ask user what name to set for the repo on the remote provided by git_remote
    parameter
    """
    if not "name" in GIT_REMOTE["repo"]:
        GIT_REMOTE["repo"]["name"] = ""
    if git_remote:
        title = git_remote["url"] + " repo name"
        msg = "Name of the repo for the remote: " + git_remote["url"]
    else:
        title = "Local repo name"
        msg = "Name of the repo (i.e the folder) locally"

    dial = Dialog(dialog="dialog", autowidgetsize=True)
    dial.set_background_title("Git remote selection")
    code, tags = dial.inputbox(msg,
                               title=title,
                               init=GIT_REMOTE["repo"]["name"],
                               width=DIAL_MAXSIZE["width"],
                               height=10)
    # pylint: disable=no-else-return
    if not code == dial.OK:
        return False
    elif not git_remote:
        GIT_REMOTE["repo"]["name"] = tags
    else:
        git_remote["name"] = tags
    return True
Пример #7
0
    def showSettings(self):
        settings = QtCore.QSettings()

        dlg = Dialog(
            settings.value("connect_points_plugin/point_layer_from", ""),
            settings.value("connect_points_plugin/polygin_layer_to", ""),
            settings.value("connect_points_plugin/filed_name_id_from", ""),
            settings.value("connect_points_plugin/filed_name_link", ""),
            settings.value("connect_points_plugin/filed_name_id_to", ""),
            settings.value("connect_points_plugin/result_layer_name", ""),
            self._iface.mainWindow()
        )
        res = dlg.exec_()
        if res == Dialog.Accepted:
            # QgisPlugin().plPrint("Save settings")
            plugin_settings = dlg.getSettings()
            settings.setValue("connect_points_plugin/point_layer_from", plugin_settings[0])
            settings.setValue("connect_points_plugin/polygin_layer_to", plugin_settings[1])
            settings.setValue("connect_points_plugin/filed_name_id_from", plugin_settings[2])
            settings.setValue("connect_points_plugin/filed_name_link", plugin_settings[3])
            settings.setValue("connect_points_plugin/filed_name_id_to", plugin_settings[4])
            settings.setValue("connect_points_plugin/result_layer_name", plugin_settings[5])

        dlg.deleteLater()
        del dlg
Пример #8
0
    def enviroment_screen():

        d = Dialog(dialog="dialog")
        d.set_background_title(Menu.background_title)

        choices = [
            ("1", "Instalar/atualizar ESP-IDF"),
            ("2", "Instalar/atualizar openocd"),
            ("3", "Instalar/atualizar toolchain"),
        ]

        options = {
            "1": ESP32.manage_sdk,
            "2": ESP32.manage_openocd,
            "3": ESP32.manage_toolchain,
        }

        code, tag = d.menu("Ambiente de desenvolvimento",
                           height=30,
                           width=100,
                           choices=choices)

        if code == d.OK:
            options[tag]()

        return code
Пример #9
0
    def __init__(self, path=os.getcwd(), extensions=[], title="Select File",
                 width=540, height=300, window=None, batch=None, group=None,
                 anchor=ANCHOR_CENTER, offset=(0, 0),
                 theme=None, movable=True, on_select=None, on_escape=None):
        self.path = path
        self.extensions = extensions
        self.title = title
        self.on_select = on_select
        self.selected_file = None
        self._set_files()

        def on_parent_menu_select(choice):
            self._select_file(self.parents_dict[choice])

        def on_menu_select(choice):
            self._select_file(self.files_dict[choice])

        self.dropdown = Dropdown(options=self.parents,
                                 selected=self.parents[-1],
                                 align=VALIGN_BOTTOM,
                                 on_select=on_parent_menu_select)
        self.menu = Menu(options=self.files, align=HALIGN_LEFT,
                         on_select=on_menu_select)
        self.scrollable = Scrollable(
            VerticalLayout([self.dropdown, self.menu], align=HALIGN_LEFT),
            width=width, height=height)

        content = self._get_content()
        Dialog.__init__(self, content, window=window, batch=batch, group=group,
                        anchor=anchor, offset=offset, theme=theme,
                        movable=movable, on_escape=on_escape)
Пример #10
0
def main():
	while True:
		vms = Principal()
		ip = vms.get_ip_address(LocalInterface)
		result = vms.auth(ip)
		token = result.split()[1]
		result = vms.procurar(ip, token)
		varcontrole = ""
		window = Dialog()

		if result.split()[0] == "ERR:":
			varcontrole = window.yesno("No VMs found. Refresh?")
			if varcontrole != 0:
				sys.exit(1)
		else:
	
			if len(result.split()) > 1:
				lista_vms = [(r, '') for r in result.split(' ')]
                                status, vm = window.menu("VM List", choices=lista_vms)
				if status != 0:
                                	sys.exit(1)
			
			else:
				vm = result.split()[0]

			result = vms.status(vm, token)
			if result.split()[0] == "ERR:":
				result = vms.ligar(vm, token)

			result = vms.conectar(vm, token)	
			if EnableShutdown:
				os.system("shutdown now -h")
                                sys.exit(1)
Пример #11
0
 def __init__(self,scr,title = "Chat"):
     """ takes the curses window to pop up over, title to display, will dynamically size to parent window """
     self.current_buddy = None
     self.current_server = None
     self.chat_connection = None
     self.win = None
     self.buddys = None
     self.messages = None
     self.reply = None
     self.reply_border = None
     self.config_button = None
     self.cancel = None
     self.config = {}
     self.status = {}
     self.children = []
     self.myname = None
     self.event_time = time.clock()
     self.title = title
     # load the config right away
     self.load_config()
     self.setparent(scr)
     self.resize()
     max_y,max_x = self.getparent().getmaxyx()
     min_y,min_x = self.getparent().getbegyx()
     Dialog.__init__(self,scr,"ChatDialog", max_y, max_x, [ Frame(title),
                                                         self.buddys,
                                                         self.messages,
                                                         self.reply_border,
                                                         self.reply,
                                                         self.config_button,
                                                         self.cancel], min_y, min_x)
     self.start_chat_thread()
Пример #12
0
    def __init__(self, startDir, callback, filter = ".*"):
        currentDir = startDir.replace('\\','/')
        self.callback = callback
        self.filter = filter
        Dialog.__init__(self, -1, -1, 400,240, "File Dialog")
        self.setLayout(pyui2.layouts.TableLayoutManager(6,8))
        
        self.dirLabel = pyui2.widgets.Label("Directory:")
        self.fileLabel = pyui2.widgets.Label("Filename:")
        self.filterLabel = pyui2.widgets.Label("Filter:")

        self.dirBox = pyui2.widgets.Label(currentDir)
        self.filesBox = pyui2.widgets.ListBox(self._pyui2Selected, self._pyui2DoubleClicked)
        self.nameBox = pyui2.widgets.Label("")
        self.filterBox = pyui2.widgets.Edit(self.filter,10,self._pyui2Filter)

        self.dirButton = pyui2.widgets.Button("Up", self._pyui2Up)
        self.openButton = pyui2.widgets.Button("Open", self._pyui2Open)
        self.closeButton = pyui2.widgets.Button("Close", self._pyui2Close)

        self.addChild( self.dirLabel,    (0,0,2,1) )
        self.addChild( self.fileLabel,   (0,6,2,1) )
        self.addChild( self.filterLabel, (0,7,2,1) )
        self.addChild( self.dirBox,      (2,0,3,1) )
        self.addChild( self.filesBox,    (0,1,6,5) )
        self.addChild( self.nameBox,     (2,6,3,1) )
        self.addChild( self.filterBox,   (2,7,3,1) )
        self.addChild( self.dirButton,   (5,0,1,1) )
        self.addChild( self.openButton,  (5,6,1,1) )
        self.addChild( self.closeButton, (5,7,1,1) )        

        self.pack()
        self.setCurrentDir(currentDir)
Пример #13
0
 def execute(self, source, target):
     if not len(target):
         return "Area name not specified"
     area_id = target[0].lower()
     confirm_dialog = Dialog(DIALOG_TYPE_CONFIRM, "Are you sure you want to permanently remove area: " + area_id, "Confirm Delete", self.finish_delete)
     confirm_dialog.area_id = area_id
     return DialogMessage(confirm_dialog)
Пример #14
0
    def debug_screen():

        d = Dialog(dialog="dialog")
        d.set_background_title(Menu.background_title)

        choices = [("1", "Iniciar debug (prompt)"),
                   ("2", "Iniciar server(openocd)"),
                   ("3", "Parar server(openocd)"),
                   ("4", "Interface (adaptador)"), ("5", "Target (device)"),
                   ("6", "JTAG"), ("7", "Reset target"), ("8", "Scan server"),
                   ("9", "Desligar interface")]

        options = {
            "1": GDB_Screen.start_debug_section,
            "2": GDB.start_debug_server,
            "3": GDB.stop_debug_server,
            "4": GDB_Screen.select_interface,
            "5": GDB_Screen.select_target,
            "6": GDB_Screen.config_jtag,
            "7": GDB.reset_target,
            "8": GDB.scan_gdbserver,
            "9": GDB.shutdown_interface,
        }

        code, tag = d.menu(
            "Selecione uma das opções abaixo\n\nInterface:%s\nTarget:%s" %
            (GDB.interface, GDB.target),
            height=30,
            width=100,
            choices=choices)

        if code == d.OK:
            options[tag]()

        return code
Пример #15
0
 def submit(self):
     m = str(self.textArea.toPlainText()).strip()
     if m.find('@timenow') is not -1:
         url = 'http://*****:*****@timenow', '<a href="time://' + str(timenow) + '">@' + str(timenow) + '</a>')
     payload={'name':self.username, 'message':m}
     if m is not '':
         if self.isQues.isChecked():
             payload['isQues'] = True
             payload['isAns' ] = False
         elif self.isAns.isChecked():
             payload['isQues'] = False
             payload['isAns' ] = True
             payload[ 'tag'  ] = str(self.tagArea.text()).strip()
         else:
             payload['isQues'] = False
             payload['isAns' ] = False
         url = 'http://localhost:8000/polls/PostInsertQuery/'
         data = {'data':json.dumps(payload)}
         r = requests.get(url,params = data)
         # Checks if the request is processed correctly by the server
         if int(r.status_code) == 500:
             d = Dialog ('Invalid! Please Try Again..',self)
             d.show()
             self.tagArea.clear()
         else:
             self.textArea.setText('')
             self.tagArea.clear()
             self.isChat.setChecked(True)
Пример #16
0
    def project_screen():

        d = Dialog(dialog="dialog")
        d.set_background_title(Menu.background_title)

        choices = [
            ("1", "Compilar all"),
            ("2", "Compilar app"),
            ("3", "Criar projeto"),
        ]

        options = {
            "1": ESP32.compile_all,
            "2": ESP32.compile_app,
            "3": ESP32.create_project,
        }

        code, tag = d.menu("Selecione uma das opções abaixo",
                           height=30,
                           width=100,
                           choices=choices)

        if code == d.OK:
            options[tag]()
            pass

        return code
Пример #17
0
    def esp32_screen():

        d = Dialog(dialog="dialog")
        d.set_background_title(Menu.background_title)

        choices = [
            ("1", "Gravar"),
            ("2", "Monitor"),
            ("3", "Configuração"),
        ]

        options = {
            "1": ESP32.flash,
            "2": ESP32.monitor,
            "3": ESP32.config,
        }

        code, tag = d.menu("Ambiente de desenvolvimento",
                           height=30,
                           width=100,
                           choices=choices)

        if code == d.OK:
            options[tag]()

        return code
Пример #18
0
 def on_action_3_triggered(self):
     """
     Slot documentation goes here.
     """
     # TODO: not implemented yet
     #dialog = Dialog()
     d = Dialog(self.tableView,  self)
     d.show()
Пример #19
0
 def ask_user(self):
     d = Dialog(callback=self.set_yesno,
                text='Just do it?',
                action_name='Do It',
                title = 'This is a Dialog')
     app.dialog = d
     d.bind(on_dismiss=app.clear_dialog)
     d.open()
Пример #20
0
class DialogParser():
    """This class takes care of parsing a chuck of text to make it into a simple list of lines"""
    text = ""

    def __init__(self, webclient, **kwargs):
        """Constructor"""
        self.webclient = webclient
        if "filepath" in kwargs:
            self.load_text_file(kwargs["filepath"])

    def load_text_file(self, filepath):
        with open(os.path.abspath(filepath), mode = "r+") as text_file:
            self.text = unicode(text_file.read(), "utf-8")

    def parse_dialog(self):
        """Parses a dialog using the text class attribute"""

        #attempt to match a header containing voice assignments
        match_obj = re.compile(r'\[(.*?)\](.*)', re.UNICODE | re.DOTALL).match(self.text)

        self.dialog = Dialog()
        if match_obj is None:
            #match didn't work, there's no voice assignment header
            lines = re.compile(r'[\n]+', re.UNICODE).split(self.text)


            for line in lines:
                if line != "":
                    splitted = line.split(":", 1)
                    self.dialog.add_cue(Cue(voice_ref=self.webclient.get_voice_object_from_name(splitted[0]), line=splitted[1]))
        else:
            #match worked,  we have to parse the voice header which looks like this [ character1 : voicename1, ...]
            voice_defs = match_obj.groups()[0].split(",")
            character_dict = dict()
            for voice_def in voice_defs:
                character, voice = tuple([string.strip() for string in voice_def.split(":")])
                character_dict[character.upper()] = self.webclient.get_voice_object_from_name(voice)

            #then parsing the dialog using both the defined characters and the regular voices
            #match didn't work, there's no voice assignment header
            lines = re.compile(r'[\n]+', re.UNICODE).split(match_obj.groups()[1])

            for line in lines:
                if line != "":
                    splitted = line.split(":", 1)
                    #checking if the voice is a "character" voice or a regular voice
                    if character_dict.has_key(splitted[0].strip().upper()):
                        voice_obj = character_dict[splitted[0].strip().upper()]
                    else:
                        voice_obj = self.webclient.get_voice_object_from_name(splitted[0])

                    self.dialog.add_cue(Cue(voice_ref=voice_obj, line=splitted[1]))


    def parse_from_string(self, text):
        self.text = text
        self.parse_dialog()
        return self.dialog
Пример #21
0
 def choose_cols(self):
     # XX possibility un/check all
     chosens = [(str(i + 1), f, i in self.csv.settings["chosen_cols"]) for i, f in enumerate(self.csv.fields)]
     d = Dialog(autowidgetsize=True)
     ret, values = d.checklist("What fields should be included in the output file?",
                               choices=chosens)
     if ret == "ok":
         self.csv.settings["chosen_cols"] = [int(v) - 1 for v in values]
         self.csv.is_processable = True
Пример #22
0
 def __init__(self, parent, username, title, callback):
     Dialog.__init__(self, parent.gui, False)
     self.dlg.set_transient_for(parent.dlg)
     self.parent = parent
     self.parent.username_dialog = self
     self.callback = callback
     self.dlg.set_title(title)
     self.username = username
     self.user.set_text(username)
     self.user.grab_focus()
def main(_):
    dialog = Dialog()

    dialog.load_vocab(FLAGS.voc_path)
    dialog.load_examples(FLAGS.data_path)

    if FLAGS.train:
        train(dialog, batch_size=FLAGS.batch_size, epoch=FLAGS.epoch)
    elif FLAGS.test:
        test(dialog, batch_size=FLAGS.batch_size)
Пример #24
0
    def start(self, delay_msec=UPDATE_MSEC):

        Dialog.start(self)

        self.schedule_display_task(delay_msec)

        height = int(self.driver.canvas['height'])-100
        self.scrollbar.place(x=0, y=0, width=SCROLLBAR_WIDTH, height=height)
        self.listbox.place(x=SCROLLBAR_WIDTH, y=0, width=self.driver.canvas['width'], height=str(height))
        self.checkbox.place(x=10, y = height+10)
Пример #25
0
 def activated(self, index):
     '''
     After activated item from list, appropriate dialog will appear.
     '''
     if not ( index.parent().data().toString().isEmpty() ) or not ( isinstance(index.model(), QStandardItemModel) ):
         module = self.moduleList.model().data(index,Qt.UserRole+1).toPyObject()
         dialog = Dialog(self._iface, module)
         dialog.show()
     else:
         pass
Пример #26
0
    def start(self, delay_msec=UPDATE_MSEC):

        Dialog.start(self)

        self.throttle_gauge = self._new_gauge(0, 'Throttle', 'red', minval=0)   # T
        self.roll_gauge     = self._new_gauge(1, '    Roll', 'blue')            # A
        self.pitch_gauge    = self._new_gauge(2, '   Pitch', 'green')           # E
        self.yaw_gauge      = self._new_gauge(3, '     Yaw', 'orange')          # R
        self.switch_gauge   = self._new_gauge(4, '     Aux', 'purple')

        self.schedule_display_task(delay_msec)
Пример #27
0
def scenceLevel2(screen):
    background = gameObject.createBgd(tileSheet)
    screen.blit(background, (0,0))
    zeldaDialog = Dialog(screen, zeldaPhoto)
    linkDialog = Dialog(screen, linkPhoto)

    zeldaDialog.message = (
        "Pretty good job Link! ",
        "Nevertheless, I would like more candies.",
        "Let's head to Candy Forest 2. ")
    zeldaDialog.show = True
    zeldaDialog.sndNext()
Пример #28
0
class Game:

	global game_backend
	global game_dialog
	empty = ''

	def __init__(self):
		locale.setlocale(locale.LC_ALL, '')
		print('lala')
		self.game_backend = backend.Backend()
		self.game_dialog = Dialog(dialog='dialog')

		user_input = []
		for i in range(0, self.game_backend.code_length):
			user_input.append([self.get_input(i, user_input, True),
							   self.get_input(i, user_input, False)])

		print(user_input)

	def get_input(self, i, user_input, shapes):
		if shapes:
			choicesl = self.game_backend.get_shapes()
			question_text = 'Please pick the ' + str(i + 1) + '. shape. ' \
															'Entered ' \
													 'until now: ' + \
							str(user_input)
			help_text = 'This is helptext for shapes.'
		else:
			choicesl = self.game_backend.get_colours()
			question_text = 'Please pick the ' + str(i + 1) + '. colour. ' \
														   'Entered ' \
													 'until now: ' + \
							str(user_input)
			help_text = 'This is helptext for colours.'

		choices = []
		for i in choicesl:
			choices.append((i, self.empty, False))

		broken = False
		while not broken:
			code, choice = self.game_dialog\
				.radiolist(question_text,\
					choices = choices,\
					help_button = True)

			if code == 'help':
				self.game_dialog.msgbox(help_text)

			else:
				broken = True

		return choicesl.index(choice)
Пример #29
0
 def execute(self, source, target):
     if not target:
         return "Player name not specified"
     player_id = target[0].lower()
     if Context.instance.sm.player_session_map.get(player_id): #@UndefinedVariable
         return "Player " + player_id + " logged in, cannot delete."
     todie = self.load_object(Player, player_id)
     if todie:
         if todie.imm_level >= source.imm_level:
             return "Cannot delete player of same or lower level."
         confirm_dialog = Dialog(DIALOG_TYPE_CONFIRM, "Are you sure you want to permanently remove " + todie.name, "Confirm Delete", self.finish_delete)
         confirm_dialog.player_id = player_id
         return DialogMessage(confirm_dialog)
     return "Player " + player_id + " does not exist."
Пример #30
0
class Command(BaseCommand):
    help = "Import subjects from xls file"
    args = 'filename'

    def handle(self, *args, **options):
        source_filename = args[0]
        doc = xlrd.open_workbook(source_filename, formatting_info=True)
        format_doc = SubjectFormat(doc)

        from dialog import Dialog
        self.dialog = Dialog()
        if format_doc.sheet.ncols >= len(format_doc.cells):
            logic = SubjectImportLogic(format_doc)

            total = logic.doc.sheet.nrows - logic.doc.start_line
            index = 0

            self.dialog.gauge_start()
            for index, parsed_row in enumerate(logic.doc):
                logic.process_row(index, parsed_row)
                try:
                    text=(u'Импорт: %s' % parsed_row[0][0]).encode('utf-8')
                except IndexError:
                    text = (u'Ошибка').encode('utf-8')
                self.dialog.gauge_update(int(float(index)/total*100),
                    text=text,
                    update_text=True)

            self.dialog.gauge_stop()

            num_errors = len(logic.errors)
            self.dialog.infobox(u'Ошибок %d из %d: ' % (num_errors, total))
class ChatBot:

    def __init__(self, voc_path, train_dir):
        self.dialog = Dialog()
        self.dialog.load_vocab(voc_path)

        self.model = Seq2Seq(self.dialog.vocab_size)

        self.sess = tf.Session()
        ckpt = tf.train.get_checkpoint_state(train_dir)
        self.model.saver.restore(self.sess, ckpt.model_checkpoint_path)

    def run(self):
        sys.stdout.write("> ")
        sys.stdout.flush()
        line = sys.stdin.readline()

        while line:
            print(self._get_replay(line.strip()))

            sys.stdout.write("\n> ")
            sys.stdout.flush()

            line = sys.stdin.readline()

    def _decode(self, enc_input, dec_input):
        if type(dec_input) is np.ndarray:
            dec_input = dec_input.tolist()

        # TODO: 구글처럼 시퀀스 사이즈에 따라 적당한 버킷을 사용하도록 만들어서 사용하도록
        input_len = int(math.ceil((len(enc_input) + 1) * 1.5))

        enc_input, dec_input, _ = self.dialog.transform(enc_input, dec_input,
                                                        input_len,
                                                        FLAGS.max_decode_len)

        return self.model.predict(self.sess, [enc_input], [dec_input])

    def _get_replay(self, msg):
        enc_input = self.dialog.tokenizer(msg)
        enc_input = self.dialog.tokens_to_ids(enc_input)
        dec_input = []

        # TODO: 구글처럼 Seq2Seq2 모델 안의 RNN 셀을 생성하는 부분에 넣을것
        #       입력값에 따라 디코더셀의 상태를 순차적으로 구성하도록 함
        #       여기서는 최종 출력값을 사용하여 점진적으로 시퀀스를 만드는 방식을 사용
        #       다만 상황에 따라서는 이런 방식이 더 유연할 수도 있을 듯
        curr_seq = 0
        for i in range(FLAGS.max_decode_len):
            outputs = self._decode(enc_input, dec_input)
            if self.dialog.is_eos(outputs[0][curr_seq]):
                break
            elif self.dialog.is_defined(outputs[0][curr_seq]) is not True:
                dec_input.append(outputs[0][curr_seq])
                curr_seq += 1

        reply = self.dialog.decode([dec_input], True)

        return reply
Пример #32
0
 def ask(self):
     if hasattr(self.port, 'config'):
         dialog = Dialog(dialog='dialog')
         dialog.set_background_title('Conguration for {PORTNAME}'.format(PORTNAME=self.port.portname))
         portchoices = []
         for option, optvalues in self.port.config.items():
             self.port.config[option]['user_choice'] = False
             portchoices.append((option, optvalues['description'], optvalues['default']))
         code, tags = dialog.checklist(
             'Choose your Configuration for {PORTNAME}'.format(PORTNAME=self.port.portname),
             choices=portchoices, title="Port configuration")
         if code == dialog.OK:
             for tag in tags:
                 self.port.config[tag]['user_choice'] = True
         print('\n')
Пример #33
0
class UI:
    def __init__(self):
        from dialog import Dialog
        self.d = Dialog()
        self.w=0
        self.h=0

    def message(self, text, title=None):
        self.d.infobox( text )

    def menu(self, title, subtitle, choices):
        return self.d.menu( subtitle, title=title, choices=choices, width=self.w, height=self.h)[1]

    def confirm(self, title, question):
        return self.d.yesno(question, title=title, width=50, height=5)
Пример #34
0
 def __init__(self):
     self.dialog = Dialog(autowidgetsize=True)
     self.dialog.add_persistent_args(['--no-mouse'])
     self.dialog.set_background_title(
         'Python vSphere Client version {}'.format(__version__)
     )
     self.agent = None
Пример #35
0
 def __init__(self, world):
     self.world = world
     self.load_image = self.world.load_image
     self.display = world.display
     self.menu = MainMenu(self)
     self.dialog = Dialog(self, self.display)
     self.state = ""
Пример #36
0
    def __init__(self):
        self.year = date.today().year
        self.d = Dialog(dialog="dialog")
        self.d.set_background_title("SlackBuild.org Templates {0}".format(
            __version__))

        self.args = sys.argv
        self.args.pop(0)
        self.__cli()

        self.source = ""
        self.chk_md5 = ""
        self.pwd = ""
        self.slack_desc_text = []
        self.slack_desc_data = []
        # appname.info
        self._version = '""'
        self._homepage = '""'
        self._download = '""'
        self._md5sum = '""'
        self._download_x86_64 = '""'
        self._md5sum_x86_64 = '""'
        self._requires = '""'
        # appname.desktop
        self._name = self.args[0]
        self._comment = ""
        self._exec = "/usr/bin/{0}".format(self.args[0])
        self._icon = "/usr/share/pixmaps/{0}.png".format(self.args[0])
        self._terminal = "false"
        self._type = ""
        self._categories = ""
        self._genericname = ""
Пример #37
0
    def showSettings(self):
        settings = QtCore.QSettings()

        dlg = Dialog(
            settings.value("pointsinpolygons_plugin/point_layer_name", ""),
            settings.value("pointsinpolygons_plugin/polygin_layer_name", ""),
            settings.value("pointsinpolygons_plugin/filed_name", ""),
            self._iface.mainWindow()
        )
        res = dlg.exec_()
        if res == Dialog.Accepted:
            # Plugin().plPrint("Save settings")
            plugin_settings = dlg.getSettings()
            settings.setValue("pointsinpolygons_plugin/point_layer_name", plugin_settings[0])
            settings.setValue("pointsinpolygons_plugin/polygin_layer_name", plugin_settings[1])
            settings.setValue("pointsinpolygons_plugin/filed_name", plugin_settings[2])
Пример #38
0
    def handle(self, *args, **options):
        source_filename = args[0]
        source_file = open(source_filename, 'r')
        descriptor, name = tempfile.mkstemp()
        os.fdopen(descriptor, 'wb').write(source_file.read())
        doc = xlrd.open_workbook(name, formatting_info=True)
        format_doc = ListenerFileFormat(doc)

        from dialog import Dialog
        self.dialog = Dialog()
        if format_doc.sheet.ncols >= len(format_doc.cells):
            logic = ListenerImportLogic(format_doc)

            total = logic.doc.sheet.nrows - logic.doc.start_line

            self.dialog.gauge_start()
            for index, parsed_row in enumerate(logic.doc):
                logic.process_row(index, parsed_row)
                try:
                    text=(u'Импорт: %s' % ' '.join(parsed_row[5])).encode('utf-8')
                except IndexError:
                    text = (u'Ошибка').encode('utf-8')
                self.dialog.gauge_update(int(float(index)/total*100),
                    text=text,
                    update_text=True)

            self.dialog.gauge_stop()

            num_errors = len(logic.errors)
            self.dialog.infobox(u'Ошибок %d из %d: ' % (num_errors, total))

        next_cmd = NormalizeCommand()
        next_cmd.handle()
Пример #39
0
    def __init__(self, networkName, nodeName):
        super(IotConsole, self).__init__()

        self.deviceSuffix = Name(nodeName)
        self.networkPrefix = Name(networkName)
        self.prefix = Name(self.networkPrefix).append(self.deviceSuffix)

        self._identityStorage = IotIdentityStorage()
        self._policyManager = IotPolicyManager(self._identityStorage)
        self._identityManager = IotIdentityManager(self._identityStorage)
        self._keyChain = KeyChain(self._identityManager, self._policyManager)

        self._policyManager.setEnvironmentPrefix(self.networkPrefix)
        self._policyManager.setTrustRootIdentity(self.prefix)
        self._policyManager.setDeviceIdentity(self.prefix)
        self._policyManager.updateTrustRules()

        self.foundCommands = {}
        self.unconfiguredDevices = []

        # TODO: use xDialog in XWindows
        self.ui = Dialog(backtitle="NDN IoT User Console", height=18, width=78)

        trolliusLogger = logging.getLogger("trollius")
        trolliusLogger.addHandler(logging.StreamHandler())