def restore_backups_for_dir(self,delfile=False):
   versionlist=[]
   backedup=False
   for vaulthash, vaultval in self.vtable.items():
     for vaultfilename, comment in vaultval[0].items():
       if os.path.dirname(vaultfilename) == self.dirname:
         versionlist.append([vaulthash,vaultfilename,"   ",vaultval[5],comment,vaultval[4],vaultval[6]]) 
   if len(versionlist) > 0:
     versionlist=sorted(versionlist, key=itemgetter(3))
     menulist=[]
     for arecord in versionlist:
       menulist.append(" %s %11d %s%s %s" % (arecord[3],arecord[6],basename(arecord[1]),arecord[2],arecord[4]))
     menulist.append(" abort")
     if delfile:
       option, index = pick(menulist, "Backups available for deletion from vault:")
     else:
       option, index = pick(menulist, "Backups available for specified directory:")
     if option == " abort":
       print ("\ncancelled\n")
       sys.exit()
     hash_to_restore = ("%s" % (versionlist[index][0]))  #FIX?
     file_to_restore = ("%s" % (versionlist[index][1]))  #FIX?
     file_permissions = ("%s" % (versionlist[index][5])) #FIX?
     if self.newname:
       file_to_restore=self.newname
     copyfile(self.vault+"/versions/"+hash_to_restore,file_to_restore,self.vault,delfile,hash_to_restore)
     if delfile:
       remove_from_table(self.vault, hash_to_restore, file_to_restore)
       print ("\nFile %s removed from vault." % (file_to_restore))
     else:
       origperm=int(file_permissions)
       os.chmod(file_to_restore, origperm)  # set permissions just in case copy2 didn't do it.
       print ("\nFile %s restored." % (file_to_restore))
   print ("")
def main():

    contexts, active_context = config.list_kube_config_contexts()
    if not contexts:
        print("Cannot find any context in kube-config file.")
        return
    contexts = [context['name'] for context in contexts]
    active_index = contexts.index(active_context['name'])
    cluster1, first_index = pick(contexts, title="Pick the first context",
                                 default_index=active_index)
    cluster2, _ = pick(contexts, title="Pick the second context",
                       default_index=first_index)

    client1 = client.CoreV1Api(
        api_client=config.new_client_from_config(context=cluster1))
    client2 = client.CoreV1Api(
        api_client=config.new_client_from_config(context=cluster2))

    print("\nList of pods on %s:" % cluster1)
    for i in client1.list_pod_for_all_namespaces().items:
        print("%s\t%s\t%s" %
              (i.status.pod_ip, i.metadata.namespace, i.metadata.name))

    print("\n\nList of pods on %s:" % cluster2)
    for i in client2.list_pod_for_all_namespaces().items:
        print("%s\t%s\t%s" %
              (i.status.pod_ip, i.metadata.namespace, i.metadata.name))
Beispiel #3
0
    def get_values_interactive(self):
        selected_reftime    = pick(self.reftimes, "select reftime: ", multi_select=True, min_selection_count=1)
        selected_start_time = pick(self.timesteps, "select start", min_selection_count=0)
        selected_end_time   = pick(self.timesteps, "select end", min_selection_count=0)
        locations.update({'other':'lon,lat'})
        selected_coords = pick(list(locations.keys()), 'select location or insert custom', min_selection_count=1)
        selected_count = pick([1,10,100,1000,10000], 'count', min_selection_count=1)
#        print("selected coordinates", selected_coords)
        if selected_coords[0][0] == 'other':
            selected_lon = input("insert lon")
            selected_lat = input("insert lat")
            assert selected_lon >= -180
            assert selected_lon <= 360
            assert selected_lat <= 90
            assert selected_lat >= -90
        else:
            selected_lon = locations[selected_coords[0]][0]
            selected_lat = locations[selected_coords[0]][1]
            
        print("Is this correct:")
        print("reftime:", selected_reftime)
        print("start:", selected_start_time)
        print("end:", selected_end_time)
        assert input("y/n: ") == "y"
        start_time = selected_start_time[0]
        self.values['testloc'] = self.ds.get_json_data_in_pandas(debug=self.debug, **{'reftime_start':selected_reftime[0][0].isoformat(), 
                                                         'reftime_end':selected_reftime[-1][0].isoformat(), 
                                                         'vars':self.varname,
                                                         'lon':selected_lon,'lat':selected_lat,
                                                         'count':selected_count[0]})
Beispiel #4
0
def main(devices=devices):
  if argParser.version_info:
    print version
  if argParser.unzip_bsp:
    bspFile()
  if argParser.unzip_apps:
    appFile()
  if argParser.pull_calib:
    pull_title = "Are devices set to enable USB debugging??"
    options = ["yes", "no"]
    _, pull_pick = pick(options, pull_title)
    if pull_pick == 0:
      for device in devices:
        pull_calib(device)
  time.sleep(2)
  if argParser.unlock_device:
    for device in devices:
      #unlockThread =threading.Thread(target=unlock,
      #                               args=(device))
      #unlockThread.start()
      #unlockThread.join()
      unlock(device)
  if argParser.nv_flash_device:
    nv_title = "This will nvFlash your device, are you sure?"
    nv_options = ["yes","no"]
    _, nv_flash = pick(nv_options, nv_title)
    if nv_flash == 0:
      for device in devices:
        nvFlash(device)
  if argParser.flash_device:
    title = "Are all devices ready to flash?"
    options = ["yes", "no"]
    _, flash_pick = pick(options, title)
    if flash_pick == 0:
      for device in devices:
        if len(devices) < 3:
          flashThread = threading.Thread(target=flashDevices,
                                    args=(bspPath + BSPChrono(), device))
          flashThread.start()
          flashThread.join()
        else:
          flashDevices(bspPath + BSPChrono(), device)
  if argParser.pull_calib and argParser.user_build and argParser.flash_device:
    push_title = "Ensure devices are set to enable USB debugging."
    options = ["ok"]
    _, push_pick = pick(options, push_title)
    for device in devices:
      push_calib(device)
  if argParser.push_apps or argParser.tango_core:
    for device in devices:
      installApks(AppChrono() + "-" + incrementer, device, appUnzipPath)
  if argParser.reboot:
    reboot(devices)
  cleanup()
