예제 #1
0
def create_product(app, created_models, verbosity, interactive, **kwargs):
    if check_created(created_models, Product):
        call_command("loaddata", "cartridge_required.json")
        if interactive:
            confirm = input("\nWould you like to install an initial "
                            "demo product and sale? (yes/no): ")
            while True:
                if confirm == "yes":
                    break
                elif confirm == "no":
                    return
                confirm = input("Please enter either 'yes' or 'no': ")
        # This is a hack. Ideally to split fixtures between optional
        # and required, we'd use the same approach Mezzanine does,
        # within a ``createdb`` management command. Ideally to do this,
        # we'd subclass Mezzanine's createdb command and shadow it,
        # but to do that, the cartridge.shop app would need to appear
        # *after* mezzanine.core in the INSTALLED_APPS setting, but the
        # reverse is needed for template overriding (and probably other
        # bits) to work correctly.
        # SO........... we just cheat, and check sys.argv here. Namaste.
        elif "--nodata" in sys.argv:
            return
        if verbosity >= 1:
            print()
            print("Creating demo product and sale ...")
            print()
        call_command("loaddata", "cartridge_optional.json")
        copy_test_to_media("cartridge.shop", "product")
예제 #2
0
 def confirm(self, prompt):
     if not self.interactive:
         return True
     confirm = input(prompt)
     while confirm not in ("yes", "no"):
         confirm = input("Please enter either 'yes' or 'no': ")
     return confirm == "yes"
예제 #3
0
def stream_mic(client, device, durations):
    print("Ready to capture your voice query")
    input("Press ENTER to start recording")
    query = None
    query_start = time()
    device.start_recording()
    try:
        recording_stopper = RecordingStopper(device, query_start, durations)

        def keyboard_stop():
            print("Press ENTER to stop recording (or wait for VAD)")
            while device.is_recording():
                res = select([sys.stdin], [], [], 1)
                for sel in res[0]:
                    if sel == sys.stdin:
                        recording_stopper.stop_recording('user_stop')

        keyboard_thread = threading.Thread(target=keyboard_stop)
        keyboard_thread.daemon = True
        keyboard_thread.start()
        query = client.stream_audio(device.generate_frames(), notification_handler=recording_stopper.stop_recording, 
                                    audio_type=device.audio_type())
        recording_stopper.stop_recording(None)
    except ValueError:
        pass
    return query
예제 #4
0
def create_product(app, created_models, verbosity, interactive, **kwargs):
    if Product in created_models:
        call_command("loaddata", "cartridge_required.json")
        if interactive:
            confirm = input("\nWould you like to install an initial "
                                "demo product and sale? (yes/no): ")
            while True:
                if confirm == "yes":
                    break
                elif confirm == "no":
                    return
                confirm = input("Please enter either 'yes' or 'no': ")
        # This is a hack. Ideally to split fixtures between optional
        # and required, we'd use the same approach Mezzanine does,
        # within a ``createdb`` management command. Ideally to do this,
        # we'd subclass Mezzanine's createdb command and shadow it,
        # but to do that, the cartridge.shop app would need to appear
        # *after* mezzanine.core in the INSTALLED_APPS setting, but the
        # reverse is needed for template overriding (and probably other
        # bits) to work correctly.
        # SO........... we just cheat, and check sys.argv here. Namaste.
        elif "--nodata" in sys.argv:
            return
        if verbosity >= 1:
            print()
            print("Creating demo product and sale ...")
            print()
        call_command("loaddata", "cartridge_optional.json")
        copy_test_to_media("cartridge.shop", "product")
예제 #5
0
 def confirm(self, prompt):
     if not self.interactive:
         return True
     confirm = input(prompt)
     while confirm not in ("yes", "no"):
         confirm = input("Please enter either 'yes' or 'no': ")
     return confirm == "yes"
예제 #6
0
    def handle_noargs(self, **options):
        verbosity = int(options.get("verbosity", 0))
        interactive = int(options.get("interactive", 0))
        no_data = int(options.get("nodata", 0))
        if "conf_setting" in connection.introspection.table_names():
            raise CommandError("Database already created, you probably "
                               "want the syncdb or migrate command")

        syncdb.Command().execute(**options)
        if not interactive and not no_data:
            install_optional_data(verbosity)
        if "south" in settings.INSTALLED_APPS:
            try:
                from south.management.commands import migrate
            except ImportError:
                return
            if interactive:
                confirm = input("\nSouth is installed for this project."
                                    "\nWould you like to fake initial "
                                    "migrations? (yes/no): ")
                while True:
                    if confirm == "yes":
                        break
                    elif confirm == "no":
                        return
                    confirm = input("Please enter either 'yes' or 'no': ")
            if verbosity >= 1:
                print()
                print("Faking initial migrations ...")
                print()
            migrate.Command().execute(fake=True)
예제 #7
0
 def complete_member_project(self):
     """
         this method is used to complete project of current gpm.
     """
     try:
         print("choose project")
         project_list = self.get_project_list()
         menu = Menu()
         project_names = [x for x in project_list.keys()]
         project_names.extend([str(BackButton.EXIT.name), str(BackButton.BACK.name)])
         project_name = menu.draw_menu(project_names)
         input()
         if str(BackButton.BACK.name) == project_name:
             return
         project_id = project_list[project_name]
         self.project_id = project_id
         member_ids = self.conn.get_project_member_name(self.project_id)
         member_dict = {}
         for data in member_ids:
             member_dict[data[1]] = data[0]
         menu = Menu()
         member_names = [x for x in member_dict.keys()]
         member_names.extend([str(BackButton.EXIT.name)])
         member_name = menu.draw_menu(member_names)
         input()
         member_id = member_dict[member_name]
         self.member_id = member_id
         self.delete_project_request()
         self.conn.commit_data()
         print(Color.F_Green + "member removal request sent to BDO" + Base.END)
     except sqlite3.Error as e:
         print(e)
         self.conn.rollback_data()
예제 #8
0
def get_login_data():
    print('Please type username and password!')
    username = input('username < ')
    password = input('password < ')
    if not (username and password):
        raise Exception('Method or function hasn\'t been implemented yet.')
    return {'username': username, 'password': password}
    def perform(self, file_access, logger):
        """
        Perform the upgrade step
        Args:
            file_access (FileAccess): file access
            logger (LocalLogger): logger

        Returns: exit code 0 success; anything else fail
        """
        try:
            logger.info("Changing motion set point PVs")

            with CachingFileAccess(file_access):

                changer = ChangePVsInXML(file_access, logger)

                changer.change_pv_name("COORD1", "COORD0")
                changer.change_pv_name("COORD2", "COORD1")

                changer.change_pv_name("COORD0:NO_OFFSET", "COORD0:NO_OFF")
                changer.change_pv_name("COORD1:NO_OFFSET", "COORD1:NO_OFF")

                changer.change_pv_name("COORD0:RBV:OFFSET", "COORD0:RBV:OFF")
                changer.change_pv_name("COORD1:RBV:OFFSET", "COORD1:RBV:OFF")

                changer.change_pv_name("COORD0:LOOKUP:SET:RBV",
                                       "COORD0:SET:RBV")
                changer.change_pv_name("COORD1:LOOKUP:SET:RBV",
                                       "COORD1:SET:RBV")

                if file_access.exists(MOTION_SET_POINTS_FOLDER):
                    print("")
                    print(
                        "{} folder exists. Motion set point configuration has changed significantly"
                        " in this version and must be manually fixed".format(
                            MOTION_SET_POINTS_FOLDER))
                    print(
                        "See https://github.com/ISISComputingGroup/ibex_developers_manual/"
                        "wiki/Motion-Set-points#upgrading-from-720 for how to do this"
                    )
                    input("Press any key to confirm this is done.")
                    print("")

                # CoordX:MTR is gone, hard to automatically replace so just raise as issue
                if changer.get_number_of_instances_of_pv(
                    ["COORD0:MTR", "COORD1:MTR"]) > 0:
                    print(
                        "The PV COORDX:MTR has been found in a config/synoptic but no longer exists"
                    )
                    print(
                        "Manually replace with a reference to the underlying axis and rerun the upgrade"
                    )
                    raise RuntimeError("Underlying motor references")

            return SUCCESS_CODE

        except Exception as e:
            logger.error(
                "Unable to perform upgrade, caught error: {}".format(e))
            return ERROR_CODE
