示例#1
0
def waitKey(t):
    if cte_waitTime > 0 or scanconfig.cte_step_wait_for_key:
        import time
        startTime = time.time()

        if scanconfig.cte_step_wait_for_key:
            import os
            if os.name == 'nt':
                import msvcrt
                print "waiting for key"
            else:
                from getch import pause
                pause('Waiting for key')
        else:
            print "waiting " + str(cte_waitTime) + " seconds"

        done = False
        ret = -1
        while not done:
            if scanconfig.cte_step_wait_for_key:
                if os.name == 'nt':
                    if msvcrt.kbhit():
                        ret = msvcrt.getch()
                        done = True

                else:
                    done = True

            elif time.time() - startTime > t:
                done = True

        return ret
    else:
        return -1
示例#2
0
def public():
    if raw_input("¿Ya cuenta con un servidor ssh local existente? (y/n)\n--> "
                 ).upper() != "Y":
        print("Creando servidor ssh local...")
        time.sleep(3)
        private()

    servidor = raw_input(
        "Introduzca su gateway(puerta de enlace predeterminada de su router) \n--> "
    )
    time.sleep(3)
    print(
        "\nA continuacion se abrira la puerta de enlace de su router, configure los puertos correspondientes."
    )
    time.sleep(4)
    webbrowser.open("http://{}".format(servidor))
    time.sleep(3)
    pause("Una vez terminado, presione una tecla para continuar...")
    os.system('service ssh restart')
    print(
        "Tu servidor ssh publico deberìa de estar listo.\nRecuerda que para accesar debes hacerlo desde otra red diferente a la tuya."
    )
    time.sleep(3)
    print("\nGRACIAS POR UTILIZAR GEN SSH.")
    exit(0)
示例#3
0
 def launch(self):
     subprocess.run(["clear"])
     print_heading(self.menu_heading, fg="bright_yellow")
     if not node_is_installed():
         print_message(INSTALL_ERROR, fg="bright_red", bold=True)
         pause(message="Press any key to continue...")
         return
     if not NODEJS_INBOX.exists():
         NODEJS_INBOX.mkdir(parents=True, exist_ok=True)
     if node_modules_folder_exists():
         message = UPDATE_MESSAGE
         prompt = UPDATE_PROMPT
         temp_folder = None
         command = "npm update --timeout=9999999"
     else:
         message = INSTALL_MESSAGE
         prompt = INSTALL_PROMPT
         temp_folder = TemporaryDirectory(dir=NIGHTMAREJS_FOLDER)
         command = f"npm install --timeout=9999999 --cache={temp_folder.name}"
     print_message(message, fg="bright_yellow")
     if not yes_no_prompt(prompt, wrap=False):
         return Result.Ok(self.exit_menu)
     subprocess.run(["clear"])
     print_heading(self.menu_heading, fg="bright_yellow")
     result = run_command(command, cwd=str(NIGHTMAREJS_FOLDER))
     if result.failure:
         return result
     if temp_folder:
         temp_folder.cleanup()
     pause(message="\nPress any key to continue...")
     return Result.Ok(self.exit_menu)
示例#4
0
    def moter_moove(self):
        while True:
            key = ord(getch())

            if key == 13:  # Enter
                self.photo()
                print "Photo!"
                pass

            if key == 27:  # ESC
                key = ord(getch())

                if key == 91:  # Arrow keys
                    key = ord(getch())
                    if key == 66:
                        print "Down Arrow"
                        self.mv(0, 10.0, 1)
                    elif key == 65:
                        print "Up Arrow"
                        self.mv(0, -10.0, 1)
                    elif key == 68:
                        print "Left Arrow"
                        self.mv(10.0, 0, 1)
                    elif key == 67:
                        print "Right Arrow"
                        self.mv(-10.0, 0, 1)

                elif key == 27:  # ESC
                    print "ESC : exit."
                    break
        self.__del__()
        pause()