Beispiel #5
0
    def remove(self, jarvis, s):
        data = self.get_data(jarvis)
        if len(data) == 0:
            jarvis.say("Nothing to remove!")
            return

        if s.startswith("everything") or s.startswith("all"):
            for entry in data:
                self.clean_up_entry(jarvis, entry)

            data = []
            self.save_data(jarvis, data)

            jarvis.say("ok")
            return

        # open selection menu
        ask_str = []
        for entry in data:
            ask_str.append(self.format(jarvis, entry))

        title = 'Please choose task to remove (select with space)'
        selected = pick(ask_str, title, multi_select=True)
        selected = [entry[1] for entry in selected]

        new_data = []
        for index, entry in enumerate(data):
            entry = data[index]
            if index not in selected:
                new_data.append(entry)
            else:
                self.clean_up_entry(jarvis, entry)

        self.save_data(jarvis, new_data)
Beispiel #6
0
def check_datasets_against_storage(device, device_dataset_path):
  """Test on-device storage against local storage to ensure that datasets
     have been pulled before wiping datasets from device, and before pulling 
     datasets unnecessarily. Then pull and wipe as necessary.
  """
  devices_to_pull = []
  venue_name = raw_input("Venue name:").upper()
  storage_dataset_path = None

  try:
    storage_dataset_path = [glob("%s/*" % i) for i in glob("/media"
    "/atap/*/*") if venue_name in i][0]
  except IndexError:
    title = ("Either invalid input (%s), or you don't "
    "have an external drive connected. Make sure things "
    "are connected and start again." % venue_name)
    _, ok = pick.pick(["Continue", "Cancel"], title)
    if ok == 0:
      print "Continuing from the beginning."
      check_datasets_against_storage()
    else:
      print "Exiting"
      exit(1)

  command = "adb -s %s shell ls %s" % (device, device_dataset_path)
  device_datasets = os.popen(command).read().split("\r\n")
  for device_dataset in device_datasets:
    if device_dataset != "" and device_dataset not in storage_dataset_path:
      print "Dataset %s not already pulled, will pull "
      "from this device (%s)." % (device_dataset, device)
      devices_to_pull += device

  return devices_to_pull
Beispiel #7
0
def main():
  check_OS_version()
  check_for_fastboot()
  fastboot_commands = [["partition:0", "gpt_both0.bin"], ["partition:1", "gpt_both1.bin"], 
  ["partition:2", "gpt_both2.bin"], ["partition:3", "gpt_both3.bin"], 
  ["partition:4", "gpt_both4.bin"], ["partition:5", "gpt_both5.bin"], 
  ["bootloader", "bootloader.img"], ["dsp", "adspso.bin"], ["mdtp", "mdtp.img"], 
  ["splash", "splash.img"], ["asusfw", "asusfw.img"], ["reboot-bootloader"], 
  ["modem", "NON-HLOS.bin"], ["boot", "boot.img"], ["recovery", "recovery.img"], 
  ["system", "system.img"], ["ADF"], ["asdf"], ["erase", "metadata"]]
  try:
    log = open("%s/fastboot.log" % os.getcwd(), "r")
    log.truncate()
  except IOError:
    log = open("%s/fastboot.log" % os.getcwd(), "w")
  print "Flashing all connected devices: %s" % devices
  print "Saving log data to fastboot.log"
  title = ("Make sure all connected devices have been " 
           "Factory Data Reset before continuing")
  _, fdr = pick.pick(["Continue", "Exit"], title)
  if fdr == 1:
    exit(0)
  for fastboot_command in fastboot_commands:
    for device in devices:
      with open("fastboot.log", "r+") as log:
        flash_pistachio(device, fastboot_command, log)
  os.system("fastboot oem uart-off")
  os.system("fastboot reboot -w")
def pick_window():
    options=['all matches','3','5','7','10','15','20','32']
    option, index = pick(options,"all matches or just a window?")
    if index==0:
        return 0
    else:
        return int(option)
    def select_file(self):
        """
        select_file(self)
        
        Returns
        -------
        option : Str, selection of file id

        """
       
        # get all files in raw predictions folder 
        rawpredlist = list(filter(lambda k: '.csv' in k, os.listdir(self.rawpred_path)))
       
        # get all files in user verified predictions
        verpredlist = list(filter(lambda k: '.csv' in k, os.listdir(self.verpred_path)))
       
        # get unique list
        not_analyzed_filelist = list(set(rawpredlist) - set(verpredlist))
        
        # remaining filelist
        analyzed_filelist = list(set(rawpredlist) - set(not_analyzed_filelist))
        
        # filelist
        filelist = [' *** ' + s for s in analyzed_filelist] +  not_analyzed_filelist           
        
        # select from command list
        title = 'Please select file for analysis: '
        option, index = pick(filelist, title, indicator = '-> ')
        return option.replace(' *** ','')
        def fix_time_attribute(self, layer_object, validation_dict, dry_run):
            # find date fields
            resource = layer_object.resource
            metadata = dict(resource.metadata)

            fields = requests.get(layer_object.resource.href.replace(
                '.xml', '.json'), auth=(rest_user, rest_pass))
            the_fields = fields.json()['featureType']['attributes']
            dates = [field.get('name') for field in the_fields['attribute'] if 'Time' in field.get(
                'binding') or 'Date' in field.get('binding')]

            if len(dates) == 0:
                add_unfixable(layer_object.name,
                              'Layer does not contain a time attribute')
                return
            elif len(dates) == 1:
                metadata['time'].attribute = dates[0]
            else:
                title = 'More than one date field found for {0} please select which to use for time attribute'.format(
                    layer_object.name)
                option, index = pick(dates, title)
                metadata['time'].attribute = dates[index]

            resource.metadata = metadata
            if dry_run is False:
                resource.catalog.save(resource)

            check_layer = gs.get_layer(layer_object.name)
            if check_valid_attribute(validation_dict, check_layer.resource.metadata.get('time'), 'attribute', None) is False:
                self.stdout.write(
                    'Could not set attribute for {0}'.format(layer_object.name))
            else:
                self.stdout.write('Attribute set to {0} for {1}'.format(
                    metadata['time'].attribute, layer_object.name))