예제 #10
0
 def project_completion(self):
     """
         this method is used to complete project of current gpm.
     """
     try:
         print("choose project")
         project_list = self.get_project_list()
         menu = Menu()
         project_names = [x for x in project_list.keys()]
         project_names.extend([str(BackButton.EXIT.name), str(BackButton.BACK.name)])
         project_name = menu.draw_menu(project_names)
         input()
         if str(BackButton.BACK.name) == project_name:
             return
         project_id = project_list[project_name]
         self.project_id = project_id
         member_ids = self.conn.get_project_members(self.project_id)
         if len(member_ids) == 0:
             print(Color.F_Red+"Can't send project completion request to BDO \n because "
                               "no member assigned to this project \n"+Base.END)
         else:
             for member_id in member_ids:
                 self.member_id = member_id[0]
                 self.delete_project_request()
             self.conn.commit_data()
             print(Color.F_Green + "Wage Request sent to BDO for all the assigned members \n "+ Base.END)
     except sqlite3.Error as e:
         print(e)
         self.conn.rollback_data()
예제 #11
0
    def handle_noargs(self, **options):
        verbosity = int(options.get("verbosity", 0))
        interactive = int(options.get("interactive", 0))
        no_data = int(options.get("nodata", 0))
        if "conf_setting" in connection.introspection.table_names():
            raise CommandError("Database already created, you probably "
                               "want the syncdb or migrate command")

        syncdb.Command().execute(**options)
        if not interactive and not no_data:
            install_optional_data(verbosity)
        if settings.USE_SOUTH:
            try:
                from south.management.commands import migrate
            except ImportError:
                return
            if interactive:
                confirm = input("\nSouth is installed for this project."
                                "\nWould you like to fake initial "
                                "migrations? (yes/no): ")
                while True:
                    if confirm == "yes":
                        break
                    elif confirm == "no":
                        return
                    confirm = input("Please enter either 'yes' or 'no': ")
            if verbosity >= 1:
                print()
                print("Faking initial migrations ...")
                print()
            migrate.Command().execute(fake=True)
예제 #12
0
def spot_remover(spot_df,
                 contrast_df,
                 vcount_dir,
                 iris_path,
                 quarantine_img=False):
    excise_toggle = input(
        "Would you like to remove any spots from the analysis? (y/[n])\t")
    assert isinstance(excise_toggle, str)
    if excise_toggle.lower() in ('y', 'yes'):
        excise_spots = input(
            "Which spots? (Separate all spot numbers by a comma)\t")
        excise_spots = [int(x) for x in excise_spots.split(',')]

        spot_df.loc[spot_df.spot_number.isin(excise_spots), 'validity'] = False

        drop_col_list = [
            col for col in contrast_df.columns
            if int(col.split(".")[0]) in excise_spots
        ]
        contrast_df.drop(columns=drop_col_list, inplace=True)

        os.chdir(vcount_dir)

        vdata_list = glob.glob('*.vdata.txt')
        bad_vfiles = [
            vf for vf in vdata_list if int(vf.split('.')[1]) in excise_spots
        ]
        print(bad_vfiles)
        for vf in bad_vfiles:
            old_vf = vf + '~'
            os.rename(vf, old_vf)
            with open(old_vf, 'r+') as ovf, open(vf, 'w') as nvf:
                lines = ovf.readlines()
                # print(lines)
                for line in lines:
                    if line.split(':')[0] == 'validity':
                        # print(line)
                        nvf.write('validity: False\n')

                    else:
                        nvf.write(line)
            os.remove(old_vf)

        if quarantine_img == True:
            os.chdir(iris_path)
            if not os.path.exists('bad_imgs'):
                os.makedirs('bad_imgs')

            bad_imgs = [
                img for sublist in [
                    glob.glob('*.' + str(spot).zfill(3) + '.*.tif')
                    for spot in excise_spots
                ] for img in sublist
            ]
            for img in bad_imgs:
                os.rename(img, "{}/bad_imgs/{}".format(iris_path, img))

    return spot_df, contrast_df
예제 #13
0
def human_oracle(evidence):
    """Simple text interface to query a human for fact generation."""
    colored_fact, colored_segment = evidence.colored_fact_and_text()
    print(u'SEGMENT: %s' % colored_segment)
    question = ' FACT: {0}? (y/n/stop) '.format(colored_fact)
    answer = input(question)
    while answer not in ['y', 'n', 'stop']:
        answer = input(question)
    return answer
예제 #14
0
파일: __init__.py 프로젝트: sanwong15/RL
def connect_to_unreal(_env, args):
    """
    Start or connect to an existing instance of the Deepdrive
    simulator running in Unreal Engine
    """
    if args.use_sim_start_command:
        # TODO: Find a better way to do this. Waiting for the hwnd and focusing does not work in windows.
        input('Press any key when the game has loaded')
    _env.connect(args.cameras)
예제 #15
0
 def compare(a, b):
     print("%s ? %s (> or <) for %s" % (a, b, feature))
     answer = input()
     while answer not in [">", "<"]:
         print("%s ? %s (> or <) for %s" % (a, b, feature))
         answer = input()
     if answer == ">":
         return 1
     if answer == "<":
         return -1
예제 #16
0
def human_oracle(evidence, possible_answers):
    """Simple text interface to query a human for fact generation."""
    colored_fact, colored_segment = evidence.colored_fact_and_text()
    print(u'SEGMENT: %s' % colored_segment)
    question = ' FACT: {0}? ({1}) '.format(colored_fact,
                                           u'/'.join(possible_answers))
    answer = input(question)
    while answer not in possible_answers:
        answer = input(question)
    return answer
예제 #17
0
파일: terminal.py 프로젝트: 52nlp/iepy
def human_oracle(evidence, possible_answers):
    """Simple text interface to query a human for fact generation."""
    colored_fact, colored_segment = evidence.colored_fact_and_text()
    print(u'SEGMENT: %s' % colored_segment)
    question = ' FACT: {0}? ({1}) '.format(colored_fact,
                                           u'/'.join(possible_answers))
    answer = input(question)
    while answer not in possible_answers:
        answer = input(question)
    return answer