示例#5
0
 def update_player_data(self, task, data_set, no_prompts):
     subprocess.run(["clear"])
     print_heading(f"Update {data_set}", fg="bright_yellow")
     spinner = Halo(spinner=get_random_dots_spinner(), color=get_random_cli_color())
     spinner.text = "Updating player data..."
     spinner.start()
     result = task.execute()
     if result.failure:
         spinner.stop()
         return result
     spinner.succeed(f"{data_set} was successfully updated!")
     if no_prompts:
         return Result.Ok()
     updated_players = result.value or []
     if not updated_players:
         pause(message="Press any key to continue...")
         return Result.Ok(updated_players)
     heading = f"Updated {data_set}: Results"
     message = f"{len(updated_players)} changes total:"
     table_viewer = DictListTableViewer(
         dict_list=updated_players,
         prompt="Press Enter to continue",
         confirm_only=True,
         table_color="bright_yellow",
         heading=heading,
         heading_color="bright_yellow",
         message=message,
         message_color="blue",
     )
     table_viewer.launch()
     return Result.Ok(updated_players)
示例#6
0
def multi_season_prompt(db_session, prompt=None, heading=None):
    if not prompt:
        prompt = "Select one or multiple seasons from the list below:"
    all_seasons = db.Season.get_all_regular_seasons(db_session)
    choices = {f"{season.year}": season.year for season in all_seasons}
    instructions = "(use SPACE BAR to select each file type, ENTER to confirm your selections)"
    seasons_prompt = Check(
        prompt=instructions,
        choices=list(choices.keys()),
        check=EMOJIS.get("CHECK", ""),
        shift=1,
        indent=0,
        margin=2,
        check_color=colors.foreground["default"],
        check_on_switch=colors.foreground["default"],
        word_color=colors.foreground["default"],
        word_on_switch=colors.bright(colors.foreground["cyan"]),
        background_color=colors.background["default"],
        background_on_switch=colors.background["default"],
    )
    selected_years = []
    while not selected_years:
        subprocess.run(["clear"])
        if heading:
            print_heading(heading, fg="bright_yellow")
        print_message(prompt, wrap=True)
        result = seasons_prompt.launch()
        if not result:
            print_error("\nYou must select at least one season!")
            pause(message="Press any key to continue...")
            continue
        selected_years = [choices[sel] for sel in result]
    return selected_years
示例#7
0
 def launch(self):
     subprocess.run(["clear"])
     print_message(f"Variable Name: {self.setting_name}\n",
                   fg="bright_magenta",
                   bold=True)
     print_message(f"Current Value: {self.current_setting}\n",
                   fg="bright_yellow",
                   bold=True)
     if not yes_no_prompt(prompt="\nChange current setting?"):
         return Result.Ok(self.exit_menu)
     user_confirmed, new_value = False, None
     while not user_confirmed:
         subprocess.run(["clear"])
         prompt = f"Enter a new value for {self.setting_name}:\n"
         new_value = Input(
             prompt, word_color=colors.foreground["default"]).launch()
         result = self.confirm_new_value(new_value)
         if result.failure:
             return Result.Ok(self.exit_menu)
         user_confirmed = result.value
     result = self.dotenv.change_value(self.setting_name, new_value)
     if not self.restart_required:
         return result
     print_message(RESTART_WARNING, fg="bright_magenta", bold=True)
     pause(message="Press any key to continue...")
     exit(0)
示例#8
0
def waitKey(t):
    if cte_waitTime > 0 or scanconfig.cte_step_wait_for_key:
        import time
        startTime = time.time()

        if scanconfig.cte_step_wait_for_key:
            import os
            if os.name == 'nt':
                import msvcrt
                print "waiting for key"
            else:
                from getch import pause
                pause('Waiting for key')
        else:
            print "waiting "+str(cte_waitTime)+" seconds"

        done = False
        ret = -1
        while not done:
            if scanconfig.cte_step_wait_for_key:
                if os.name == 'nt':
                    if msvcrt.kbhit():
                        ret = msvcrt.getch()
                        done = True

                else:
                    done = True

            elif time.time() - startTime > t:
                done = True

        return ret
    else:
        return -1