Beispiel #11
0
def getFileList(rootDIR):
    global username
    while True:
        title = "Please choose the student UBIT name to grade"
        list_dirs = os.walk(rootDIR)
        options = []
        for root, dirs, files in list_dirs:
            for d in dirs:
                options.append(os.path.join(root, d))
        init_index = 0
        try:
            init_index = readPos()
        except:
            pass
        option, index = pick(options, title, indicator='=>', default_index=init_index)
        username = option
        savePos(index)


        title = "Please choose the file name that you want to grade ('.v','.zip','.tar','rar')."
        def go_back(picker):
            return (None, -1)

        for files in os.walk(rootDIR+option):
            f = files[2]
        picker = Picker(f, title, indicator='=>')
        picker.register_custom_handler(curses.KEY_LEFT,  go_back)
        option2, index2 = picker.start()
        #print option2
        # run autograding 
        print option+option2
        autoGrading(option+"/"+option2)
Beispiel #12
0
def main():

    name = 'busybox-test'
    resp = None

    timestr = time.strftime("%Y%m%d-%H%M%S")
    contexts, active_context = config.list_kube_config_contexts()
    if not contexts:
        print("Cannot find any context in kube-config file.")
        return

    # Create Python List of all contexts for use by PICK Module
    contexts = [context['name'] for context in contexts]
    active_index = contexts.index(active_context['name'])

    # PICK to select SOURCE Cluster for KMOTION
    cluster1, first_index = pick(contexts, title="Pick the source Cluster Context for the POD to kmotioned",
                                 default_index=active_index)
    client1 = client.CoreV1Api(
        api_client=config.new_client_from_config(context=cluster1))

    # Create Python List of all PODs in SRC Namespace for PICK Module
    source_pods = [i.metadata.name for i in client1.list_pod_for_all_namespaces().items]
    selected_pod = pick(source_pods, title="Pick the POD to be backed up")

    pod_name == selected_pod.metadata.name  # Return the Kubernetes API POD object
    pod_namespace == selected_pod.metadata.name
    try:
        resp = client1.read_namespaced_pod(name=i.metadata.name,
                                       namespace='default')
    except ApiException as e:
        if e.status != 404:
            print("Unknown error: %s" % e)
            exit(1)

    if not resp:
        print("Error--> Pod %s does not exist. " % name)


    while True:
        resp = client1.read_namespaced_pod(name=i.metadata.name,
                                       namespace='lucky13')
        if resp.status.phase != 'Pending':
            break
        time.sleep(1)
    print("Done.")
Beispiel #13
0
	def more_drinks(self):
		y_n = ["Yes", "No"]
		self.option, self.add_drinks = pick(y_n, f"{self.name}, would you like another drink?")
		if self.add_drinks == 0:
			self.init()
		else:
			self.order_total()
		return
Beispiel #14
0
 def select_finisher(self, options, state):
     if not isinstance(options, list):
         options = [options]
     option_text = []
     for opt in options:
         option_text.append(str(opt))
     finisher, i = pick(options, 'Choose your Finisher:', '=>')
     return options[i]
def confirm_selector(title):
    options = [{'label': '是', 'value': True}, {'label': '否', 'value': False}]
    selected, idx = pick(options,
                         title,
                         multi_select=False,
                         min_selection_count=1,
                         options_map_func=lambda option: option.get('label'))
    return selected.get('value')
Beispiel #16
0
def set_file():
    directory_files = [s for s in os.listdir() if s.endswith('.md')]
    title = 'Choose file for processing:> '
    file_to_open, index = pick(directory_files, title)

    # user input for file to open
    #    file_to_open = input("What file do you want to open? > ")
    file_process(file_to_open)
Beispiel #17
0
 def get_behavior(self, actions, state, trigger):
     ctx = state_string_cli(state)
     if len(actions) > 1:
         action_opts_text = []
         for a in actions:
             behaviors = state.get_permitted_behaviors(a)
             b_strings = []
             for b in behaviors:
                 b_strings.append(str(b))
             action_opts_text.append(' OR '.join(b_strings))
         a, ai = pick(action_opts_text, ctx + 'Select an action', '=>')
         chosen_a = actions[ai]
     else:
         chosen_a = actions[0]
     permitted = state.get_permitted_behaviors(chosen_a)
     b, bi = pick(permitted, ctx + 'Choose your move', '=>')
     return chosen_a, permitted[bi]
Beispiel #18
0
 def __init__(self, args):
     CloudData.__init__(self, platform=self.GCP_PLATFORM)
     profile_name = args.profile
     if not profile_name:
         profile_name, _ = pick(list(self.GCP_PROFILES.keys()),
                                'Pick Profile')
     profile = self.GCP_PROFILES[profile_name]
     self._install_config['baseDomain'] = profile['base_domain']
Beispiel #19
0
 def __init__(self, args):
     CloudData.__init__(self, platform=self.AZURE_PLATFORM)
     subscription = args.profile
     if not subscription:
         subscription, _ = pick(list(self.AZURE_BASE_DOMAINS.keys()),
                                'Pick Subscription')
     self._install_config['baseDomain'] = self.AZURE_BASE_DOMAINS[
         subscription]
Beispiel #20
0
 def show_menu(self):
     exit_code = True
     # while exit_code:
     option, index = pick(self.main_options, self.main_title)
     if option == "环境安装":
         # 进入二级菜单
         option, index = pick(self.sub_options, self.subtitle)
         # 返回主菜单
         if option == "返回主菜单":
             pick(self.main_options, self.main_title)
         else:
             # 其他命令使用install函数安装
             self.install(option)
     elif option == "退出":
         exit(0)
     elif option == "工具使用":
         print('工具使用')
Beispiel #21
0
def pick_assessment():
    option, index = pick(
        PICK_OPTIONS,
        'Please select an assessment from the list:',
        indicator='=>',
        default_index=0,
    )
    return OPTIONS[option]
Beispiel #22
0
def pick_cmd(name, limit=100):
    hm = HistoryMap(os.path.join(os.environ['HOME'], '.tm2m'))
    history = hm[name]
    history.load()
    lst = [x.cmd.strip('\n') for x in history.lst[:limit]]
    title = "Command using {} ({}):".format(name, history.fname)
    cmd, _ = pick.pick(lst, title)
    return cmd