예제 #18
0
def manual_cookies():
    url = input('url << ')
    anti_spider(url)
    code_img_save()

    input_code = input('code << ')

    verify_code(input_code)

    return _get_cookies()
예제 #19
0
def Initialize(config=None,
               external_hostname=None,
               admin_password=None,
               redownload_templates=False,
               repack_templates=True,
               token=None):
    """Initialize or update a GRR configuration."""

    print("Checking write access on config %s" % config["Config.writeback"])
    if not os.access(config.parser.filename, os.W_OK):
        raise IOError("Config not writeable (need sudo?)")

    print("\nStep 0: Importing Configuration from previous installation.")
    options_imported = 0
    prev_config_file = config.Get("ConfigUpdater.old_config", default=None)
    if prev_config_file and os.access(prev_config_file, os.R_OK):
        print("Found config file %s." % prev_config_file)
        # pytype: disable=wrong-arg-count
        if builtins.input("Do you want to import this configuration? "
                          "[yN]: ").upper() == "Y":
            options_imported = ImportConfig(prev_config_file, config)
        # pytype: enable=wrong-arg-count
    else:
        print("No old config file found.")

    print("\nStep 1: Setting Basic Configuration Parameters")
    print(
        "We are now going to configure the server using a bunch of questions.")
    ConfigureDatastore(config)
    ConfigureUrls(config, external_hostname=external_hostname)
    ConfigureEmails(config)

    print("\nStep 2: Key Generation")
    if config.Get("PrivateKeys.server_key", default=None):
        if options_imported > 0:
            print(
                "Since you have imported keys from another installation in the "
                "last step,\nyou probably do not want to generate new keys now."
            )
        # pytype: disable=wrong-arg-count
        if (builtins.input(
                "You already have keys in your config, do you want to"
                " overwrite them? [yN]: ").upper() or "N") == "Y":
            config_updater_keys_util.GenerateKeys(config, overwrite_keys=True)
        # pytype: enable=wrong-arg-count
    else:
        config_updater_keys_util.GenerateKeys(config)

    FinalizeConfigInit(config,
                       token,
                       admin_password=admin_password,
                       redownload_templates=redownload_templates,
                       repack_templates=repack_templates,
                       prompt=True)
예제 #20
0
파일: terminal.py 프로젝트: 52nlp/iepy
 def get_human_answer(self, evidence):
     keys = u'/'.join(self.keys)
     c_fact, c_text = self.formatter.colored_fact_and_text(evidence)
     question = self.template % {
         'keys': keys, 'fact': c_fact,
         'text': c_text
     }
     answer = input(question)
     while answer not in self.keys:
         answer = input('Invalid answer. (%s): ' % keys)
     return answer
예제 #21
0
def Initialize(config=None,
               external_hostname = None,
               admin_password = None,
               redownload_templates = False,
               repack_templates = True,
               token = None):
  """Initialize or update a GRR configuration."""

  print("Checking write access on config %s" % config["Config.writeback"])
  if not os.access(config.parser.filename, os.W_OK):
    raise IOError("Config not writeable (need sudo?)")

  print("\nStep 0: Importing Configuration from previous installation.")
  options_imported = 0
  prev_config_file = config.Get("ConfigUpdater.old_config", default=None)
  if prev_config_file and os.access(prev_config_file, os.R_OK):
    print("Found config file %s." % prev_config_file)
    # pytype: disable=wrong-arg-count
    if builtins.input("Do you want to import this configuration? "
                      "[yN]: ").upper() == "Y":
      options_imported = ImportConfig(prev_config_file, config)
    # pytype: enable=wrong-arg-count
  else:
    print("No old config file found.")

  print("\nStep 1: Setting Basic Configuration Parameters")
  print("We are now going to configure the server using a bunch of questions.")
  ConfigureDatastore(config)
  ConfigureUrls(config, external_hostname=external_hostname)
  ConfigureEmails(config)

  print("\nStep 2: Key Generation")
  if config.Get("PrivateKeys.server_key", default=None):
    if options_imported > 0:
      print("Since you have imported keys from another installation in the "
            "last step,\nyou probably do not want to generate new keys now.")
    # pytype: disable=wrong-arg-count
    if (builtins.input("You already have keys in your config, do you want to"
                       " overwrite them? [yN]: ").upper() or "N") == "Y":
      config_updater_keys_util.GenerateKeys(config, overwrite_keys=True)
    # pytype: enable=wrong-arg-count
  else:
    config_updater_keys_util.GenerateKeys(config)

  FinalizeConfigInit(
      config,
      token,
      admin_password=admin_password,
      redownload_templates=redownload_templates,
      repack_templates=repack_templates,
      prompt=True)
예제 #22
0
 def delete_gpm(self):
     """
       this method is used to delete gpm for current bdo.
     """
     try:
         print("choose gmp to delete:\n")
         gpm_list = self.get_gpm_list()
         menu = Menu()
         gpm_names = [x for x in gpm_list.keys()]
         gpm_names.extend(
             [str(BackButton.EXIT.name),
              str(BackButton.BACK.name)])
         gpm_name = menu.draw_menu(gpm_names)
         input()
         if gpm_name == str(BackButton.BACK.name):
             return
         self.gpm_id = gpm_list.pop(gpm_name)
         os.system('clear')
         print('choose another gpm to assign current gpm members:\n')
         menu2 = Menu()
         if len(gpm_list.keys()) == 0:
             print(
                 Color.F_Red +
                 "Can't delete GPM because you don't have any alternative GPM "
                 + Base.END)
             return
         alternative_gpm_names = [x for x in gpm_list.keys()]
         alternative_gpm_names.extend(
             [str(BackButton.EXIT.name),
              str(BackButton.BACK.name)])
         alternative_gpm_name = menu2.draw_menu(alternative_gpm_names)
         input()
         if alternative_gpm_name == str(BackButton.BACK.name):
             return
         # assigning new gpm to members
         self.conn.update_member_gpm(gpm_list[alternative_gpm_name],
                                     self.gpm_id)
         # completing all gpm projects
         project_ids = self.conn.get_gpm_projects(self.gpm_id)
         for project_id in project_ids:
             self.project_id = project_id
             member_ids = self.conn.get_project_members(self.project_id)
             for member_id in member_ids:
                 self.member_id = member_id[0]
                 self.delete_project_members()
         self.conn.update_user('is_deleted', self.gpm_id, 'True')
         self.conn.commit_data()
     except Exception as e:
         print(e)
         self.conn.rollback_data()
예제 #23
0
 def get_human_answer(self, evidence):
     keys = u'/'.join(self.keys)
     c_fact, c_text = evidence.colored_fact_and_text()
     question = self.template % {
         'keys': keys,
         'fact': c_fact,
         'text': c_text
     }
     if PY2:
         question = question.encode('utf-8')
     answer = input(question)
     while answer not in self.keys:
         answer = input('Invalid answer. (%s): ' % keys)
     return answer