示例#9
0
def file_types_prompt(prompt, valid_file_types=VigFile.ALL):
    if not prompt:
        prompt = "Select one or multiple file types from the list below:"
    choices = {f"{f}": f for f in VigFile if int(f) & valid_file_types == f}
    instructions = "(use SPACE BAR to select each file type, ENTER to confirm your selections)"
    file_types_prompt = Check(
        prompt=instructions,
        choices=list(choices.keys()),
        check=EMOJIS.get("CHECK", ""),
        shift=1,
        indent=0,
        margin=2,
        check_color=colors.foreground["default"],
        check_on_switch=colors.foreground["default"],
        word_color=colors.foreground["default"],
        word_on_switch=colors.bright(colors.foreground["cyan"]),
        background_color=colors.background["default"],
        background_on_switch=colors.background["default"],
    )
    file_types = []
    while not file_types:
        subprocess.run(["clear"])
        print_message(prompt, fg="bright_yellow", bold=True, underline=True)
        result = file_types_prompt.launch()
        if not result:
            print_error("\nYou must select at least one file type!")
            pause(message="Press any key to continue...")
            continue
        file_types = [choices[sel] for sel in result]
    return file_types
示例#10
0
def setaddress():
    # This function is a user option that will set you a new home address based on what you input. Zip/Postal code is not needed.
    shelf_file = shelve.open('sethome')
    shelf_file['address'] = input("What is your new home address?\n")
    print("\nYour new QuickMap address is " + shelf_file['address'] + "\n")
    shelf_file.close()
    pause('\nPress any key to return to menu\n')
示例#11
0
 def synchronize_files(self):
     if self.all_files_are_in_sync:
         message = "All files for selected data sets are in sync!"
         print_message(message, fg="bright_green", bold=True)
         pause(message="Press any key to continue...")
         return Result.Ok()
     for file_type, file_type_dict in self.sync_files.items():
         for data_set, (out_of_sync, missing_files,
                        outdated_files) in file_type_dict.items():
             if not out_of_sync:
                 continue
             all_sync_files = []
             missing_count = 0
             outdated_count = 0
             if missing_files:
                 all_sync_files.extend(missing_files)
                 missing_count = len(missing_files)
             if outdated_files:
                 all_sync_files.extend(outdated_files)
                 outdated_count = len(outdated_files)
             table_viewer = self.create_table_viewer(
                 all_sync_files, data_set, file_type, missing_count,
                 outdated_count)
             apply_changes = table_viewer.launch()
             if apply_changes:
                 self.apply_pending_changes(file_type, data_set,
                                            missing_files, outdated_files)
     return Result.Ok()
示例#12
0
def intro():
    game_name = ("""\033[1;32;1m

                    ___________.__
                    \__    ___/|  |__    ____
                      |    |   |  |  \ _/ __ \\
                      |    |   |   Y  \\\\  ___/
                      |____|   |___|  / \___  >
                                    \/      \/\033[1;31;1m
        __      __         .__    __    .__
       /  \    /  \_____   |  |  |  | __|__|  ____    ____
       \   \/\/   /\__  \  |  |  |  |/ /|  | /    \  / ___\\
        \        /  / __ \_|  |__|    < |  ||   |  \/ /_/  >
         \__/\  /  (____  /|____/|__|_ \|__||___|  /\___  /
              \/        \/            \/         \//_____/
                    \tAnd Picking Up Items!\033[0m\033[1;34;1m
                  ________
                 /  _____/ _____     _____    ____
                /   \  ___ \__  \   /     \ _/ __ \\
                \    \_\  \ / __ \_|  Y Y  \\\\  ___/
                 \______  /(____  /|__|_|  / \___  >
                        \/      \/       \/      \/\033[0m

    """)
    os.system('clear')
    print(game_name)
    time.sleep(1)
    pause()