Beispiel #23
0
def choose():
    title = 'pick the topic of words'
    options = [
        file.replace("./words/", "").replace(".txt", "")
        for file in glob("./words/*.txt")
    ]
    option, index = pick(options, title)
    return option
    def get_values_interactive(self):
        selected_reftime = pick(self.reftimes,
                                "select reftime: ",
                                multi_select=True,
                                min_selection_count=1)
        selected_start_time = pick(self.timesteps,
                                   "select start",
                                   min_selection_count=0)
        selected_end_time = pick(self.timesteps,
                                 "select end",
                                 min_selection_count=0)
        locations.update({'other': 'lon,lat'})
        selected_coords = pick(list(locations.keys()),
                               'select location or insert custom',
                               min_selection_count=1)
        selected_count = pick([1, 10, 100, 1000, 10000],
                              'count',
                              min_selection_count=1)
        #        print("selected coordinates", selected_coords)
        if selected_coords[0][0] == 'other':
            selected_lon = input("insert lon")
            selected_lat = input("insert lat")
            assert selected_lon >= -180
            assert selected_lon <= 360
            assert selected_lat <= 90
            assert selected_lat >= -90
        else:
            selected_lon = locations[selected_coords[0]][0]
            selected_lat = locations[selected_coords[0]][1]

        print("Is this correct:")
        print("reftime:", selected_reftime)
        print("start:", selected_start_time)
        print("end:", selected_end_time)
        assert input("y/n: ") == "y"
        start_time = selected_start_time[0]
        self.values['testloc'] = self.ds.get_json_data_in_pandas(
            debug=self.debug,
            **{
                'reftime_start': selected_reftime[0][0].isoformat(),
                'reftime_end': selected_reftime[-1][0].isoformat(),
                'vars': self.varname,
                'lon': selected_lon,
                'lat': selected_lat,
                'count': selected_count[0]
            })
 def restore_backup_by_name(self,delfile=False,latest=False):
   versionlist=[]
   backedup=False
   searchstring=re.compile(self.meta[1].keys()[0],re.I)
   for vaulthash, vaultval in self.vtable.items():
     for vaultfilename, comment in vaultval[0].items():
       hit = searchstring.search(vaultfilename)
       if hit:                                   
         if vaulthash == self.meta[0]:
           versionlist.append([vaulthash,vaultfilename," X ",vaultval[5],comment,vaultval[4],vaultval[6]])
           backedup=True
         else:
           versionlist.append([vaulthash,vaultfilename,"   ",vaultval[5],comment,vaultval[4],vaultval[6]])
   if len(versionlist) > 0:
     versionlist=sorted(versionlist, key=itemgetter(3))
     menulist=[]
     for arecord in versionlist:
       menulist.append(" %s %11d %s%s %s" % (arecord[3],arecord[6],basename(arecord[1]),arecord[2],arecord[4]))
     menulist.append(" abort")
     if delfile:
       option, index = pick(menulist, "Versions available for removal from vault:")
     else:
       if not latest and len(versionlist) > 1:
         option, index = pick(menulist, "Versions available:")
       else:
         option = ""
         index=0
         if len(versionlist) > 1:
           index = -1 
     if option == " abort":
       print ("\ncancelled\n")
       sys.exit()
     hash_to_restore = ("%s" % (versionlist[index][0]))
     file_to_restore = ("%s" % (versionlist[index][1]))
     file_permissions = ("%s" % (versionlist[index][5]))
     if self.newname:
       file_to_restore=self.newname
     copyfile(self.vault+"/versions/"+hash_to_restore,file_to_restore,self.vault,delfile,hash_to_restore)
     if delfile:
       remove_from_table(self.vault, hash_to_restore, file_to_restore)
       print ("\nFile %s removed from vault." % (file_to_restore))
     else:
       origperm=int(file_permissions)
       os.chmod(file_to_restore, origperm)  # set permissions just in case copy2 didn't do it.
       print ("\nFile %s restored." % (file_to_restore))
   print ("")
def prompt_two_option_pick(pick_title, pick_options):
    '''
    Function to display two option pick by passing title and options
    It returns a boolean value 'True' for index 0 and 'False' for index 1
    '''
    pick_option, index = pick(pick_options, pick_title)
    pick_bool = True if(index==0) else False
    return(pick_bool)
Beispiel #27
0
 def get_choices_inventory(self):
     chosen_option, index = pick(self.options_inventory, self.title)
     if index == 0:
         self.get_list_vms()
     elif index == 1:
         self.get_list_datastores()
     elif index == 2:
         exit(0)
Beispiel #28
0
def interactive(Qz, path, limit, tracks=True, embed_art=False):
    while True:
        Albums, Types, IDs = [], [], []
        try:
            while True:
                query = input("\nEnter your search: [Ctrl + c to quit]\n- ")
                print("Searching...")
                if len(query.strip()) == 0:
                    break
                start = Search(Qz, query, limit)
                start.getResults(tracks)
                if len(start.Total) == 0:
                    break
                Types.append(start.Types)
                IDs.append(start.IDs)

                title = (
                    "Select [space] the item(s) you want to download "
                    "(zero or more)\nPress Ctrl + c to quit\n"
                )
                Selected = pick(
                    start.Total, title, multiselect=True, min_selection_count=0
                )
                if len(Selected) > 0:
                    Albums.append(Selected)

                    y_n = pick(
                        ["Yes", "No"],
                        "Items were added to queue to be downloaded. Keep searching?",
                    )
                    if y_n[0][0] == "N":
                        break
                else:
                    break

            if len(Albums) > 0:
                desc = (
                    "Select [intro] the quality (the quality will be automat"
                    "ically\ndowngraded if the selected is not found)"
                )
                Qualits = ["320", "Lossless", "Hi-res =< 96kHz", "Hi-Res > 96 kHz"]
                quality = pick(Qualits, desc, default_index=1)
                processSelected(Qz, path, Albums, IDs, Types, quality, embed_art)
        except KeyboardInterrupt:
            sys.exit("\nBye")