예제 #24
0
파일: login.py 프로젝트: riyaz489/mnrega
def main():
    """
    this method is used to call main menu for login
    """
    conn = ConnectDb()
    try:
        os.system('clear')
        # select role for login
        print("login as:\n")
        menu = Menu()
        roles = [x.name for x in Role]
        roles.extend([str(BackButton.EXIT.name)])
        role = menu.draw_menu(roles)
        role_id = Role[role].value
        input()

        # get user name and password for login
        user_name = input("enter user name: ")
        password = getpass()

        # check user authentication
        result = conn.get_user_with_role(user_name, role_id)
        flag = True
        if result is not None:
            os.system('clear')
            actual_pass = decrypt_pass(result[1])
            if str(actual_pass.decode("utf-8")) == password:
                flag = False
                if role_id == int(Role.BDO.value):
                    bdo = BDO()
                    bdo.bdo_id = result[0]
                    bdo.bdo_features()
                elif role_id == int(Role.GPM.value):
                    gpm = GPM()
                    gpm.gpm_id = result[0]
                    gpm.gpm_features()
                elif role_id == int(Role.Member.value):
                    member = Member()
                    member.member_id = result[0]
                    member.member_features()
        if result is None or flag:
            print(Color.F_Red + 'wrong credentials' + Base.END)
            input()
            main()

    except Exception as e:
        print(e)
        sys.exit()
    finally:
        conn.close_conn()
예제 #25
0
 def assign_members_to_projects(self):
     """
           this method is used to assign member to project of current gpm.
     """
     print("choose project")
     project_list = self.get_project_list()
     menu = Menu()
     project_names = [x for x in project_list.keys()]
     project_names.extend(
         [str(BackButton.EXIT.name),
          str(BackButton.BACK.name)])
     project_name = menu.draw_menu(project_names)
     input()
     if str(BackButton.BACK.name) == project_name:
         return
     project_id = project_list[project_name]
     print("choose member for project")
     members_list = self.get_members_list()
     self.project_id = project_id
     project_members_id = self.conn.get_project_members(self.project_id)
     # removing already assigned members from the list
     for id in project_members_id:
         temp = None
         for key, value in members_list.items():
             if id[0] == value:
                 temp = key
                 break
         members_list.pop(temp, None)
     members_required = self.conn.get_project_members_required(
         self.project_id)
     # checking if total number of members in given project are less then actual project requirement
     if members_required[0] <= len(project_members_id):
         print(Color.F_Red + "members limit exceeded" + Base.END)
         return
     # removing members who are already in some projects
     members_list = {
         key: value
         for key, value in members_list.items()
         if project_members_id.count(value) == 0
     }
     menu = Menu()
     member_names = [x for x in members_list.keys()]
     member_names.extend([str(BackButton.EXIT.name)])
     member_name = menu.draw_menu(member_names)
     input()
     member_id = members_list[member_name]
     self.member_id = member_id
     self.assign_project_members_request()
예제 #26
0
    def show_requests(self):
        """
            this method is used show request and resolve request of current gpm.
        """
        try:
            projects = self.conn.get_requests(self.gpm_id)
            result = projects.fetchall()
            counter = 0
            # getting columns for showing requests and adding index column at first in list
            projects_fields = (('index'),) + projects.description
            # request is empty then returning early with a message
            if len(result) == 0:
                print(Color.F_Red + "there is no pending request" + Base.END)
                return
            temp = result
            # converting list of tuples into list of list
            temp = [list(elem) for elem in temp]
            print("write index of request to manage:\n")
            for request in temp:
                request.insert(0, counter)
                counter += 1
            table = PrettyTable()
            table.field_names = [column[0] for column in projects_fields[:-1]]
            for row in temp:
                table.add_row(row[:-1])
            print(table)
            row_number = input("enter index number: ")
            if not Validation.is_int(row_number):
                print("row number is not valid")
                input()
                return
            menu = Menu()
            result_names = [x.name for x in RequestResult]
            result_names.extend([str(BackButton.EXIT.name)])
            result_name = menu.draw_menu(result_names)
            input()
            status = "NULL"
            if str(result_name) == str(RequestResult.APPROVED.name):
                status = "'True'"
            elif str(result_name) == str(RequestResult.REJECTED.name):
                status = "'False'"

            self.conn.resolve_request(status, result[int(row_number)][4])
            self.conn.commit_data()
            print(Color.F_Green + "Request completed successfully" + Base.END)
        except Exception as e:
            print(e)
            self.conn.rollback_data()
예제 #27
0
    def handle_noargs(self, **options):
        verbosity = int(options.get("verbosity", 0))
        interactive = int(options.get("interactive", 0))
        no_data = int(options.get("nodata", 0))
        if "conf_setting" in connection.introspection.table_names():
            raise CommandError("Database already created, you probably "
                               "want the syncdb or migrate command")

        syncdb.Command().execute(**options)
        if not interactive and not no_data:
            install_optional_data(verbosity)
        if settings.USE_SOUTH:
            try:
                from south.management.commands import migrate
            except ImportError:
                pass
            else:
                confirm = "yes"
                if interactive:
                    confirm = input("\nSouth is installed for this project."
                                        "\nWould you like to fake initial "
                                        "migrations? (yes/no): ")
                    while confirm not in ("yes", "no",):
                        confirm = input("Please enter either 'yes' or 'no': ")
                if confirm == "yes":
                    if verbosity >= 1:
                        print()
                        print("Faking initial migrations ...")
                        print()
                    migrate.Command().execute(fake=True)
        if settings.USE_MODELTRANSLATION and settings.USE_I18N:
            try:
                from modeltranslation.management.commands \
                        import update_translation_fields
            except ImportError:
                return
            if interactive:
                confirm = input("\nDjango-modeltranslation is installed for "
                                "this project and you have specified to use "
                                "i18n.\nWould you like to update translation "
                                "fields from the default ones? (yes/no): ")
                while True:
                    if confirm == "yes":
                        break
                    elif confirm == "no":
                        return
                    confirm = input("Please enter either 'yes' or 'no': ")
            update_translation_fields.Command().execute(verbosity=verbosity)
예제 #28
0
def ask_question(question, allowed=None):
    """ Asks a yes/no question to the user """
    readline = get_readline()
    if allowed is None:
        allowed = {
            'y': True,
            'Y': True,
            'yes': True,
            'n': False,
            'N': False,
            'no': False
        }
    while True:
        line = builtins.input(question)
        line = line.strip()

        # we don't want these to go into the history
        if readline is not None:
            try:
                l = readline.get_current_history_length()
                if l:
                    readline.remove_history_item(l - 1)
            except:
                pass

        if line in allowed:
            return allowed[line]
예제 #29
0
def ask_question(question, allowed=None):
    """ Asks a yes/no question to the user """
    readline = get_readline()
    if allowed is None:
        allowed = {
            'y': True,
            'Y': True,
            'yes': True,
            'n': False,
            'N': False,
            'no': False
        }
    while True:
        line = builtins.input(question)
        line = line.strip()

        # we don't want these to go into the history
        if readline is not None:
            try:
                l = readline.get_current_history_length()
                if l:
                    readline.remove_history_item(l - 1)
            except:
                pass

        if line in allowed:
            return allowed[line]