示例#13
0
def know_how():

    know_how = ("""
    \033[0;34;1m
     __  __                                  __  __
    /\ \/\ \                                /\ \/\ \\
    \ \ \/'/'    ___     ___   __  __  __   \ \ \_\ \    ___   __  __  __
     \ \ , <   /' _ `\  / __`\/\ \/\ \/\ \   \ \  _  \  / __`\/\ \/\ \/\ \\
      \ \ \\\\`\ /\ \/\ \/\ \L\ \ \ \_/ \_/ \   \ \ \ \ \/\ \L\ \ \ \_/ \_/ \\
       \ \_\ \_\ \_\ \_\ \____/\ \___x___/'    \ \_\ \_\ \____/\ \___x___/'
        \/_/\/_/\/_/\/_/\/___/  \/__//__/       \/_/\/_/\/___/  \/__//__/\033[0m

    """)

    print(know_how)

    print("\nThe world is in great danger... Well, maybe not whole world...\
    \nBut the part of it... Really important part! Codecool! Collect items,\
    \ntravel through raw and brutal world of early access Walking And Picking up Items Game\
    \nbeat the boss and fulfill your destiny...")

    print(
        "\n\033[0;32;1mCONTROLS:\033[0m\n\nW go up\nS go down\nA go left\nD go right\n"
    )

    print("Collect 5 items to open portal to next level.")

    print(
        "\n\033[0;33;1mTHIS GAME WAS CREATED BY:\033[0m\n\nKlaudia Borowska\nCezary'Czarosław' Broś\
    \nTomasz Budkiewicz\nGrzegorz Bury")
    pause()
示例#14
0
 def launch(self):
     subprocess.run(["clear"])
     print_heading("This feature is not currently available",
                   fg="bright_yellow")
     print_message(
         "Sorry for any inconvenience, I promise to finish this soon!")
     pause(message="\nPress any key to return to the previous menu...")
     return Result.Ok(True)
示例#15
0
 def create_and_populate_database_tables(self):
     self.update_menu_heading("In Progress")
     result = self.app.initialize_database()
     if result.success:
         self.update_menu_heading("Complete!", heading_color="bright_green")
         print_message(DB_INITIALIZED, fg="bright_green", bold=True)
         pause(message="Press any key to continue...")
     return result
示例#16
0
文件: util.py 项目: a-luna/vigorish
def shutdown_cli_immediately():
    subprocess.run(["clear"])
    print_heading("Restart Required!", fg="bright_magenta")
    warning = "Application must be restarted for these changes to take effect."
    print_message(warning, fg="bright_magenta", bold=True)
    print_message("Shutting down vigorish!\n", fg="bright_magenta", bold=True)
    pause(message="Press any key to continue...")
    subprocess.run(["clear"])
    exit(0)
示例#17
0
def moving(dungeon, last_tile_rep, width, height):
    p_coords = find_p(dungeon, width, height)
    p_x = p_coords[0]
    p_y = p_coords[1]

    mv = getch.getch()

    if mv == '\x1b':
        return True

    elif mv == 'w':
        try:
            if '█' not in dungeon[p_y - 1][p_x] and p_y - 1 >= 0:
                last_tile = dungeon[p_y - 1][p_x]
                dungeon[p_y][p_x] = last_tile_rep
                last_tile_rep = last_tile
                p_y -= 1
                dungeon[p_y][p_x] = c.blue + '●'
        except IndexError:
            pass
    elif mv == 'a':
        try:
            if '█' not in dungeon[p_y][p_x - 1] and p_x - 1 >= 0:
                last_tile = dungeon[p_y][p_x - 1]
                dungeon[p_y][p_x] = last_tile_rep
                last_tile_rep = last_tile
                p_x -= 1
                dungeon[p_y][p_x] = c.blue + '●'
        except IndexError:
            pass
    elif mv == 's':
        try:
            if '█' not in dungeon[p_y + 1][p_x]:
                last_tile = dungeon[p_y + 1][p_x]
                dungeon[p_y][p_x] = last_tile_rep
                last_tile_rep = last_tile
                p_y += 1
                dungeon[p_y][p_x] = c.blue + '●'
        except IndexError:
            pass
    elif mv == 'd':
        try:
            if '█' not in dungeon[p_y][p_x + 1]:
                last_tile = dungeon[p_y][p_x + 1]
                dungeon[p_y][p_x] = last_tile_rep
                last_tile_rep = last_tile
                p_x += 1
                dungeon[p_y][p_x] = c.blue + '●'
        except IndexError:
            pass
    if c.green + '$' in last_tile_rep:
        clear()
        getch.pause('Fin.')
        return True
    return [dungeon, last_tile_rep]