def get_player2():
    '''
    Function to get number of players(Single player or Multiplayer)
    '''
    pick_title = 'Please select number of players to play the game: '
    pick_options = ['Single player', 'Two player']
    pick_option, index = pick(pick_options, pick_title)
    player2 = "COMPUTER" if(index==0) else "Player2"
    return(player2)
Beispiel #30
0
def confirm(action_name: str, extra_text=None):
    # Confirmation
    action_upper = action_name.upper()
    conf_title = f"# Are you SURE you want to {action_name}?"
    if extra_text:
        conf_title += f"\n{extra_text}"
    conf_options = [f"[YES, {action_upper}]", "[CANCEL]"]
    conf_selected, conf_sel_index = pick.pick(conf_options, conf_title)
    return conf_selected == f"[YES, {action_upper}]"
Beispiel #31
0
def run_tool():
    prompt = 'What would you like to do?'
    (option, _) = pick(["Extract Data", "Exit"], prompt, indicator="=>")

    if option == "Exit":
        sys.exit(colored("Bye!", "green"))

    if option == "Extract Data":
        extract_data()
Beispiel #32
0
def main():
    """Main function for news source data scraping tool."""

    title = 'Please select a news source from which to gather text data (press ENTER to select indicated option): '
    options = ['BBC', 'NYT', 'Reuters', 'CNN']
    selected_source = pick(options, title, multi_select=False, min_selection_count=1)[0].lower()
    source_data, query = source_selector(selected_source)

    source_data.to_csv(f'data/scraped/{selected_source}_{query}.csv')
Beispiel #33
0
 def get_choices_vm_hardware(self, vm):
     chosen_option, index = pick(self.options_vm_hardware, self.title)
     # if last element, exit
     if index == len(self.options_vm_hardware) - 1:
         exit(0)
     elif index == 0:
         VirtualMachine.change_mac(vm, self.inventory.service_instance)
     elif index == 2:
         exit(0)
def prompt_for_direct_messages(dms):
    dm_names = [
        user_names_by_id.get(dm['user'], f"{dm['user']} (name unknown)")
        for dm in dms
    ]
    selected_dms = pick(dm_names,
                        'Select the 1:1 DMs you want to export:',
                        multi_select=True)
    return [dms[index] for _, index in selected_dms]
Beispiel #35
0
def say_question(title, options, table_name):
    def get_label(option):
        return option.get("name" + table_name)

    option, index = pick(options,
                         title,
                         indicator=">",
                         options_map_func=get_label)
    return option["id"]
Beispiel #36
0
    def select(self):
        quoteSectors = self.get_dict_quoteSectors()

        title = 'Please choose a quote sector: '
        option, index = pick(list(quoteSectors.keys()), title)

        self.url = Scrape.url + "?quoteSectors=" + quoteSectors[option]

        print("Accessing", self.url)
Beispiel #37
0
def pip_uninstall(pack_list):
    """picker for package. runs system processes for pip show and pip uninstall. returns picked option"""
    pack_list.insert(0, main)
    option, _ = pick(pack_list, "Pick a package to unstall")
    if option == main:
        return
    subprocess.call(["pip", "show", option])
    subprocess.call(["pip", "uninstall", option])
    return option
Beispiel #38
0
def get_google_calendar_id():
    cal_id = redis.get(redis_key('calendar_id'))
    if cal_id:
      return cal_id.decode()
    calendars = service.calendarList().list().execute()
    option, index = pick([c['summary'] for c in calendars['items']], 'Pick the correct calendar: ')
    cal_id = calendars['items'][index]['id']
    redis.set(redis_key('calendar_id'), cal_id)
    return cal_id
Beispiel #39
0
def ask_question_using_pick(options: t.List[Answer],
                            question_from_set: QuestionAnswerSet):
    option, index = pick(
        options,
        question_from_set.question.text,
        indicator='=>',
        default_index=0,
    )
    question_from_set.answer = question_from_set.answer_options[index]
def pick_outlier_rejection():
    options=map(str,[0.95,0.9,0.8,0.7,0.6,0.5])
    text="""
Outlier rejection ratio:
maximum ratio between the matching distance of the first and second candidates
if their ratio is higher the match is discarded to avoid ambiguities
"""
    option, index = pick(options,"outlier rejection ratio")
    return float(option)
Beispiel #41
0
def setup():
    global arduino
    port_list = serial.tools.list_ports.comports()
    if len(port_list) == 0:
        print("ポートがありません。")
        exit()
    port, index = pick(port_list, "ポートを選択:")
    arduino = serial.Serial(port.device, baudrate=9600)
    print("通信開始")
Beispiel #42
0
def promptForDirectMessages(dms):
    dmNames = [
        userNamesById.get(dm['user'], dm['user'] + " (name unknown)")
        for dm in dms
    ]
    selectedDms = pick(dmNames,
                       'Select the 1:1 DMs you want to export:',
                       multi_select=True)
    return [dms[index] for dmName, index in selectedDms]
    def run(self):
        """
        Main loop, returns socket connected to online or initializing environment.
        """
        commands = {
            "request_create_environment": self.request_create_environment,
            "request_active_processes": self.request_active_processes,
            "request_join_environment": self.request_join_environment,
        }

        # run initial command if specified
        if (self.initial_command in commands.keys() and not self.ready_for_recv):
            commands[self.initial_command]()

        # run commands until waiting for a message
        while(not self.ready_for_recv):
            title = "Pick a command:"
            options = commands.keys()
            option, index = pick(options, title)
            commands[option]()

        # loop while still connected to the queue
        while(self.connected_to_queue):
            # if waiting for a message, receive a message
            if (self.ready_for_recv):
                msg = self.recv_json(self.sock)

                j = json.loads(msg)

                self.ready_for_recv = False

            # run commands until waiting for a message
            while(not self.ready_for_recv):
                title = "Pick a command:"
                options = commands.keys()
                option, index = pick(options, title)
                commands[option]()

        print "=" * 60
        print " " * 19, "Client Setup Complete"
        print "=" * 60
        return self.sock