예제 #30
0
def main():
    # Create the EventHandler and pass it your bot's token.
    token = 'TOKEN'
    updater = Updater(token, workers=10)

    # Get the dispatcher to register handlers
    dp = updater.dispatcher

    # This is how we add handlers for Telegram messages
    dp.add_handler(CommandHandler("start", start))
    dp.add_handler(CommandHandler("help", help))
    # Message handlers only receive updates that don't contain commands
    dp.add_handler(MessageHandler([Filters.text], message))
    # Regex handlers will receive all updates on which their regex matches,
    # but we have to add it in a separate group, since in one group,
    # only one handler will be executed
    dp.add_handler(RegexHandler('.*', any_message), group=1)

    # String handlers work pretty much the same. Note that we have to tell
    # the handler to pass the args or update_queue parameter
    dp.add_handler(StringCommandHandler('reply', cli_reply, pass_args=True))
    dp.add_handler(StringRegexHandler('[^/].*', cli_noncommand,
                                      pass_update_queue=True))

    # All TelegramErrors are caught for you and delivered to the error
    # handler(s). Other types of Errors are not caught.
    dp.add_error_handler(error)

    # Start the Bot and store the update Queue, so we can insert updates
    update_queue = updater.start_polling(timeout=10)

    '''
    # Alternatively, run with webhook:

    update_queue = updater.start_webhook('0.0.0.0',
                                         443,
                                         url_path=token,
                                         cert='cert.pem',
                                         key='key.key',
                                         webhook_url='https://example.com/%s'
                                             % token)

    # Or, if SSL is handled by a reverse proxy, the webhook URL is already set
    # and the reverse proxy is configured to deliver directly to port 6000:

    update_queue = updater.start_webhook('0.0.0.0', 6000)
    '''

    # Start CLI-Loop
    while True:
        text = input()

        # Gracefully stop the event handler
        if text == 'stop':
            updater.stop()
            break

        # else, put the text into the update queue to be handled by our handlers
        elif len(text) > 0:
            update_queue.put(text)
예제 #31
0
 def run(self):
     if not exists(self.env.venv_path):
         prompt = input("\nVirtualenv doesn't exist: %s"
                        "\nWould you like to create it? (yes/no) " %
                        self.env.proj_name)
         if prompt.lower() != "yes":
             print("\nAborting!")
             return False
         CreateTask(self.env).run()
     for name in self.get_templates():
         self.upload_template_and_reload(name)
     with self.project():
         BackupTask(self.env).run("last.db")
         static_dir = self.static()
         if exists(static_dir):
             self.run_command("tar -cf last.tar %s" % static_dir)
         git = self.env.git
         last_commit = "git rev-parse HEAD" if git else "hg id -i"
         self.run_command("%s > last.commit" % last_commit)
         with self.update_changed_requirements():
             if git:
                 self.run_command("git pull origin master -f")
             else:
                 self.run_command("hg pull && hg up -C")
         manage_task = ManageTask(self.env)
         manage_task.run("collectstatic -v 0 --noinput")
         manage_task.run("syncdb --noinput")
         manage_task.run("migrate --noinput")
     RestartTask(self.env).run()
     return True
예제 #32
0
 def run(self):
     if not exists(self.env.venv_path):
         prompt = input("\nVirtualenv doesn't exist: %s"
                        "\nWould you like to create it? (yes/no) "
                        % self.env.proj_name)
         if prompt.lower() != "yes":
             print("\nAborting!")
             return False
         CreateTask(self.env).run()
     for name in self.get_templates():
         self.upload_template_and_reload(name)
     with self.project():
         BackupTask(self.env).run("last.db")
         static_dir = self.static()
         if exists(static_dir):
             self.run_command("tar -cf last.tar %s" % static_dir)
         git = self.env.git
         last_commit = "git rev-parse HEAD" if git else "hg id -i"
         self.run_command("%s > last.commit" % last_commit)
         with self.update_changed_requirements():
             if git:
                 self.run_command("git pull origin master -f")
             else:
                 self.run_command("hg pull && hg up -C")
         manage_task = ManageTask(self.env)
         manage_task.run("collectstatic -v 0 --noinput")
         manage_task.run("syncdb --noinput")
         manage_task.run("migrate --noinput")
     RestartTask(self.env).run()
     return True
예제 #33
0
def get_slice_input(num_elements):
    while True:
        try:
            string = input(
                '\nEnter a number or interval (e.g. 8 or 5-10). (q to quit): ')
            slice_match = re.match(r'^(\d*)[:-](\d*)$', string)
            index_match = re.match(r'^(\d+)$', string)
            quit_match = re.match(r'^q$', string.lower())
            if slice_match:
                slice_min = int(slice_match.group(1) or 0)
                slice_max = int(slice_match.group(2) or num_elements - 1)
            elif index_match:
                slice_min = int(index_match.group(1))
                slice_max = slice_min
            elif quit_match:
                print('OK, quitting program\n')
                sys.exit(0)
            else:
                raise SyntaxError('Syntax not allowed')

            # Check the values of the ints
            if slice_min > slice_max:
                raise ValueError('Max is not larger than min')
            if slice_max >= num_elements or slice_min > num_elements - 1:
                raise ValueError('Value is too high')

        except Exception as e:
            # An exception was generated above
            print('Sorry, not a valid input: {}\n'.format(e))
            continue
        else:
            # No exception generated above, we're done
            break

    return slice(slice_min, slice_max + 1)
예제 #34
0
def msbuild():
    SHELL = msbuild_module.Shell()
    line = p_line('Death') + p_line('windows') + p_line(
        'msbuild') + green + '[shellcode]' + yellow + ' $> '
    p_dec(SHELL.desc_reverse)
    shellcode = input(line)
    print(SHELL.payload.format(shellcode=shellcode))
def deploy():
    """
    Deploy latest version of the project.
    Check out the latest version of the project from version
    control, install new requirements, sync and migrate the database,
    collect any new static assets, and restart gunicorn's work
    processes for the project.
    """
    if not exists(env.venv_path):
        prompt = input("\nVirtualenv doesn't exist: %s\nWould you like "
                           "to create it? (yes/no) " % env.proj_name)
        if prompt.lower() != "yes":
            print("\nAborting!")
            return False
        create()
    for name in get_templates():
        upload_template_and_reload(name)
    with project():
        backup("last.db")
        static_dir = static()
        if exists(static_dir):
            run("tar -cf last.tar %s" % static_dir)
        git = env.git
        last_commit = "git rev-parse HEAD" if git else "hg id -i"
        run("%s > last.commit" % last_commit)
        with update_changed_requirements():
            run("git pull origin master -f" if git else "hg pull && hg up -C")
        manage("collectstatic -v 0 --noinput")
        manage("compress")
        with project():
            run('chmod -R o+rX static')
        manage("syncdb --noinput")
        manage("migrate --noinput")
    gunicorn('restart')
    return True