示例#18
0
def moving(dungeon,last_tile_rep,width,height):
  p_coords = find_p(dungeon,width,height)
  p_x = p_coords[0]
  p_y = p_coords[1]

  mv = getch.getch()

  if mv == '\x1b':
    return True
  
  elif mv == 'w':
    try:
      if '█' not in dungeon[p_y-1][p_x] and p_y-1 >= 0:
        last_tile = dungeon[p_y-1][p_x]
        dungeon[p_y][p_x] = last_tile_rep
        last_tile_rep = last_tile
        p_y -= 1
        dungeon[p_y][p_x] = c.blue + '●'
    except IndexError:
      pass
  elif mv == 'a':
    try:
      if '█' not in dungeon[p_y][p_x-1] and p_x-1 >= 0:
        last_tile = dungeon[p_y][p_x-1]
        dungeon[p_y][p_x] = last_tile_rep
        last_tile_rep = last_tile
        p_x -= 1
        dungeon[p_y][p_x] = c.blue + '●'
    except IndexError:
      pass
  elif mv == 's':
    try:
      if '█' not in dungeon[p_y+1][p_x]:
        last_tile = dungeon[p_y+1][p_x]
        dungeon[p_y][p_x] = last_tile_rep
        last_tile_rep = last_tile
        p_y += 1
        dungeon[p_y][p_x] = c.blue + '●'
    except IndexError:
      pass
  elif mv == 'd':
    try:
      if '█' not in dungeon[p_y][p_x+1]:
        last_tile = dungeon[p_y][p_x+1]
        dungeon[p_y][p_x] = last_tile_rep
        last_tile_rep = last_tile
        p_x += 1
        dungeon[p_y][p_x] = c.blue + '●'
    except IndexError:
      pass
  if c.green + '$' in last_tile_rep:
    clear()
    getch.pause('Fin.')
    return True
  return [dungeon,last_tile_rep]
示例#19
0
    def enter(self):
        clear()
        print "*" * 50
        print "Information of Account"
        print "*" * 50
        all_account = manager.get_account_all()

        print all_account
        time.sleep(1)
        getch.pause()  #Press any key
        return 'info'
示例#20
0
def showaddress():
    # This function is a user option that will show you what your current home address is set to, without prompting you to set a new one.
    shelf_file = shelve.open('sethome')
    if shelf_file['address'] == '':
        print(
            "\n********You have no QuickMap home address currently set.********\n"
        )
    else:
        print("\n********Your QuickMap home address is " +
              shelf_file['address'] + "********\n")
    pause('\nPress any key to return to menu\n')
示例#21
0
文件: util.py 项目: a-luna/vigorish
def validate_scrape_dates(db_session, start_date, end_date):
    result = db.Season.validate_date_range(db_session, start_date, end_date)
    if result.success:
        season = result.value
        return Result.Ok(season)
    print_heading("\nError! Invalid value for start and/or end dates",
                  fg="bright_red")
    for s in result.error:
        print_message(s, fg="bright_red")
    pause(message="\nPress any key to continue...")
    return Result.Fail("")
示例#22
0
文件: EX.py 项目: s2upins2/backup
 def enter(self):
     clear()
     print "*"*50
     print "Information of Account"
     print  "*"*50
     all_account=manager.get_account_all()
     
    
     print all_account
     time.sleep(1)
     getch.pause()  #Press any key
     return  'info'
示例#23
0
def sync_down_to_local(app, year, file_type, data_set):
    """Sync files from S3 bucket to local folder."""
    data_sets_int = sum(int(ds) for ds in flatten_list2d(data_set))
    result_dict = SyncDataNoPromptsTask(app).execute(
        sync_direction=SyncDirection.DOWN_TO_LOCAL,
        year=year,
        file_type=file_type,
        data_sets_int=data_sets_int,
    )
    result = Result.Combine(list(result_dict.values()))
    if os.environ.get("ENV") != "TEST":  # pragma: no cover
        pause(message="\nPress any key to continue...")
    return exit_app(app, result)
示例#24
0
 def import_scraped_data(self, restart_required):
     if not self.import_scraped_data_prompt():
         return self.setup_complete(restart_required)
     subprocess.run(["clear"])
     self.subscribe_to_events()
     result = self.import_data_task.execute(overwrite_existing=True)
     if result.error:
         print_message(result.error, fg="bright_red")
         pause(message="Press any key to continue...")
     else:
         time.sleep(2)
     self.unsubscribe_from_events()
     return self.setup_complete(restart_required)