Beispiel #44
0
    def pickChoice():
        file436Module, file436test = "", ""
        while True:
            while True:
                p436 = [f for f in filesList[0] if ".v" == f[1]]
                if file436Module == "":
                    try:
                        file436ModuleL = [f for f in p436 if 'tb' not in f[0]]
                        file436Module = file436ModuleL[0]
                    except:
                        pass
                if file436test == "":
                    try:
                        file436testL = [f for f in p436 if 'tb' in f[0]] 
                        file436test = file436testL[0]
                    except:
                        pass
                title = "The filename for problem 4.36: Module: "+combinPath(file436Module)+" TestBunch: " + combinPath(file436test) + ". Is this correct?"
                option = ["YES", "NO"]
                choice, idx = pick(option, title, indicator='=>')

                p436 = [f for f in filesList[2] if ".v" == f[1]]
                if choice == "YES":
                    break
                else:
                    p436.append("None")
                    title = "Please choose the *Module* file name for Problem 4.36:"
                    file436Module, index = pick(p436, title, indicator='=>')
                 
                    title = "Please choose the *TestBunch* file name for Problem 4.36:"
                    file436test, index = pick(p436, title, indicator='=>')

            p454 = [f for f in filesList[1] if ".v" == f[1] ] 
            p454.append("None")
            title = "Please choose the *Module* file name for Problem 4.54a (BCD):"
            file454AModule, index1 = pick(p454, title, indicator='=>')
         
            title = "Please choose the *TestBunch* file name for Problem 4.54a (BCD):"
            file454Atest, index2 = pick(p454, title, indicator='=>')
           
            title = "Please choose the *Module* file name for Problem 4.54b (GC):"
            file454BModule, index3 = pick(p454, title, indicator='=>')

            title = "Please choose the *TestBunch* file name for Problem 4.54b (GC):"
            file454Btest, index4 = pick(p454, title, indicator='=>')


            title = "Is this correct?"
            option = ["YES", "NO"]
            correct, idx = pick(option, title, indicator='=>')
            if correct == "YES":
                return file436Module, file436test, file454AModule, file454Atest, file454BModule, file454Btest
Beispiel #45
0
def pull_datasets(devices, device_dataset_path, storage_dataset_path):
  for device in devices:
    devices_to_pull = None
    devices_to_pull += check_datasets_against_storage(device, device_dataset_path)
    command = ["adb", "-s", device, "pull", device_dataset_path, storage_dataset_path]

  if devices_to_pull:
    title = ("Some devices have datasets to pull: %s" %devices_to_pull)
    _, ok = pick.pick(["Go ahead with pull", "Cancel"], title)
    if ok == 1:
      title2 = ("Not pulling data, would you like to erase the datasets?")
      _, erase = pick.pick(["Yes", "No"], title)
      if erase == 0:
        for device in device_to_pull:
          wipe_device(device, device_dataset_path)
      else:
        print "Not erasing datasets. Exiting"
        exit(0)
    else:
      subprocess.call(command)
Beispiel #46
0
def pickpaged (options, skip=0, limit=10, index=0, title="", indicator='*', originalSkip=0):
    """Construct and start a :class:`Picker <Picker> in a paged fashion`.

    Usage::

      >>> import pickpaged
      >>>
      >>> title = 'Please choose an option: '
      >>> skip = 0
      >>> limit = 2 # Two options per page
      >>> index = 0 # Which index to start cursor at
      >>> options = ['option1', 'option2', 'option3', 'option4', 'option5']
      >>> while True:
      >>>     options = getPage(skip, limit) # Your custom routine to get the options for the page
      >>>     option, index, skip = pickpaged.pickpaged(options, skip, limit, index, title)
      >>>     if option not in pickpaged.pager_options:
      >>>         # This is a valid option (not NEXT, PREV, REFR or EXIT)
      >>>         # Your code to work on the selected option goes here
      >>>     else:
      >>>         if option == pickpaged.EXIT:
      >>>             break
    """
    original_title = title
    try:
        optionCount = len(options)
        if optionCount == limit:
            options.append(NEXT)
        if skip > originalSkip:
            options.append(PREV)

        if skip == 0 and optionCount == 0:
            title = original_title + "\n\nNone found!"
        elif skip > 0 and optionCount == 0:
            title = original_title + "\n\nNo more found."

        options.append(REFR)
        options.append(EXIT)
        option, index = pick(options, title, indicator, index)
        if option == REFR:
            index = 0 # Reset index before redrawing current page
        elif option == NEXT:
            index = 0 # Reset index before drawing next page
            skip = skip + limit
        elif option == PREV:
            index = 0 # Reset index before drawing previous page
            skip = skip - limit
        return (option, index, skip)
    except SystemExit as e:
        sys.exit(0)
    except Exception as e:
        print(traceback.format_exc())
        sys.exit(3)
    def pick_option(self, msg, default_choice=None):
        """
        Select from options in a menu via cursor
        """
        title = msg["title"]
        options = msg["options"]

        if default_choice is not None and default_choice in options:
            return default_choice

        option, index = pick(options, title)

        return option
def pickFolder(folders,label):
	"""pick filter out of list of subdirectories"""#check for matches
	displayList = ['all']
	for folder in folders:
		displayName = os.path.basename(os.path.normpath(folder))
		displayList.append(displayName)

	folder, index = pick(displayList, label)
	displayList.pop(0)
	if index == 0:
		return displayList,folders
	else:
		return [displayList[index-1]],[folders[index-1]]
Beispiel #49
0
    def select_one_remind(self, jarvis):
        data = self.get_data(jarvis)
        ask_str = []
        for entry in data:
            ask_str.append(self.format(jarvis, entry))

        if len(ask_str) == 0:
            return None

        title = 'Please choose from todo list:'
        _, index = pick(ask_str, title)

        return data[index]
Beispiel #50
0
def net_menu():


    title = 'Enter Network To Scan: '
    options = ['LAN', 'WLAN', 'EXIT']
    option,index = pick(options,title,indicator= '=>',default_index=0)

    if option == 'LAN':

        return index

    elif option == 'WLAN':

        return index

    elif option == 'EXIT':

        return  index