def read_param_file():
    ''' Asks for, reads and formats the parameter file
    '''
    if len(sys.argv) < 2:
        p_param = input('\nPlease inform the path to the json config file:\n')
    else:
        p_param = sys.argv[1]
    stable = False
    while not stable:
        tmp = p_param.strip('"').strip("'").strip(' ')
        stable = tmp == p_param
        p_param = tmp
    if os.path.isdir(p_param):
        f_names = [
            os.path.join(p_param, f) for f in os.listdir(p_param)
            if '.json' in f and not '~' in f
        ]
    else:
        f_names = [p_param]

    params = []
    for file_name in f_names:
        print('')
        print("Extraction of the parameters from file %s" % file_name)
        p = trsf_parameters(file_name)
        if not p.check_parameters_consistancy():
            print("\n%s Failed the consistancy check, it will be skipped")
        else:
            params += [p]
        print('')
    return params
def deploy():
    """
    Deploy latest version of the project.
    Check out the latest version of the project from version
    control, install new requirements, sync and migrate the database,
    collect any new static assets, and restart gunicorn's work
    processes for the project.
    """
    if not exists(env.venv_path):
        prompt = input("\nVirtualenv doesn't exist: %s"
                       "\nWould you like to create it? (yes/no) "
                       % env.proj_name)
        if prompt.lower() != "yes":
            print("\nAborting!")
            return False
        create()
    for name in get_templates():
        upload_template_and_reload(name)
    with project():
        backup("last.db")
        static_dir = static()
        if exists(static_dir):
            run("tar -cf last.tar %s" % static_dir)
        git = env.git
        last_commit = "git rev-parse HEAD" if git else "hg id -i"
        run("%s > last.commit" % last_commit)
        with update_changed_requirements():
            run("git pull origin master -f" if git else "hg pull && hg up -C")
        manage("collectstatic -v 0 --noinput")
        manage("syncdb --noinput")
        manage("migrate --noinput")
    restart()
    return True
예제 #38
0
    def start(self):
        """ Routersploit main entry point. Starting interpreter loop. """

        print_info(self.banner)
        printer_queue.join()
        payloadFile = 0

        # add a function
        # let me test iot automate
        self.loadAutoScript()
        while True:
            try:
                command, args = self.parse_line(input(self.prompt))
                print_status('%s :: %s'%(command,args))
                
                if not command:
                    continue
                command_handler = self.get_command_handler(command)

                command_handler(args)
            except RoutersploitException as err:
                print_error(err)
            except EOFError:
                print_info()
                print_status("routersploit stopped")
                break
            except KeyboardInterrupt:
                print_info()
            finally:
                printer_queue.join()
예제 #39
0
 def getInput(self, _message):
     global firstTime
     global runningScript
     global emoteClassOn
     if runningScript == True:
         if firstTime == False:
             self.message = input('\n\tWrite message to be analyzed: ')
             _message = self.message
             self.countPunct(_message)
             self.countWordSent(_message)
             self.runAnalysis(_message)
         else:
             print(
                 """\n\tNow starting Emote as a script. Use Emote Mass Analyzer to break down a text into individual sentence 
              classifications, or import Emote as a library.""")
             firstTime = False
             self.initialTrain()
     else:
         if firstTime == True:
             # print("\nFIRST TIME IS TRUE")
             print("\n\tRunning Emote as a library..")
             self.message = _message
             emoteClassOn = True
             self.countPunct(_message)
             self.countWordSent(_message)
             self.runAnalysis(_message)
         else:
             # print("\nFIRST TIME IS FALSE")
             emoteClassOn = False
             self.message = _message
             self.countPunct(_message)
             self.countWordSent(_message)
             self.runAnalysis(_message)
예제 #40
0
def run(resume_dir=None,
        data_dir=c.RECORDING_DIR,
        agent_name=None,
        overfit=False,
        eval_only=False,
        tf_debug=False,
        freeze_pretrained=False,
        train_args_collection_name=None):
    show_tfboard_hint()
    if agent_name == c.DAGGER_MNET2:
        if not glob.glob(data_dir + '/*.tfrecord'):
            tfrecord_dirs = glob.glob(data_dir + '/*' + c.TFRECORD_DIR_SUFFIX)
            if len(tfrecord_dirs) == 0:
                raise RuntimeError('No tfrecord directories found')
            elif len(tfrecord_dirs) > 1:
                dir_num = None
                while dir_num is None:
                    question = 'Which tfrecord directory would you like to train on?'
                    for i, tfrecord_dir in enumerate(tfrecord_dirs):
                        question += '\n%d) %s' % (i + 1, tfrecord_dir)
                    dir_num = int(
                        input(question + '\nEnter index above: ').strip())
                    if dir_num > len(tfrecord_dirs):
                        dir_num = None
                        print('Invalid directory number')
                data_dir = tfrecord_dirs[dir_num - 1]
        # Use tf-slim training
        if eval_only:
            eval_mobile_net(data_dir)
        else:
            train_mobile_net(data_dir, resume_dir, train_args_collection_name)
    else:
        custom_train_loop(agent_name, data_dir, eval_only, freeze_pretrained,
                          overfit, resume_dir, tf_debug)
예제 #41
0
파일: base.py 프로젝트: inyoka/mezzanine
 def trunc(self, model, prompt, **fields):
     """
     Truncates fields values for the given model. Prompts for a new
     value if truncation occurs.
     """
     for field_name, value in list(fields.items()):
         field = model._meta.get_field(field_name)
         max_length = getattr(field, "max_length", None)
         if not max_length:
             continue
         elif not prompt:
             fields[field_name] = value[:max_length]
             continue
         while len(value) > max_length:
             encoded_value = value.encode("utf-8")
             new_value = eval(
                 input(
                     "The value for the field %s.%s exceeds "
                     "its maximum length of %s chars: %s\n\nEnter a new value "
                     "for it, or press return to have it truncated: " %
                     (model.__name__, field_name, max_length,
                      encoded_value)))
             value = new_value if new_value else value[:max_length]
         fields[field_name] = value
     return fields
예제 #42
0
def StdIn():
    """
    Generator that emulates `sys.stdin`. Uses `input()` builtin
    rather than directly using sys.stdin to allow usage within an
    interactive session.
    """
    while True:
        yield input()
예제 #43
0
파일: commands.py 프로젝트: lowks/ido
def get_answer(message, answers='Yn', default='Y', quit=''):
    """
    Get an answer from stdin, the answers should be 'Y/n' etc.
    If you don't want the user can quit in the loop, then quit should be None.
    """
    if quit and quit not in answers:
        answers = answers + quit
        
    message = message + '(' + '/'.join(answers) + ')[' + default + ']:'
    ans = input(message).strip().upper()
    if default and not ans:
        ans = default.upper()
    while ans not in answers.upper():
        ans = input(message).strip().upper()
    if quit and ans == quit.upper():
        print("Command be cancelled!")
        sys.exit(1)
    return ans