示例#25
0
 def display_no_match_found(self, matches):
     subprocess.run(["clear"])
     for match_dict in matches:
         match_dict["invalid_pfx"].pop("at_bat_id")
         match_dict["invalid_pfx"].pop("pitcher_id")
         match_dict["invalid_pfx"].pop("batter_id")
     subprocess.run(["clear"])
     error = "No matching at bats were found for the invalid PitchFX data below:\n"
     print_message(error, fg="bright_red", bold=True)
     unmatched_rows = [match_dict["invalid_pfx"] for match_dict in matches]
     print_message(tabulate(unmatched_rows, headers="keys"), wrap=False)
     print()
     pause(message="Press any key to continue...")
示例#26
0
 def launch(self):
     if not self.prompt_user_run_task():
         return Result.Ok(True)
     self.subscribe_to_events()
     result = self.backup_db.execute()
     self.unsubscribe_from_events()
     self.spinner.stop()
     if result.failure:
         return result
     zip_file = result.value
     subprocess.run(["clear"])
     self.display_zip_file_details(zip_file)
     pause(message="\nPress any key to continue...")
     return Result.Ok(True)
示例#27
0
def data_sets_prompt(
    heading: str = None,
    prompt: str = None,
    valid_data_sets: Optional[List[DataSet]] = None,
    checked_data_sets: Optional[List[DataSet]] = None,
):
    if not prompt:
        prompt = "Select one or multiple data sets from the list below:"
    if not valid_data_sets:
        valid_data_sets = [DataSet.ALL]
    instructions = "(use SPACE BAR to select each data set, ENTER to confirm your selections)"
    valid_data_sets_int = sum(int(ds) for ds in valid_data_sets)
    choices = {
        f"{DATA_SET_TO_NAME_MAP[ds]}": ds
        for ds in DataSet if valid_data_sets_int & ds == ds
    }
    if checked_data_sets:
        checked_int = sum(int(ds) for ds in checked_data_sets)
        checked_data_sets = [
            f"{DATA_SET_TO_NAME_MAP[ds]}" for ds in DataSet
            if checked_int & ds == ds
        ]
    ds_prompt = DataSetCheck(
        prompt=instructions,
        choices=list(choices.keys()),
        checked_data_sets=checked_data_sets,
        check=EMOJIS.get("CHECK", ""),
        shift=1,
        indent=0,
        margin=2,
        check_color=colors.foreground["default"],
        check_on_switch=colors.foreground["default"],
        background_color=colors.foreground["default"],
        background_on_switch=colors.foreground["default"],
        word_color=colors.foreground["default"],
        word_on_switch=colors.bright(colors.foreground["cyan"]),
    )
    data_sets = []
    while not data_sets:
        subprocess.run(["clear"])
        if heading:
            print_heading(heading, fg="bright_yellow")
        print_message(prompt, wrap=True)
        result = ds_prompt.launch()
        if not result:
            print_error("\nYou must select at least one data set!")
            pause(message="Press any key to continue...")
            continue
        data_sets = [DATA_SET_FROM_NAME_MAP[sel] for sel in result]
    return data_sets
示例#28
0
 def enter(self):
     clear()
     print "*" * 50
     print "List SSH Key"
     print "*" * 50
     list_ssh = manager.get_all_sshkeys()
     i = 0
     while i < len(list_ssh):
         print list_ssh[i]
         print "\n\n\n"
         i += 1
     time.sleep(1)
     getch.pause()
     return 'config'
示例#29
0
 def display_results(self):
     subprocess.run(["clear"])
     if self.combined_success_and_no_pfx_errors:
         plural = "games total" if self.total_games > 1 else "game"
         success_message = f"\nAll game data ({self.total_games} {plural}) combined, no errors"
         print_message(success_message,
                       wrap=False,
                       fg="bright_cyan",
                       bold=True)
     if self.failed_game_ids:
         self.display_games_failed_to_combine()
     if self.all_pfx_errors:
         self.display_pitchfx_errors()
     pause(message="Press any key to continue...")
示例#30
0
文件: EX.py 项目: s2upins2/backup
 def enter(self):
     clear()
     print "*"*50
     print "List SSH Key"
     print "*"*50
     list_ssh = manager.get_all_sshkeys()
     i = 0
     while i < len(list_ssh):
         print list_ssh[i]
         print "\n\n\n"
         i+=1
     time.sleep(1)
     getch.pause()        
     return 'config'    