Beispiel #51
0
def _pick_file(f,text,extensions):
    assert(p.isdir(f))
    pattern=p.join(f,'*')
    possible_paths=glob(pattern)
    if extensions:
        possible_paths=[pp for pp in possible_paths if p.isdir(pp) or only_extension(pp) in extensions]
    options=sorted(map(only_filename,possible_paths))
    optionMap={only_filename(path):path for path in possible_paths}
    #opt={only_filename(i):i for i in possible_paths}
    options=[parent_label]+favs.values()+options
    for k in favs:
        optionMap[favs[k]]=k
    a,b=pick(options,text+'\nPath :'+f )
    if  parent_label in a:
        return _pick_file(p.join(f,'..'),text,extensions)
    a=optionMap[a]
    if p.isdir(a):
        return _pick_file(a,text,extensions)
    else:
        return a
Beispiel #52
0
def main():
    contexts, active_context = config.list_kube_config_contexts()
    if not contexts:
        print("Cannot find any context in kube-config file.")
        return
    contexts = [context['name'] for context in contexts]
    active_index = contexts.index(active_context['name'])
    option, _ = pick(contexts, title="Pick the context to load",
                     default_index=active_index)
    # Configs can be set in Configuration class directly or using helper
    # utility
    config.load_kube_config(context=option)

    print("Active host is %s" % configuration.host)

    v1 = client.CoreV1Api()
    print("Listing pods with their IPs:")
    ret = v1.list_pod_for_all_namespaces(watch=False)
    for item in ret.items:
        print(
            "%s\t%s\t%s" %
            (item.status.pod_ip,
             item.metadata.namespace,
             item.metadata.name))
Beispiel #53
0
#-*-coding:utf-8-*-

from __future__ import print_function

from pick import pick

title = 'Please choose your favorite programming language: '
options = ['Java', 'JavaScript', 'Python', 'PHP', 'C++', 'Erlang', 'Haskell']
option, index = pick(options, title, indicator='=>', default_index=2)
print(option, index)
Beispiel #54
0
def transferfile(results):
    file_path = results['file_abs_path']
    file_name = results['file_name']
    ####Select and activate source endpoint, using endpoint display name index####
    endpt_cmd = "ssh cli.globusonline.org endpoint-search --scope my-endpoints | grep 'Display Name' | cut -d ':' -f2 | cut -d ' ' -f2"
    endpt_out = subprocess.check_output(endpt_cmd, shell=True)
    endpts = endpt_out.split("\n")
    endpts_i = []
    for i, x in enumerate(endpts):                  # Create index of endpoint with display names
	if x not in ['n/a','']:
		endpts_i.append(i)
    endpts_d = [endpts[i] for i in endpts_i]
    title = 'Select source Globus endpoint and press Enter, then select Midway destination directory: '
    indicator = '=>'
    d_src_endpt, index = pick(endpts_d, title, indicator)
    print "Selected source endpoint: "+d_src_endpt+"\nSelected file to transfer: "+file_name+"\n"
    l_endpt_cmd = "ssh cli.globusonline.org endpoint-search --scope my-endpoints | grep 'Legacy Name' | cut -d ':' -f2 | cut -d ' ' -f2"
    l_endpt_out = subprocess.check_output(l_endpt_cmd, shell=True)
    l_endpts = l_endpt_out.split("\n")
    l_endpts_d = [l_endpts[i] for i in endpts_i]
    src_endpt = l_endpts_d[index]
    activate_src_cmd = "ssh cli.globusonline.org endpoint-activate "+src_endpt
    os.system(activate_src_cmd)
    ####Select destination directory####
    root = Tkinter.Tk()
    root.withdraw() #use to hide tkinter window
    root.update()
    if not cache['dst_path']:
	currdir = os.getcwd()
    else:
	currdir = cache['dst_path']
    dest_full_dir = tkFileDialog.askdirectory(parent=root, initialdir=currdir, title='Select a Midway destination directory')
    if not dest_full_dir:
	raise SystemExit
    cache['src_path'] = results['file_abs_path'].rsplit('/', 1)[0]
    cache['dst_path'] = dest_full_dir
    save_json(cache, cache_path)                    # update cache with destination directory
    if sys.platform == 'darwin':
	dest_dir = dest_full_dir.split('/Volumes')[1]
    if os.name == 'nt':                             # for Windows systems only
	import win32com.client
	from itertools import izip_longest
	def grouper(n, iterable, fillvalue=None):
    		"grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
    		args = [iter(iterable)] * n
    		return izip_longest(fillvalue=fillvalue, *args)
	def getDriveMappings():
    		"""
    		Return a dictionary of drive letter to UNC paths as mapped on the
    		system.
    		"""
    		network = win32com.client.Dispatch('WScript.Network')
    		# http://msdn.microsoft.com/en-us/library/t9zt39at%28VS.85%29.aspx
    		drives = network.EnumNetworkDrives()
    		# EnumNetworkDrives returns an even-length array of drive/unc pairs.
    		# Use grouper to convert this to a dictionary.
    		result = dict(grouper(2, drives))
    		# Potentially several UNC paths will be connected but not assigned
    		# to any drive letter. Since only the last will be in the
    		# dictionary, remove it.
    		if '' in result: del result['']
    		return result
	def getUNCForDrive(drive):
    		"""
    		Get the UNC path for a mapped drive.
    		Throws a KeyError if no mapping exists.
    		"""
    		return getDriveMappings()[drive.upper()]
	drive = dest_full_dir.split(':')[0]+':'
	UNCname = getUNCForDrive(drive)
	parentdir = UNCname.rsplit('\\')[-1]
        dest_dir = '/'+parentdir+dest_full_dir.split(':')[1]
	file_path = file_path.replace('\\', '/')
	file_path = '/'+file_path.replace(':','',1)
    print "Destination endpoint: ucrcc#midway \nSelected Midway destination directory: "+dest_dir+"\n"
    results['dst_path'] = dest_dir
    ####Transfer file to destination on Midway####
    if os.name == 'posix':
	transfer_cmd = "echo '" +src_endpt+file_path+" ucrcc#midway"+dest_dir+"/"+file_name+"' | ssh cli.globusonline.org transfer -s 3"
    if os.name == 'nt':
	transfer_cmd = "echo | set /P =" +src_endpt+file_path+" ucrcc#midway"+dest_dir+"/"+file_name+" | ssh cli.globusonline.org transfer -s 3"
    transfer_id = subprocess.check_output(transfer_cmd, shell=True)
    print "Globus Transfer "+transfer_id
    ####Send metadata to XROMM server####
    resource = results['resource']
    version = results['version']
    path = 'studies/'

    if resource.startswith('file'):
        study_trial  = results['data']['study_trial']
        if '/' in study_trial:                      # study/trial
            study, trial = study_trial.split('/')
            path += '{}/trials/{}/'.format(study, trial)
        else:
            study, trial = study_trial, ''          # no trial name
            path += '{}/'.format(study)

    elif resource is 'trial':
        path += results['data']['study'] + '/trials/'

    #url = 'http://xromm.rcc.uchicago/api/v{}/{}'.format(version, path)
    #url = 'http://localhost:8081/{}'.format(path)
    print "sending to", url

    # comment out next two lines when backend service in place!
    url = "http://httpbin.org/post"
    print "\n... actually, we're sending to", url, "for testing purposes!"
    resp = requests.post(url, json=json.dumps(results))
    print(resp.text)
    if os.name == 'nt':                             #check for Windows
        print "press any key to exit"
        os.system('pause')                          #allows message reading (Windows/cygwin)
    try:
        number  = int(input())
        collatz(number)
    except ValueError as verror:
        print('ValueError: You need input digital.')
    except:
        print('ValueError: You need input any digital.')
         