예제 #44
0
def compmake_console_lines(context):
    """ Returns lines with at least one character. """
    readline = get_readline()

    if readline is not None:
        try:
            # Rewrite history
            # TODO: use readline's support for history
            if os.path.exists(COMPMAKE_HISTORY_FILENAME):
                with open(COMPMAKE_HISTORY_FILENAME) as f:
                    lines = f.read().split('\n')

                with open(COMPMAKE_HISTORY_FILENAME, 'w') as f:
                    last_word = None
                    for word in lines:
                        word = word.strip()
                        if len(word) == 1:
                            continue  # 'y', 'n'
                        if word in ['exit', 'quit', 'ls']:
                            continue
                        if word == last_word:  # no doubles
                            continue
                        f.write('%s\n' % word)
                        last_word = word

            # noinspection PyUnresolvedReferences
            readline.read_history_file(COMPMAKE_HISTORY_FILENAME)
        except:
            pass

        # noinspection PyUnresolvedReferences
        readline.set_history_length(300)
        completer = lambda text, state: tab_completion2(context, text, state)
        # noinspection PyUnresolvedReferences
        readline.set_completer(completer)
        # noinspection PyUnresolvedReferences
        readline.set_completer_delims(" ")
        # noinspection PyUnresolvedReferences
        readline.parse_and_bind('tab: complete')

    while True:
        clean_console_line(sys.stdout)

        # TODO: find alternative, not reliable if colored
        # line = raw_input(colored('@: ', 'cyan'))
        line = builtins.input('@: ')
        line = line.strip()
        if not line:
            continue

        if readline is not None:
            # noinspection PyUnresolvedReferences
            readline.write_history_file(COMPMAKE_HISTORY_FILENAME)

        yield line
예제 #45
0
def SwitchToRelDB(config):
  """Switches a given config from using AFF4 to using REL_DB."""
  if config["Database.enabled"]:
    print(
        "New generation datastore (REL_DB) is already enabled in the config.\n"
        "Nothing to do.")
    return

  print("***************************************************************\n"
        "Make sure to back up the existing configuration writeback file,\n"
        "you will need it if you decide to switch to the old datastore.\n"
        "Writeback file path:\n%s\n"
        "***************************************************************\n" %
        config["Config.writeback"])
  RetryBoolQuestion("Continue?", True)

  config.Set("Database.enabled", True)
  config.Set("Database.aff4_enabled", False)
  config.Set("Database.implementation", "MysqlDB")

  if (config["Blobstore.implementation"] == "MemoryStreamBlobStore" or
      RetryBoolQuestion(
          "You have a custom 'Blobstore.implementation' setting. Do you want to\n"
          "switch to DbBlobStore (default option for REL_DB, meaning that blobs\n"
          "will be stored inside the MySQL database)?", True)):
    config.Set("Blobstore.implementation", "DbBlobStore")

  if (RetryBoolQuestion(
      "Do you want to use a different MySQL database for the REL_DB datastore?",
      True)):
    db_name = RetryQuestion("MySQL Database", "^[A-Za-z0-9-]+$",
                            config["Mysql.database_name"])
  else:
    db_name = config["Mysql.database_name"]
  config.Set("Mysql.database", db_name)

  if (builtins.input(
      "Do you want to use previously set up MySQL username and password\n"
      "to connect to MySQL database '%s'? [Yn]: " % db_name).upper() or
      "Y") == "Y":
    username = config["Mysql.database_username"]
    password = config["Mysql.database_password"]
  else:
    username = RetryQuestion("MySQL Username", "[A-Za-z0-9-@]+$",
                             config["Mysql.database_username"])
    # TODO(hanuszczak): Incorrect type specification for `getpass`.
    # pytype: disable=wrong-arg-types
    password = getpass.getpass(
        prompt="Please enter password for database user %s: " % username)

  config.Set("Mysql.username", username)
  config.Set("Mysql.password", password)

  print("Configuration updated.")
예제 #46
0
파일: __init__.py 프로젝트: JPWKU/mezzanine
def create_pages(app, created_models, verbosity, interactive, **kwargs):

    if not is_full_install():
        return

    from mezzanine.pages.models import Page
    from mezzanine.forms.models import Form
    from mezzanine.galleries.models import Gallery

    if check_created(created_models, Page, Form, Gallery):
        call_command("loaddata", "mezzanine_required.json")
        if interactive:
            confirm = input("\nWould you like to install some initial "
                              "demo pages?\nEg: About us, Contact form, "
                              "Gallery. (yes/no): ")
            while confirm not in ("yes", "no"):
                confirm = input("Please enter either 'yes' or 'no': ")
            install_optional = (confirm == "yes")
        else:
            install_optional = True
        if install_optional:
            install_optional_data(verbosity)
예제 #47
0
def check_folders(name):
    """Only checks and asks questions. Nothing is written to disk."""

    if os.getcwd().endswith('analyses'):
        correct = input('You are in an analyses folder. This will create '
                        'another analyses folder inside this one. Do '
                        'you want to continue? (y/N)')
        if correct != 'y':
            return False

    if not os.path.exists(os.path.join(os.getcwd(), 'analyses')):
        correct = input('This is the first analysis here. Do '
                        'you want to continue? (y/N)')
        if correct != 'y':
            return False

    if os.path.exists(os.path.join(os.getcwd(), 'analyses', name)):
        correct = input('An analysis with this name exists already. Do '
                        'you want to continue? (y/N)')
        if correct != 'y':
            return False

    return True
예제 #48
0
def create_virtualenv():
    if not exists(env.venv_home):
        run('mkdir -p %s' % env.venv_home)
    with cd(env.venv_home):
        if exists(env.proj_name):
            prompt = input("\nVirtualenv exists: %s\nWould you like "
                               "to replace it? (yes/no) " % env.proj_name)
            if prompt.lower() != "yes":
                print("\nAborting!")
                return False
            remove()
        run("virtualenv %s --distribute" % env.proj_name)
        vcs = "git" if env.git else "hg"
        run("%s clone %s %s" % (vcs, env.repo_url, env.proj_path))
예제 #49
0
def create_pages(app, created_models, verbosity, interactive, **kwargs):

    if not is_full_install():
        return

    from mezzanine.pages.models import Page
    from mezzanine.forms.models import Form
    from mezzanine.galleries.models import Gallery

    required = set([Page, Form, Gallery])
    if required.issubset(set(created_models)):
        call_command("loaddata", "mezzanine_required.json")
        if interactive:
            confirm = input("\nWould you like to install some initial "
                                "demo pages?\nEg: About us, Contact form, "
                                "Gallery. (yes/no): ")
            while True:
                if confirm == "yes":
                    break
                elif confirm == "no":
                    return
                confirm = input("Please enter either 'yes' or 'no': ")
            install_optional_data(verbosity)
def transformData(STORMX, STORMY, rate):
    userInput = input('8 = up, 2 = down, 4 = left, 6 = right')
    if userInput == 8:
        STORMX_UP = np.subtract(STORMX, rate)
        return STORMX_UP, STORMY 
    if userInput == 2:
        STORMX_DOWN = np.add(STORMX, rate)
        return STORMX_DOWN, STORMY
    if userInput == 4:
        STORMY_LEFT = np.subtract(STORMY, rate)
        return STORMX, STORMY_LEFT 
    if userInput == 6:
        STORMY_RIGHT = np.add(STORMY, rate)
        return STORMX, STORMY_RIGHT
    return STORMX, STORMY