示例#31
0
    def forward(self, feat, right, wrong, fake=None, fake_diff_mask=None):

        num_wrong = wrong.size(1)
        batch_size = feat.size(0)

        feat = feat.view(-1, self.ninp, 1)
        right_dis = torch.bmm(right.view(-1, 1, self.ninp), feat)
        wrong_dis = torch.bmm(wrong, feat)
        # batch_wrong_dis = torch.bmm(batch_wrong, feat)

        if self.debug:
            if self.iter % self.log_iter == 0:
                print('---------------- Scores ------------------')
                rows = [['data_' + str(i) for i in range(batch_size)]]
                # pair_wise_score_diff_np = pair_wise_score_diff.cpu().detach().numpy()
                wrong_scores_np = wrong_dis.cpu().detach().numpy()
                right_scores_np = right_dis.cpu().detach().numpy()

                for j in range(num_wrong):
                    row = []
                    for i in range(batch_size):
                        row.append(
                            '{}:{}'.format(right_scores_np[i], wrong_scores_np[i][j]))
                    rows.append(row)
                st = Texttable()
                st.add_rows(rows)
                print(st.draw())
                pause()

        wrong_score = torch.sum(torch.exp(wrong_dis - right_dis.expand_as(wrong_dis)), 1)


        loss_dis = torch.sum(torch.log(wrong_score + 1))
        loss_norm = right.norm() + feat.norm() + wrong.norm()

        if fake:
            fake_dis = torch.bmm(fake.view(-1, 1, self.ninp), feat)
            fake_score = torch.masked_select(torch.exp(fake_dis - right_dis), fake_diff_mask)

            margin_score = F.relu(torch.log(fake_score + 1) - self.margin)
            loss_fake = torch.sum(margin_score)
            loss_dis += loss_fake
            loss_norm += fake.norm()

        loss = (loss_dis + 0.1 * loss_norm) / batch_size
        if fake:
            return loss, loss_fake.data[0] / batch_size
        else:
            return loss
示例#32
0
文件: EX.py 项目: s2upins2/backup
 def enter(self):
     clear()
     print "*"*50
     print "Information of Droplets"
     print "*"*50
     a = ""
     print "No  ID    {:15}NAME       {:20}IP          {:20}Status".format(a,a,a)
     droplets = manager.get_all_droplets()
     i = 0
     while i < len(droplets):
         print "%d. "%(i+1),droplets[i]
         i+=1
     time.sleep(1)
     getch.pause()  #Press any key
     return 'info'
示例#33
0
 def launch(self):
     if not self.prompt_user_run_task():
         return Result.Ok(True)
     self.subscribe_to_events()
     result = self.calc_pitch_times.execute()
     self.spinner.stop()
     self.unsubscribe_from_events()
     if result.failure:
         return result
     subprocess.run(["clear"])
     results = result.value
     time_between_pitches = db.TimeBetweenPitches.from_calc_results(self.db_session, results)
     self.display_pitch_metrics(time_between_pitches.as_dict())
     pause(message="\nPress any key to continue...")
     return Result.Ok()
示例#34
0
 def enter(self):
     clear()
     print "*" * 50
     print "List Regions"
     print "*" * 50
     a = ""
     print "Name{:20}  Slug{:15}  Available".format(a, a)
     print "=" * 60
     region = manager.get_all_regions()
     i = 0
     while i < len(region):
         print region[i]
         i += 1
     time.sleep(1)
     getch.pause()  #Press any key
     return 'info'
示例#35
0
文件: EX.py 项目: s2upins2/backup
 def enter(self):
     clear()
     print "*"*50
     print "List Regions"
     print "*"*50
     a=""
     print "Name{:20}  Slug{:15}  Available".format(a,a)
     print "="*60
     region = manager.get_all_regions()
     i = 0
     while  i< len(region):
         print region[i]
         i+=1
     time.sleep(1)
     getch.pause()  #Press any key
     return 'info'