collatz_test()

print('\r\n')

# 示例: 单选
title = 'Please choose your favorite programming language: '
options = ['Java', 'JavaScript', 'Python', 'PHP', 'C++', 'Erlang', 'Haskell']
option, index = pick(options, title)
print(option, index)
print(option)
print(index)
curses.endwin()

# 示例: 多选
title = 'Please choose your favorite programming language (press SPACE to mark, ENTER to continue): '
options = ['Java', 'JavaScript', 'Python', 'PHP', 'C++', 'Erlang', 'Haskell']
selected = pick(options, title, multi_select=True, min_selection_count=1)
print(selected)

# 示例: 替换选中指示符
title = 'Please choose your favorite programming language: '
options = ['Java', 'JavaScript', 'Python', 'PHP', 'C++', 'Erlang', 'Haskell']
option, index = pick(options, title, indicator='=>', default_index=2)
def pick_preset():
    options=["NORMAL","HIGH","ULTRA"]
    option, index = pick(options, "how many features do you want?")
    return option
Beispiel #57
0
def main(devices=devices):
  if argParser.version_info:
    print version
  if argParser.unzip_bsp:
    bspFile()
  if argParser.unzip_apps:
    appFile()
  if argParser.pull_calib:
    pull_title = "Are devices set to enable USB debugging??"
    options = ["yes", "no"]
    _, pull_pick = pick(options, pull_title)
    if pull_pick == 0:
      for device in devices:
        pull_calib(device)
  time.sleep(2)
  if argParser.unlock_device:
    for device in devices:
      unlock(device)
  if argParser.nv_flash_device:
    nv_title = "This will nvFlash your device, are you sure?"
    nv_options = ["yes","no"]
    _, nv_flash = pick(nv_options, nv_title)
    if nv_flash == 0:
      for device in devices:
        nvFlash(device)

  if argParser.flash_device:
    bsp_title = "Which bsp image would you like to use?"
    bsp_options = []
    bspFiles = []
    for i in glob.glob(bspPath + "*"):
      bspFiles.append(i)
      bsp_options.append(i.split("/")[6])
    _, pick_bsp = pick(bsp_options, bsp_title)
    userBSP = bspFiles[pick_bsp]

    title = "Are all devices ready to flash?"
    options = ["yes", "no"]
    _, flash_pick = pick(options, title)
    if flash_pick == 0:
      for device in devices:
        if len(devices) < 3:
          flashThread = threading.Thread(target=flashDevices,
                                    args=(userBSP, device))
          flashThread.start()
          flashThread.join()
        else:
          flashDevices(bspPath + BSPChrono(), device)

  if argParser.pull_calib and argParser.user_build and argParser.flash_device:
    push_title = "Ensure devices are set to enable USB debugging."
    options = ["ok"]
    _, push_pick = pick(options, push_title)
    for device in devices:
      push_calib(device)

  if argParser.push_apps or argParser.tango_core:
    app_title = "Which app folder would you like to use?"
    app_options = []
    appFiles = []
    for i in glob.glob(appPath + "*"):
      appFiles.append(i)
      app_options.append(i.split("/")[6])
    _, pick_app = pick(app_options, app_title)
    datePath = appFiles[pick_app]

    for device in devices:
      installApks(datePath, device, appUnzipPath)
  if argParser.reboot:
    reboot(devices)

  """if len(argParser) < 1:
    no_flags_title = "What would you like this script to do? Select all that apply"
    no_flags_options = ["Flash", "Install apks", "Install TangoCore Only",
                        "Exclude TangoCore from install",
                        "Choose serial number from list", "Unzip apps",
                        "Unzip User-Debug bsp", "Unzip User-Build bsp", "Reboot",
                        "Unlock device"
                        ]
    _, pick_arg = pick(no_flags_options, no_flags_title)"""


  cleanup()
Beispiel #58
0
zipFilePath = downloads + "*.zip"

# Creates a list with the device serial numbers.
devices = [device[0]
           for device in [line.split("\t")
           for line in os.popen("adb devices").read().split("\n")
           if len(line.split("\t")) == 2]]
if len(devices) > 0:
  lastDevice = devices[-1]

if argParser.serial_number:
  print devices
  serial_title = "Which device would you like to use?"
  serial_options = devices
  _, pick_serial = pick(serial_options, serial_title)
  devices = devices[pick_serial]

print devices


def unlock(device):
  subprocess.call(["adb", "-s", device, "reboot", "bootloader"])
  time.sleep(1)
  subprocess.call(["fastboot", "-s", device, "oem", "unlock"])
  time.sleep(3)
  subprocess.check_call(["fastboot", "-s", device, "reboot"])
  print "~"*20, "Device unlocked, rebooting now","~"*20
  if device == lastDevice:
    countdown(260)
def ask(s):
    options=['yes','no']
    option, index = pick(options,s)
    return ('yes' in option)
def pick_describer():
    option, index = pick(KEYPOINT_METHODS, "what kind of feature do you want?")
    return option