예제 #51
0
def RetryQuestion(question_text, output_re="", default_val=None):
  """Continually ask a question until the output_re is matched."""
  while True:
    if default_val is not None:
      new_text = "%s [%s]: " % (question_text, default_val)
    else:
      new_text = "%s: " % question_text
    # pytype: disable=wrong-arg-count
    output = builtins.input(new_text) or str(default_val)
    # pytype: enable=wrong-arg-count
    output = output.strip()
    if not output_re or re.match(output_re, output):
      break
    else:
      print("Invalid input, must match %s" % output_re)
  return output
예제 #52
0
def create_site(app, created_models, verbosity, interactive, **kwargs):
    if Site in created_models:
        domain = "127.0.0.1:8000" if settings.DEBUG else gethostname()
        if interactive:
            entered = input("\nA site record is required.\nPlease "
                                "enter the domain and optional port in "
                                "the format 'domain:port'.\nFor example "
                                "'localhost:8000' or 'www.example.com'. "
                                "\nHit enter to use the default (%s): " %
                                domain)
            if entered:
                domain = entered.strip("': ")
        if verbosity >= 1:
            print()
            print("Creating default site record: %s ... " % domain)
            print()
        Site.objects.create(name="Default", domain=domain)
예제 #53
0
def create_app():
    """
    Create a new folder for the client side code (angularjs app).
    Pulls the angularjs app  repo from gitlab,
    """
    with cd(env.venv_home):
        if exists(env.app_name):
            prompt = input("\nApp exists: %s"
                           "\nWould you like to replace it? (yes/no) "
                           % env.app_name)
            if prompt.lower() != "yes":
                print("\nAborting!")
                return False
            sudo("rm -rf %s" % env.app_name)
        run("mkdir %s" % env.app_name)
        with cd(env.app_name):
            vcs = "git" if env.git else "hg"
            run("%s clone %s" % (vcs, env.app_repo_url))
예제 #54
0
def getUserInput(message,type):
    """
        This method will obptain the user input, and it wil handle any type of bad input
    :param message: Display message to user
    :param type:  supported INT, STR
    :return: It return a boolean, if true input was valid,otherwise false
             It returns the input obtain from the user
    """
    validInput = False
    while not validInput:
        try:
            userInput = input(message)

            if type == "int":
                return True, int(userInput)
            else:
                return True, userInput
        except Exception as ex:
            print("Please provide a " + ("number" if  type == "int" else "Alpha-value") , end='')
예제 #55
0
 def get(self):
   value = self.default
   # Check for a command line parameter.
   for i in range(len(sys.argv)):
     if sys.argv[i].startswith('--%s=' % self.name):
       value = sys.argv[i].split('=')[1]
     elif sys.argv[i] == '--%s' % self.name:
       value = sys.argv[i + 1]
   # If the param was not on the command line, ask the user to input the
   # value.
   # In order for this to prompt the user, the default value for the option
   # must be None.
   if value is None:
     prompt = '%s: ' % self.prompt
     if self.secret:
       value = getpass.getpass(prompt)
     else:
       print('You can specify this on the command line using --%s' % self.name)
       value = input(prompt)
   return value
예제 #56
0
 def create_site(self):
     domain = "127.0.0.1:8000" if settings.DEBUG else gethostname()
     if self.interactive:
         entered = input("\nA site record is required.\nPlease "
                           "enter the domain and optional port in "
                           "the format 'domain:port'.\nFor example "
                           "'localhost:8000' or 'www.example.com'. "
                           "\nHit enter to use the default (%s): " %
                         domain)
         if entered:
             domain = entered.strip("': ")
     if self.verbosity >= 1:
         print("\nCreating default site record: %s ...\n" % domain)
     try:
         site = Site.objects.get()
     except Site.DoesNotExist:
         site = Site()
     site.name = "Default"
     site.domain = domain
     site.save()
예제 #57
0
def FinalizeConfigInit(config,
                       token,
                       admin_password = None,
                       redownload_templates = False,
                       repack_templates = True,
                       prompt = True):
  """Performs the final steps of config initialization."""
  config.Set("Server.initialized", True)
  print("\nWriting configuration to %s." % config["Config.writeback"])
  config.Write()
  print("Initializing the datastore.")
  # Reload the config and initialize the GRR database.
  server_startup.Init()

  print("\nStep 3: Adding GRR Admin User")
  try:
    CreateUser("admin", password=admin_password, is_admin=True)
  except UserAlreadyExistsError:
    if prompt:
      # pytype: disable=wrong-arg-count
      if ((builtins.input("User 'admin' already exists, do you want to "
                          "reset the password? [yN]: ").upper() or "N") == "Y"):
        UpdateUser("admin", password=admin_password, is_admin=True)
      # pytype: enable=wrong-arg-count
    else:
      UpdateUser("admin", password=admin_password, is_admin=True)

  print("\nStep 4: Repackaging clients with new configuration.")
  if prompt:
    redownload_templates = RetryBoolQuestion(
        "Server debs include client templates. Re-download templates?", False)
    repack_templates = RetryBoolQuestion("Repack client templates?", True)
  if redownload_templates:
    InstallTemplatePackage()
  # Build debug binaries, then build release binaries.
  if repack_templates:
    repacking.TemplateRepacker().RepackAllTemplates(upload=True, token=token)
  print("\nGRR Initialization complete! You can edit the new configuration "
        "in %s.\n" % config["Config.writeback"])
  print("Please restart the service for the new configuration to take "
        "effect.\n")
예제 #58
0
파일: commands.py 프로젝트: lowks/ido
def get_input(prompt, default=None, choices=None, option_value=None):
    """
    If option_value is not None, then return it. Otherwise get the result from 
    input.
    """
    if option_value is not None:
        return option_value
    
    choices = choices or []
    while 1:
        r = input(prompt+' ').strip()
        if not r and default is not None:
            return default
        if choices:
            if r not in choices:
                r = None
            else:
                break
        else:
            break
    return r
예제 #59
0
    def start(self):
        """ Routersploit main entry point. Starting interpreter loop. """

        print_info(self.banner)
        printer_queue.join()
        while True:
            try:
                command, args = self.parse_line(input(self.prompt))
                if not command:
                    continue
                command_handler = self.get_command_handler(command)
                command_handler(args)
            except RoutersploitException as err:
                print_error(err)
            except EOFError:
                print_info()
                print_status("routersploit stopped")
                break
            except KeyboardInterrupt:
                print_info()
            finally:
                printer_queue.join()
예제 #60
0
파일: base.py 프로젝트: desecho/mezzanine
 def trunc(self, model, prompt, **fields):
     """
     Truncates fields values for the given model. Prompts for a new
     value if truncation occurs.
     """
     for field_name, value in fields.items():
         field = model._meta.get_field(field_name)
         max_length = getattr(field, "max_length", None)
         if not max_length:
             continue
         elif not prompt:
             fields[field_name] = value[:max_length]
             continue
         while len(value) > max_length:
             encoded_value = value.encode("utf-8")
             new_value = input("The value for the field %s.%s exceeds "
                 "its maximum length of %s chars: %s\n\nEnter a new value "
                 "for it, or press return to have it truncated: " %
                 (model.__name__, field_name, max_length, encoded_value))
             value = new_value if new_value else value[:max_length]
         fields[field_name] = value
     return fields