示例#36
0
 def launch(self):
     while True:
         subprocess.run(["clear"])
         if self.heading:
             print_heading(self.heading, fg=self.heading_color)
         result = super().launch()
         if not result:
             continue
         try:
             return date_parser.parse(result)
         except ValueError:
             error = f'\nError: "{result}" could not be parsed as a valid date.'
             print_heading(error, fg="bright_red")
             print_message(ERROR_HELP_MESSAGE, fg="bright_red")
             print_message(EXAMPLES, fg="bright_red")
             pause(message="Press any key to continue...")
示例#37
0
文件: EX.py 项目: s2upins2/backup
 def enter(self):
     clear()
     print "*"*50
     print "List Images"
     print "*"*50
     print "\n\n"
     a = ""
     print "  ID{:10}   NAME{:50}    SLUG{:10}              OS      ".format(a,a,a)
     print "="*120
     images = manager.get_all_images()
     i = 0
     while i < len(images):
         print images[i]
         i+=1 
     time.sleep(1)
     getch.pause()  #Press any key
     return 'info'
示例#38
0
    dummy = 0  # Dummy for avoiding indentation failures

db.commit()
db.close()

if scanconfig.cte_step_wait_for_key:
    import os
    if os.name == 'nt':
        import msvcrt
        print "Press any key to close document"
        if msvcrt.kbhit():
            ret = msvcrt.getch()
            done = True

    else:
        from getch import getch, pause
        pause("Press any key to close document")

if scanconfig.cte_export_ods:
    doc.save("./db/" + timestr + ".ods")
    doc.close()

if scanconfig.cte_export_openpyxl:
    doc.save("./db/" + timestr + ".xlsx")

if scanconfig.cte_use_cvcam:
    cam.release()
    cv2.destroyAllWindows()

sws.motorClose()
示例#39
0
文件: EX.py 项目: s2upins2/backup
    def enter(self):
        clear()
        i=1
        a = ""
        print "Droplets Action:"
        print "No  ID    {:15}NAME       {:20}IP          {:20}Status".format(a,a,a)
        my_droplets = manager.get_all_droplets()
        

        for a in my_droplets:
            print "%d. "%(i),a
            i+=1
        print "Choose Action: "
        print "\t1. Turn on"
        print "\t2. Turn off"
        print "\t3. Restart"
        print "\t4. Delete"
        print "\t0. Back"
        choose = raw_input("> ")


        if choose == "1":
            print "Turn On:\nPlz! Enter No  .\nOr Enter 0 for ALL! "
            press = input("> ")
            if press == 0:
                print "Turn on....\nSure that Status of every Droplets is Off"
                for drop in my_droplets:
                    drop.power_on() 
            else :
                my_droplets[press-1].power_on()


        if choose == "2":
            print "Turn Off:\nPlz! Enter No  .\nOr Enter 0 for ALL! "
            press = input("> ")


            if press == 0:
                print "Turn off....\nSure that Status of every Droplets is On"
                for drop in my_droplets:
                    drop.power_off() 
            else :
                my_droplets[press-1].power_off()           



        if choose == "3":
            print "Reboot:\nPlz! Enter No  .\nOr Enter 0 for ALL! "
            press = input("> ")

            if press == 0:
                print "Turn off....\nSure that Status of every Droplets is On"
                for drop in my_droplets:
                    drop.reboot() 
            else :
                my_droplets[press-1].reboot()


        if choose == "4":
            print "Delete:\nPlz! Enter No  .\nOr Enter 0 for ALL! "
            press = input("> ")

            if press == 0:
                print "Delete ALL! Are you sure! Yes/No? "
                confirm = raw_input("> ")
                confirm = confirm.lower()

                if confirm == "yes":
                    print "Turn off....\nSure that Status of every Droplets is On"
                    for drop in my_droplets:
                        drop.destroy() 

                else : 
                    return 'action'

            else :
                print "Delete \n[%s]\n Are you sure ! Yes/No?"%my_droplets[press-1]
                confirm = raw_input("> ")
                confirm = confirm.lower()
                if confirm == "yes":
                    my_droplets[press-1].destroy()
                else :
                    return 'action'            
        if choose == "0":
            return 'config'

        time.sleep(1)
        getch.pause()        
        return 'config'
示例#40
0
from getch import getch, pause

key = getch()
print 'You pressed:', key
pause()