예제 #1
0
    def makeBid(self, auctionRound, upcard, dealer_position):

        input("Press Enter to continue...")
        #        self.informUpCard(auctionRound)
        if auctionRound == 0:
            self.sortForBiddingRoundOne(self.upcard.getSuit())
            title = 'The upcard is %s. \n Your hand is %s. \n Would you like to Bid, or Pass?' % (
                self.upcard, self.convertHandToText())
        else:
            self.sortForBiddingRoundTwo(self.upcard.getSuit())
            title = 'The upcard was %s. \n Your hand is %s. \n Would you like to Bid, or Pass?' % (
                self.upcard, self.convertHandToText())
        options = ['Bid', 'Pass']

        picker = Picker(options, title)
        #picker.register_custom_handler(curses.KEY_LEFT, go_back)
        option, index = picker.start()

        if option == 'Bid':
            trialBid = self.selectTrump()
            if self.isValidBid(trialBid, self.upcard, auctionRound):
                return trialBid
            else:
                print(
                    'That is not a legal choice. The only bid you may make is the suit of the up card.'
                )
                return self.makeBid(auctionRound, upcard, dealer_position)

        elif option == 'Pass':
            if self.isValidBid(BIDS.passbid, self.upcard, auctionRound):
                return BIDS.passbid
            else:
                print(self.upcard, auctionRound)
                print("You may not passout the hand")
                return self.makeBid(auctionRound, upcard, dealer_position)
예제 #2
0
파일: test_pick.py 프로젝트: eth0izzle/pick
 def test_get_lines(self):
     title = 'Please choose an option: '
     options = ['option1', 'option2', 'option3']
     picker = Picker(options, title, indicator='*')
     lines, current_line = picker.get_lines()
     assert lines == [title, '', '* option1', '  option2', '  option3']
     assert current_line == 3
예제 #3
0
def SetupAudioDevice():
    global configData
    logging.info("Setting up audio output device")
    selectedDevice = re.compile(r"alsasink device=\"(\S+)\"").match(
        configData["audio"]["output"])
    availableDeviceList = alsaaudio.pcms()
    devicePickerDefaultIndex = 0
    if (selectedDevice is not None):
        if (selectedDevice.groups()[0] in availableDeviceList):
            devicePickerDefaultIndex = availableDeviceList.index(
                selectedDevice.groups()[0])
    devicePickerTitle = (
        "Please select an audio device for music playback using arrow keys.\n"
        "Press 't' to test audio output\n"
        "Press 'Enter' to confirm")
    devicePicker = Picker(availableDeviceList,
                          devicePickerTitle,
                          indicator='-->',
                          default_index=devicePickerDefaultIndex)
    devicePicker.register_custom_handler(ord("t"), PlayTestingAudio)
    devicePickerOption, devicePickerIndex = devicePicker.start()
    configData["audio"][
        "output"] = "alsasink device=\"%s\"" % availableDeviceList[
            devicePickerIndex]
    logging.info("Finish setting up audio output device")
예제 #4
0
파일: test_pick.py 프로젝트: simonbru/pick
 def test_get_lines(self):
     title = 'Please choose an option: '
     options = ['option1', 'option2', 'option3']
     picker = Picker(options, title, indicator='*')
     lines, current_line = picker.get_lines()
     assert lines == [title, '', '* option1', '  option2', '  option3']
     assert current_line == 3
예제 #5
0
파일: aaa.py 프로젝트: quake0day/pikachu
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)
예제 #6
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)
예제 #7
0
    def test_options_map_func(self):
        title = 'Please choose an option: '
        options = [{'label': 'option1'}, {'label': 'option2'}, {'label': 'option3'}]

        def get_label(option): return option.get('label')

        picker = Picker(options, title, indicator='*', options_map_func=get_label)
        lines, current_line = picker.get_lines()
        assert lines == [title, '', '* option1', '  option2', '  option3']
        assert picker.get_selected() == ({ 'label': 'option1' }, 0)
예제 #8
0
    def playCard(self, suitLed, trick):

        input("Press Enter to continue...")
        validCards = [c for c in self.hand if self.isValidPlay(c, suitLed)]
        title = 'Here is the trick so far %s.\n Here is your remaining hand %s\n What card would you like to play? Here are your legal options:' % (
            self.convertTrickToText(trick), self.convertHandToText())
        picker = Picker(validCards, title)
        toPlay, index = picker.start()
        self.hand.remove(toPlay)
        return toPlay
예제 #9
0
def add(license, gitignore, readme):

	if license:
		click.clear()
		licenseURL = 'https://api.github.com/licenses'
		GETResponse = licenses.getRequestsAsJSON(licenseURL)
		licensesDict = {}

		for i in GETResponse:
			licensesDict[i['key']] = i['name']
		promptMessage = 'Choose a license or press s to stop'
		title = promptMessage
		options = list(licensesDict.values())
		picker = Picker(options, title, indicator = '=>', default_index = 0)
		picker.register_custom_handler(ord('s'),  go_back)
		chosenLicense, index = picker.start()
		# user selection is stored in chosenLicense, which is the index'th element in options = licenses
		if index != -1:
			licenses.generateLicense(licenseURL, licensesDict, chosenLicense)
		else:
			sys.exit(0)

	if gitignore:
		url = "https://api.github.com/repos/github/gitignore/contents/"
		r = requests.get(url)

		if r.status_code==200:
			x = r.json()
		else:
			click.secho("Internal error occured.", bold=True, fg='red')
			sys.exit(0)
		ignores = [{"name" : item['name'], "url" : item['download_url']} for item in x if item['type']=='file' and ".gitignore" in item['name']]
		promptMessage = 'Choose a gitignore \n(press SPACE to mark, ENTER to continue, s to stop):'
		title = promptMessage
		options = [item['name'] for item in ignores]
		picker = Picker(options, title, multi_select=True, min_selection_count=1)
		picker.register_custom_handler(ord('s'),  go_back)
		selected = picker.start()
		
		if type(selected) == list:
			d_urls = [ignores[item[1]]['url'] for item in selected]
		else:
			sys.exit(0)
		sep = "\n"+("#" * 40)+"\n"
		str_write = ''.join(["".join(sep+requests.get(item).text+sep) for item in d_urls])

		with open('.gitignore', 'a+') as file:
			file.write(str_write)
		click.secho("gitignore templates added succesfully.\n", fg = "green", bold = True)

	if readme:			
		with open('README.md', 'w+') as file:
			pass	
예제 #10
0
    def _run_menu(self, options):
        title = "\n".join(self._title_lines())
        special_keys = []
        for k, action_desc, handler in self.key_options:
            title += "\n    ({}) to {}".format(k, action_desc)
            special_keys.append((ord(k), handler))

        menu = Picker(options, title)
        for special_key in special_keys:
            menu.register_custom_handler(*special_key)

        return menu.start()[0]
예제 #11
0
def get_selected_device(devices):
    """
    Prints available devices as selectable option list.
    Returns selected option.
    """
    picker = Picker(title=title,
                    options=devices,
                    indicator='->',
                    options_map_func=settings_manager.map_device_status)

    picker.register_custom_handler(ord('s'), set_default_device)

    option, _ = picker.start()
    return option
예제 #12
0
    def swapUpCard(self, upcard):

        input("Press Enter to continue...")
        self.hand.append(upcard)
        trump_suit = upcard.getSuit()
        self.announceTrumpSuit(trump_suit)
        self.sortForPlay(trump_suit)

        #        validCards = [[c.getSuit(),c.getRank()] for c in self.hand if self.isValidPlay(c, suitLed)]
        title = '%s has been selected as trump, and you got %s as the upcard. Select a card to return:' % (
            trump_suit.name, self.upcard)
        picker = Picker(self.hand, title)
        toReturn, index = picker.start()
        self.hand.remove(toReturn)
예제 #13
0
파일: test_pick.py 프로젝트: simonbru/pick
 def test_move_up_down(self):
     title = 'Please choose an option: '
     options = ['option1', 'option2', 'option3']
     picker = Picker(options, title)
     picker.move_up()
     assert picker.get_selected() == ('option3', 2)
     picker.move_down()
     picker.move_down()
     assert picker.get_selected() == ('option2', 1)
예제 #14
0
def one(prompt, *args, **kwargs):
    """Instantiates a picker, registers custom handlers for going back,
    and starts the picker.
    """
    indicator = '‣'
    if sys.version_info < (3, 0):
        indicator = '>'

    def go_back(picker):
        return None, -1

    options, verbose_options = prepare_options(args)
    idx = kwargs.get('idx', 0)

    picker = Picker(verbose_options,
                    title=prompt,
                    indicator=indicator,
                    default_index=idx)
    picker.register_custom_handler(ord('h'), go_back)
    picker.register_custom_handler(curses.KEY_LEFT, go_back)
    with stdout_redirected(sys.stderr):
        option, index = picker.start()
        if index == -1:
            raise QuestionnaireGoBack
        if kwargs.get('return_index', False):
            # `one` was called by a special client, e.g. `many`
            return index
        return options[index]
예제 #15
0
파일: test_pick.py 프로젝트: d3n3y/pick
 def test_pick(self):
     title = 'Please choose an option: '
     options = ['option1', 'option2', 'option3']
     picker = Picker(options, title)
     picker.move_up()
     assert picker.get_selected() == ('option3', 2)
     picker.move_down()
     picker.move_down()
     assert picker.get_selected() == ('option2', 1)
예제 #16
0
def show_menu(startid='main'):
    """
    shows the menu on screen
    :param startid: the id of the menu to start with (used to find parrent)
    :return:
    """

    # check if package or device are to be changed
    # just working around stacking curses menus
    if context.chg_pkg:
        context.package = experimentation.choosePackage()
        context.chg_pkg = False
        return
    if context.chg_dev:
        context.device = experimentation.chooseDevice(context.package)
        context.chg_dev = False

    context.current_menu = startid
    menu = menu_tree[startid]
    options = menu['menu'].keys()

    options.sort()

    if context.package:
        subtitle = "Package: {}, Device: {}".format(context.package,
                                                    context.device)
    else:
        subtitle = ""

    hotkeys = "Press 'p' to change the package, 'd' to change the device"
    title = "{}\n{}\n{}".format(menu['title'], hotkeys, subtitle)
    picker = Picker(options=options, title=title)
    picker.register_custom_handler(ord('p'), choose_package)
    picker.register_custom_handler(ord('d'), choose_device)
    action, idx = picker.start()

    context.action = action
    if action == "pass":
        # used to change package or device
        # will simply do nothing and reload the menu
        return
    if action == "quit":
        if menu['parent_menu'] != None:
            show_menu(menu['parent_menu'])
        else:
            logger.info("... finished")
            exit()
    else:
        func = menu['menu'][action][0]
        if func == 'menu':
            func = globals()['show_menu']
        if menu['menu'][action][1] is not None:
            args = menu['menu'][action][1]
            func(*args)  # calling with arguments
        else:
            func()  # calling without arguments
예제 #17
0
    def askSelection(self, choices):
        selectedItem, selectedIndex = ("", -1)
        currentPath = self.fileManager.getCurrentPath()

        if self.selectionType is SelectionType.Picker:
            picker = Picker(choices, currentPath + " ('q' to quit)")
            picker.register_custom_handler(ord('q'), sys.exit)
            picker.register_custom_handler(ord('o'), self.switchOrderBy)

            selectedItem, selectedIndex = picker.start()

        else:
            while True:
                print(currentPath + " ('q' to quit)")
                for i, choice in enumerate(choices):
                    print("["+str(i)+"] " + choice)
                try:
                    selectedIndex = int(input("Select your choice between 0-" + str(len(choices)-1) + ": "))
                    if selectedIndex < 0 or selectedIndex >= len(choices):
                        print("Invalid choice. Must be between 0-" + str(len(choices)-1) + ".")
                    else:
                        break
                except ValueError:
                    print("Please enter a number.")

        return selectedItem, selectedIndex
예제 #18
0
def choose_unit(systempath, units):
    options = []
    ss = get_output("ss -l -p -n")
    ps_aux = get_output("ps ax -o pid,%cpu,%mem,ppid,args -ww")
    for unit in units:
        running = "✓" if is_unit_running(unit) or is_unit_running(
            unit + ".timer") else "✗"
        enabled = "✓" if is_unit_enabled(unit) or is_unit_enabled(
            unit + ".timer") else "✗"
        ps = read_ps_aux_by_unit(systempath, unit, ps_aux)
        if ps is None:
            port = ""
        else:
            pid, *_ = ps
            port = get_port_from_ps_and_ss(pid, ss)
        options.append((unit, running, enabled, port))

    pad = "{}|    {}    |    {}    |   {}"
    offset = max([len(x[0]) for x in options]) + 3
    formatted_options = [
        pad.format(x.ljust(offset), r, e, p) for x, r, e, p in options
    ]
    quit = "-- Quit --"
    formatted_options.append(" ")
    formatted_options.append(quit)
    title = "These are known units:\n\n{}| Active  | On boot |   Port".format(
        " " * (offset + 2))
    default_index = 0
    while True:
        p = Picker(formatted_options, title, default_index=default_index)
        p.register_custom_handler(ord('q'), lambda _: sys.exit(0))
        chosen, index = p.start()
        if chosen == quit:
            return None
        elif chosen == " ":
            default_index = index
            continue
        else:
            break
    return units[index]
예제 #19
0
def single(prompt="", **kwargs):
    """Instantiates a picker, registers custom handlers for going back,
    and starts the picker.
    """
    def go_back(picker):
        return None, -1

    options = kwargs["options"] if "options" in kwargs else []

    picker = Picker(options, title=prompt, indicator='=>')
    picker.register_custom_handler(ord('h'), go_back)
    picker.register_custom_handler(curses.KEY_LEFT, go_back)
    option, i = picker.start()
    if i < 0:  # user went back
        return option, 1
    return option, None
예제 #20
0
    def selectTrump(self):

        title = 'Please select the suit you would like to be trump:'
        options = ['Spades', 'Hearts', 'Diamonds', 'Clubs']
        picker = Picker(options, title)
        choice, index = picker.start()

        title = 'Would you like to go alone?'
        options = ['Yes, alone', 'No, not alone']
        picker = Picker(options, title)
        alone, indexd = picker.start()

        Alone = alone == 'Yes, alone'
        suit = None
        if choice == 'Spades':
            suit = SUITS.spades
        elif choice == 'Hearts':
            suit = SUITS.hearts
        elif choice == 'Diamonds':
            suit = SUITS.diamonds
        elif choice == 'Clubs':
            suit = SUITS.clubs

        return BIDS((suit, Alone))
예제 #21
0
파일: test_pick.py 프로젝트: simonbru/pick
 def test_no_title(self):
     options = ['option1', 'option2', 'option3']
     picker = Picker(options)
     lines, current_line = picker.get_lines()
     assert current_line == 1
예제 #22
0
파일: test_pick.py 프로젝트: simonbru/pick
 def test_default_index(self):
     title = 'Please choose an option: '
     options = ['option1', 'option2', 'option3']
     picker = Picker(options, title, default_index=1)
     assert picker.get_selected() == ('option2', 1)
예제 #23
0
def viewFile(name, types, pid):
    """
    view-files: Filter based list of the names and ids of the first 10 files the user has access to
    """
    token = os.path.join(dirpath, 'token.json')
    store = file.Storage(token)
    creds = store.get()
    service = build('drive', 'v3', http=creds.authorize(Http()))
    page_token = None
    query = ""
    if name:
        q_name = click.prompt('enter the search value')
        query = "name contains '" + q_name + "' "
    if types:
        mimeTypes = {
            "xls": 'application/vnd.ms-excel',
            "xlsx": 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
            "xml": 'text/xml',
            "ods": 'application/vnd.oasis.opendocument.spreadsheet',
            "csv": 'text/plain',
            "tmpl": 'text/plain',
            "pdf": 'application/pdf',
            "php": 'application/x-httpd-php',
            "jpg": 'image/jpeg',
            "png": 'image/png',
            "gif": 'image/gif',
            "bmp": 'image/bmp',
            "txt": 'text/plain',
            "doc": 'application/msword',
            "js": 'text/js',
            "swf": 'application/x-shockwave-flash',
            "mp3": 'audio/mpeg',
            "zip": 'application/zip',
            "rar": 'application/rar',
            "tar": 'application/tar',
            "arj": 'application/arj',
            "cab": 'application/cab',
            "html": 'text/html',
            "htm": 'text/html',
            "default": 'application/octet-stream',
            "audio": 'application/vnd.google-apps.audio',
            "Google Docs": 'application/vnd.google-apps.document',
            "Google Drawing": 'application/vnd.google-apps.drawing',
            "Google Drive file": 'application/vnd.google-apps.file',
            "Google Forms": 'application/vnd.google-apps.form',
            "Google Fusion Tables": 'application/vnd.google-apps.fusiontable',
            "Google My Maps": 'application/vnd.google-apps.map',
            "Google Photos": 'application/vnd.google-apps.photo',
            "Google Slides": 'application/vnd.google-apps.presentation',
            "Google Apps Scripts": 'application/vnd.google-apps.script',
            "Google Sites": 'application/vnd.google-apps.site',
            "Google Sheets": 'application/vnd.google-apps.spreadsheet',
            "3rd party shortcut": 'application/vnd.google-apps.drive-sdk',
            "folder": 'application/vnd.google-apps.folder'
        }
        promptMessage = 'Choose a media type to filter \n(press SPACE to mark, ENTER to continue, s to stop):'
        title = promptMessage
        options = [x for x in mimeTypes.keys()]
        picker = Picker(options, title, multi_select=True,
                        min_selection_count=1)
        picker.register_custom_handler(ord('s'), go_back)
        selected = picker.start()
        if type(selected) == list:
            query += "and ("
            for types in selected:
                query += "mimeType='" + mimeTypes[types[0]] + "' or "
            query = query[:-3]
            query += ")"
        if (not name) and types:
            query = query[4:]
    if pid:
        parent = click.prompt('enter the fid of parent or  sharing link')
        fid = get_fid(parent)
        if (name != False) or (types != False):
            query += " and "
        query += "'" + fid + "' in parents"
    i = 1
    if pid:
        parent = click.prompt('enter the fid of parent or  sharing link')
        fid = get_fid(parent)
        if (name != False) or (types != False):
            query += " and "
        query += "'" + fid + "' in parents"
    while True:
        response = service.files().list(q=query,
                                        spaces='drive',
                                        fields='nextPageToken, files(id, name,mimeType,modifiedTime)',
                                        pageToken=page_token).execute()

        templist = [response.get('files', [])[i:i + 25] for i in range(0, len(
            response.get('files', [])), 25)]  # breakdown list to 25 entries at a time
        for item in templist:
            t = PrettyTable(['Sr.', 'Name', 'ID', 'Type', 'Modified Time'])
            for fils in item:
                t.add_row([i, fils.get('name')[:25], fils.get('id'), fils.get(
                    'mimeType').replace('application/', '')[:25], fils.get('modifiedTime')])
                i += 1
            print(t)
            click.confirm('Do you want to continue?', abort=True)
            click.clear()
        page_token = response.get('nextPageToken', None)
        if page_token is None:
            break
예제 #24
0
def get_request(service, fid, mimeType):
    if(re.match('^application/vnd\.google-apps\..+', mimeType)):
        if(mimeType == 'application/vnd.google-apps.document'):
            mimeTypes = {
                "pdf": 'application/pdf',
                "txt": 'text/plain',
                "doc": 'application/msword',
                "zip": 'application/zip',
                "html": 'text/html',
                "rtf": "application/rtf",
                "odt": "application/vnd.oasis.opendocument.text"
            }
        elif(mimeType == 'application/vnd.google-apps.spreadsheet'):
            mimeTypes = {
                "pdf": 'application/pdf',
                "xlsx": 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
                "zip": 'application/zip',
                "html": 'text/html',
                "ods": 'application/vnd.oasis.opendocument.spreadsheet',
                "csv": 'text/plain',
                "tsv": "text/tab-separated-values",
            }
        elif(mimeType == 'application/vnd.google-apps.presentation'):
            mimeTypes = {
                "pdf": 'application/pdf',
                "zip": 'application/zip',
                "html": 'text/html',
                "pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation",
                "plain txt": 'text/plain'
            }
        else:
            mimeTypes = {
                "ods": 'application/vnd.oasis.opendocument.spreadsheet',
                "csv": 'text/plain',
                "tmpl": 'text/plain',
                "pdf": 'application/pdf',
                "php": 'application/x-httpd-php',
                "jpg": 'image/jpeg',
                "png": 'image/png',
                "gif": 'image/gif',
                "bmp": 'image/bmp',
                "txt": 'text/plain',
                "doc": 'application/msword',
                "js": 'text/js',
                "swf": 'application/x-shockwave-flash',
                "mp3": 'audio/mpeg',
                "zip": 'application/zip',
                "rar": 'application/rar',
                "tar": 'application/tar',
                "arj": 'application/arj',
                "cab": 'application/cab',
                "html": 'text/html',
                "htm": 'text/html'
            }
        promptMessage = 'Choose type to export to \n(ENTER to select, s to stop):'
        title = promptMessage
        options = [x for x in mimeTypes.keys()]
        picker = Picker(options, title, indicator='=>', default_index=0)
        picker.register_custom_handler(ord('s'),  go_back)
        chosen, index = picker.start()
        if index != -1:
            request = service.files().export_media(
                fileId=fid, mimeType=mimeTypes[chosen])
            return request, str("." + chosen)
        else:
            sys.exit(0)
    else:
        request = service.files().get_media(fileId=fid)
        return request, ""
예제 #25
0
def cli(query, playlistsearch, video, playlist, interactive):
    if interactive:
        tui.main()
    else:
        if not query:
            print("Error: Enter a search query")
            sys.exit(1)

        query = " ".join(query)

        url = ""
        choice = dict()

        if video:
            isValid, details = isValidURL(query, urlType="video")
            if isValid:
                # print(f"Selected : {url}")
                choice['id'] = details['id']
                choice['url'] = query
                choice['title'] = details['snippet']['title']
            else:
                print("Invalid URL")
                sys.exit(3)
        elif playlist:
            isValid, details = isValidURL(query, urlType="playlist")
            url = query
            if isValid:
                # print(f"Selected : {url}")
                choice['id'] = details['id']
                choice['url'] = query
                choice['title'] = details['snippet']['title']
            else:
                print("Invalid URL")
                sys.exit(3)
        else:
            if playlistsearch:
                results = search_pl(query)
            else:
                results = search_video(query)

            if len(results) < 1:
                click.secho("No results found.", fg="red")
                sys.exit(3)

            options = [x["title"] for x in results]
            title = f"Search results for {query} (q to quit)"

            picker = Picker(options, title)
            picker.register_custom_handler(ord('q'), quit_pick)
            option, index = picker.start()

            choice = results[index]

        print(f"Selected : {choice['url']}")

        options = ["Play", "Download"]
        title = "Choose what you want to do (q to quit)"
        picker = Picker(options, title)

        picker.register_custom_handler(ord('q'), quit_pick)

        option, index = picker.start()

        if playlist or playlistsearch:
            if option == "Download":
                for playlist_item in extract_playlist_data(choice['url']):
                    print(f"Downloading {playlist_item['title']}")
                    download_video(playlist_item['url'], print_hook)
            elif option == "Play":
                if not PLAY_SUPPORT:
                    print("Play support is not available for your system.")
                    sys.exit(2)
                else:
                    for playlist_item in extract_playlist_data(choice['url']):
                        # print(f"Playing {playlist_item['title']}")
                        play_audio(playlist_item['url'],
                                   playlist_item['title'])
        else:
            if option == "Download":
                print(f"Downloading {choice['title']}")
                download_video(choice['url'], print_hook)
            elif option == "Play":
                if not PLAY_SUPPORT:
                    print("Play support is not available for your system.")
                    sys.exit(2)
                else:
                    # print(f"Playing {choice['title']}")
                    play_audio(choice['url'], choice['title'])
예제 #26
0
#-*-coding:utf-8-*-

from __future__ import print_function

import curses
from pick import Picker

def go_back(picker):
    return (None, -1)

title = 'Please choose your favorite NBA trio: '
options = [
    'Bill Russell\nBob Cousy\nJohn Havlicek',
    'Magic Johnson\nKareem Abdul Jabbar\nJames Worthy',
    'Larry Bird\nKevin McHale\nRobert Parrish',
    'Michael Jordan\nScottie Pippen\nDennis Rodman',
    'Walt Frazier\nWillis Reed\nDave DeBusschere',
    'Tim Duncan\nManu Ginobili\nTony Parker'
]

picker = Picker(options, title, indicator='---->', multiselect=True)
picker.register_custom_handler(curses.KEY_LEFT, go_back)
option, index = picker.start()
print(option, index)
예제 #27
0
파일: test_pick.py 프로젝트: eth0izzle/pick
 def test_no_title(self):
     options = ['option1', 'option2', 'option3']
     picker = Picker(options)
     lines, current_line = picker.get_lines()
     assert current_line == 1
예제 #28
0
파일: test_pick.py 프로젝트: simonbru/pick
 def test_multi_select(self):
     title = 'Please choose an option: '
     options = ['option1', 'option2', 'option3']
     picker = Picker(options,
                     title,
                     multi_select=True,
                     min_selection_count=1)
     assert picker.get_selected() == []
     picker.mark_index()
     assert picker.get_selected() == [('option1', 0)]
     picker.move_down()
     picker.mark_index()
     assert picker.get_selected() == [('option1', 0), ('option2', 1)]
예제 #29
0
def list_pr():
	repo = Repo(os.getcwd())
	assert not repo.bare
	url = repo.remotes.origin.url
	repo_name = url.replace('https://github.com','').replace('.git','')
	params = {'state':'open'}
	data = file_handler()
	url = "https://api.github.com/repos"+repo_name+"/pulls"
	r = requests.get(url,params=params)
	if r.status_code == 200:
		pulls = r.json()
		message = "pull requests for "+ repo_name[1:] +"\npress s to quit and enter to select"
		options = [ '#'+pull['url'].split('/')[-1]+' '+pull['title']+' : '+pull['user']['login'] for pull in pulls ]
		picker = Picker(options, message , indicator = '=>', default_index = 0)
		picker.register_custom_handler(ord('s'),  go_back)
		chosenpr, index = picker.start()
		pull = pulls[index]
		event_number = pull['url'].split('/')[-1]
		from_to = pull['head']['label']+' to '+pull['base']['label']
		click.clear()
		click.secho('#'+event_number+': from ',nl=False)
		click.secho(from_to,fg='cyan')
		click.secho("title: ",nl=False)
		click.secho(pull['title'],fg='yellow')
		click.secho("made by: ",nl=False)
		click.secho(pull['user']['login'],fg='blue')
		if(pull['body']!=""):
			click.secho("body:\n"+pull['body'],fg='yellow')
		click.secho("created at: "+pull['created_at'])
		comment_url = pull['comments_url']
		r = requests.get(comment_url)
		if r.status_code == 200:
			comments = r.json()
			if comments != []:
				click.secho('comments:')
			for comment in comments:
				click.secho(comment['user']['login']+":"+comment['body'])
			click.secho('=================================================')
			inp = click.prompt("enter n to check the pull request in a new branch\n      m to merge the pull request\n      c to comment on the pull request \n      any other key to exit\n")
			if inp == 'n':
				click.secho('creating a new brach and checking out to the branch')
				fetch = 'git fetch origin pull/'+event_number+'/head:pr#'+event_number
				os.system(fetch)
				checkout = 'git checkout pr#'+event_number
				os.system(checkout)
			elif inp == 'm':
				click.confirm('Are you sure you want to merge this pull request ?',abort=True)
				username = click.prompt("username")
				headers = {"Authorization": "token "+data[username][0]}
				url = "https://api.github.com/repos"+repo_name+"/pulls/"+event_number+"/merge"
				r = requests.put(url,headers=headers)
				click.secho(r.json()['message'])
			elif inp == 'c':
				inp = click.prompt("Enter the comment that you want to make")
				username = click.prompt("username")
				headers = {"Authorization": "token "+data[username][0]}
				url = "https://api.github.com/repos"+repo_name+"/issues/"+event_number+"/comments"
				payload = {"body":inp}
				r = requests.post(url,data=json.dumps(payload),headers=headers)
				if r.status_code == 201:
					click.secho("comment published")
				else:
					click.secho("Internal Error",fg='red')
		else:
			click.secho("Internal error"+r.status_code, fg='red')
	else:
		click.secho("Internal error", fg='red')
예제 #30
0
파일: utils.py 프로젝트: zhaohc10/airflow2
def get_request(service, fid, mimeType):
    if(re.match('^application/vnd\.google-apps\..+', mimeType)):
        if(mimeType == 'application/vnd.google-apps.document'):
            mimeTypes = {extension: mime.guess_type("placeholder_filename." + extension)[0] for extension
                         in ("pdf",
                             "txt",
                             "doc",
                             "zip",
                             "html",
                             "rtf",
                             "odt")}
        elif(mimeType == 'application/vnd.google-apps.spreadsheet'):
            mimeTypes = {extension: mime.guess_type("placeholder_filename." + extension)[0] for extension
                         in ("pdf",
                             "xlsx",
                             "zip",
                             "html",
                             "ods",
                             "csv",
                             "tsv")}
        elif(mimeType == 'application/vnd.google-apps.presentation'):
            mimeTypes = {extension: mime.guess_type("paceholder_filename." + extension)[0] for extension
                         in ("pdf",
                             "zip",
                             "html",
                             "pptx",
                             "txt")}
        else:
            mimeTypes = {extension: mime.guess_type("paceholder_filename." + extension)[0] for extension
                         in ("ods",
                             "csv",
                             "pdf",
                             "jpg",
                             "png",
                             "gif",
                             "bmp",
                             "txt",
                             "doc",
                             "js",
                             "swf",
                             "mp3",
                             "zip",
                             "rar",
                             "tar",
                             "cab",
                             "html",
                             "htm")}
            mimeTypes.update(
                {'tmpl': 'text/plain', 'php': 'application/x-httpd-php', 'arj': 'application/arj'})
        promptMessage = 'Choose type to export to \n(ENTER to select, s to stop):'
        title = promptMessage
        options = [x for x in mimeTypes.keys()]
        picker = Picker(options, title, indicator='=>', default_index=0)
        picker.register_custom_handler(ord('s'), go_back)
        chosen, index = picker.start()
        if index != -1:
            request = service.files().export_media(
                fileId=fid, mimeType=mimeTypes[chosen])
            return request, str("." + chosen)
        else:
            sys.exit(0)
    else:
        request = service.files().get_media(fileId=fid)
        return request, ""
예제 #31
0
파일: ycl.py 프로젝트: SubhrajitPrusty/ycl
def cli(query, playlistsearch, video, playlist, interactive, export, output):
    LOCAL_PLAYLIST = False

    if not is_connected():
        click.secho("Check your internet connection.", fg="red", bg="yellow")
        sys.exit(1)

    if interactive:
        tui.main()
    else:
        if not query:
            print("Error: Enter a search query")
            sys.exit(1)

        query = " ".join(query)

        choice = dict()

        if video:
            isValid, details = isValidURL(query, urlType="video")
            if isValid:
                # print(f"Selected : {url}")
                choice['id'] = details['id']
                choice['url'] = query
                choice['title'] = details['snippet']['title']
            else:
                print("Invalid URL")
                sys.exit(3)
        elif playlist:
            isValid, details = isValidURL(query, urlType="playlist")
            if isValid:
                # print(f"Selected : {url}")
                choice['id'] = details['id']
                choice['url'] = query
                choice['title'] = details['snippet']['title']
            else:
                if os.path.exists(query):
                    LOCAL_PLAYLIST = parse_file(query)
                else:
                    print("ERROR: Wrong link or file path")
                    sys.exit(3)
        elif export:
            isValid, details = isValidURL(query, urlType="playlist")
            if isValid:
                # print(f"Selected : {url}")
                video_list = '\n'.join([
                    f"{play_list['url']},{play_list['title']}"
                    for play_list in extract_playlist_data(query)
                ])
                SAVE_FILE = details['snippet']['title'] + ".ycl"
                handle = open(SAVE_FILE, "w", encoding="utf8")
                handle.write(video_list)
                handle.close()
                print(f"Playlist saved to {SAVE_FILE} ")
                sys.exit()
            else:
                print("ERROR: Invalid URL")
                sys.exit(3)
        else:
            if playlistsearch:
                results = search_pl(query)
            else:
                results = search_video(query)

            if len(results) < 1:
                click.secho("No results found.", fg="red")
                sys.exit(3)

            options = [x["title"] for x in results]
            title = f"Search results for {query} (q to quit)"
            picker = Picker(options, title)
            picker.register_custom_handler(ord('q'), quit_pick)
            option, index = picker.start()

            choice = results[index]

        selected = query if LOCAL_PLAYLIST else choice['url']
        print(f"Selected : {selected}")

        options = ["Play", "Download"]
        title = "Choose what you want to do (q to quit)"
        picker = Picker(options, title)

        picker.register_custom_handler(ord('q'), quit_pick)

        option, index = picker.start()
        # curses.initscr()
        curses.endwin()
        if playlist or playlistsearch:

            if LOCAL_PLAYLIST:
                playlist_list = LOCAL_PLAYLIST
            else:
                playlist_list = extract_playlist_data(choice['url'])

            for video in playlist_list:
                if option == "Download":
                    print(f"\x1B[1KDownload: {video['title']}\n")
                    download_video(video['url'],
                                   print_hook,
                                   output_format=output)
                    # print()
                elif option == "Play":
                    play_audio(video['url'], video['title'])
        else:
            if option == "Download":
                print(f"\x1B[1KDownload: {choice['title']}\n")
                download_video(choice['url'], print_hook, output_format=output)
            elif option == "Play":
                play_audio(choice['url'], choice['title'])
예제 #32
0
#-*-coding:utf-8-*-

from __future__ import print_function

import curses
from pick import Picker


def go_back(picker):
    return (None, -1)


title = 'Please choose your favorite programming language: '
options = ['Java', 'JavaScript', 'Python', 'PHP', 'C++', 'Erlang', 'Haskell']

picker = Picker(options, title)
picker.register_custom_handler(curses.KEY_LEFT, go_back)
option, index = picker.start()
print(option, index)
예제 #33
0
def cli(query, playlistsearch, video, playlist, interactive):
    LOCAL_PLAYLIST = False

    if interactive:
        tui.main()
    else:
        if not query:
            print("Error: Enter a search query")
            sys.exit(1)

        query = " ".join(query)

        url = ""
        choice = dict()

        if video:
            isValid, details = isValidURL(query, urlType="video")
            if isValid:
                # print(f"Selected : {url}")
                choice['id'] = details['id']
                choice['url'] = query
                choice['title'] = details['snippet']['title']
            else:
                print("Invalid URL")
                sys.exit(3)
        elif playlist:
            isValid, details = isValidURL(query, urlType="playlist")
            if isValid:
                # print(f"Selected : {url}")
                choice['id'] = details['id']
                choice['url'] = query
                choice['title'] = details['snippet']['title']
            else:
                if os.path.exists(query):
                    LOCAL_PLAYLIST = parse_file(query)
                else:
                    print("ERROR: Wrong link or file path")
                    sys.exit(3)
        else:
            if playlistsearch:
                results = search_pl(query)
            else:
                results = search_video(query)

            if len(results) < 1:
                click.secho("No results found.", fg="red")
                sys.exit(3)

            options = [x["title"] for x in results]
            title = f"Search results for {query} (q to quit)"

            picker = Picker(options, title)
            picker.register_custom_handler(ord('q'), quit_pick)
            option, index = picker.start()

            choice = results[index]

        selected = query if LOCAL_PLAYLIST else choice['url']
        print(f"Selected : {selected}")

        options = ["Play", "Download"]
        title = "Choose what you want to do (q to quit)"
        picker = Picker(options, title)

        picker.register_custom_handler(ord('q'), quit_pick)

        option, index = picker.start()

        if playlist or playlistsearch:

            if LOCAL_PLAYLIST:
                playlist_list = LOCAL_PLAYLIST
            else:
                playlist_list = extract_playlist_data(choice['url'])

            for video in playlist_list:
                if option == "Download":
                    print(f"\x1B[1KDownload: {video['title']}\n")
                    download_video(video['url'], print_hook)
                    # print()
                elif option == "Play":
                    play_audio(video['url'], video['title'])
        else:
            if option == "Download":
                print(f"\x1B[1KDownload: {choice['title']}\n")
                download_video(choice['url'], print_hook)
            elif option == "Play":
                play_audio(choice['url'], choice['title'])
예제 #34
0
파일: custom.py 프로젝트: eth0izzle/pick
#-*-coding:utf-8-*-

from __future__ import print_function

import curses
from pick import Picker

def go_back(picker):
    return (None, -1)

title = 'Please choose your favorite programming language: '
options = ['Java', 'JavaScript', 'Python', 'PHP', 'C++', 'Erlang', 'Haskell']

picker = Picker(options, title)
picker.register_custom_handler(curses.KEY_LEFT, go_back)
option, index = picker.start()
print(option, index)
예제 #35
0
def ws_picker(actions: 'list[str]', title: str, **kwargs) -> Picker:
    picker = Picker(actions, title, **kwargs)
    picker.register_custom_handler(ord('w'), m.move_up())
    picker.register_custom_handler(ord('s'), m.move_down())
    return picker
예제 #36
0
def view_file(name, types, pid):
    """
    view-files: Filter based list of the names and ids of the first 10 files the user has access to
    """
    cwd = os.getcwd()
    flags = {"--name": [None], "--types": [None], "--pid": [None]}
    token = os.path.join(dirpath, 'token.json')
    store = file.Storage(token)
    creds = store.get()
    service = build('drive', 'v3', http=creds.authorize(Http()))
    page_token = None
    query = ""
    if name:
        q_name = click.prompt('enter the search value')
        flags["--name"] = [q_name]
        query = "name contains '" + q_name + "' "
    if types:
        mimeTypes = {extension: mime.guess_type("placeholder_filename." + extension)[0] for extension
                     in ("xls",
                         "xlsx",
                         "xml",
                         "ods",
                         "csv",
                         "pdf",
                         "jpg",
                         "png",
                         "gif",
                         "bmp",
                         "txt",
                         "doc",
                         "js",
                         "swf",
                         "mp3",
                         "zip",
                         "rar",
                         "tar",
                         "cab",
                         "html",
                         "htm")}
        mimeTypes.update({'tmpl': 'text/plain',
                          'php': 'application/x-httpd-php',
                          'arj': 'application/arj',
                          "default": 'application/octet-stream',
                          "audio": 'application/vnd.google-apps.audio',
                          "Google Docs": 'application/vnd.google-apps.document',
                          "Google Drawing": 'application/vnd.google-apps.drawing',
                          "Google Drive file": 'application/vnd.google-apps.file',
                          "Google Forms": 'application/vnd.google-apps.form',
                          "Google Fusion Tables": 'application/vnd.google-apps.fusiontable',
                          "Google My Maps": 'application/vnd.google-apps.map',
                          "Google Photos": 'application/vnd.google-apps.photo',
                          "Google Slides": 'application/vnd.google-apps.presentation',
                          "Google Apps Scripts": 'application/vnd.google-apps.script',
                          "Google Sites": 'application/vnd.google-apps.site',
                          "Google Sheets": 'application/vnd.google-apps.spreadsheet',
                          "3rd party shortcut": 'application/vnd.google-apps.drive-sdk',
                          "folder": 'application/vnd.google-apps.folder'})
        promptMessage = 'Choose a media type to filter \n(press SPACE to mark, ENTER to continue, s to stop):'
        title = promptMessage
        options = [x for x in mimeTypes.keys()]
        picker = Picker(options, title, multi_select=True,
                        min_selection_count=1)
        picker.register_custom_handler(ord('s'), utils.go_back)
        selected = picker.start()
        option = []
        if isinstance(selected, list):
            query += "and ("
            for types in selected:
                query += "mimeType='" + mimeTypes[types[0]] + "' or "
                option.append(types[0])
            query = query[:-3]
            query += ")"
            flags["--types"] = option
        if (not name) and types:
            query = query[4:]
    if pid:
        parent = click.prompt('enter the fid of parent or  sharing link')
        flags["--pid"] = [parent]
        fid = utils.get_fid(parent)
        if (name != False) or (types != False):
            query += " and "
        query += "'" + fid + "' in parents"
    i = 1
    while True:
        response = service.files().list(q=query,
                                        spaces='drive',
                                        fields='nextPageToken, files(id, name,mimeType,modifiedTime)',
                                        pageToken=page_token).execute()

        templist = [response.get('files', [])[j:j + 25] for j in range(0, len(
            response.get('files', [])), 25)]
        for item in templist:
            t = PrettyTable(['Sr.', 'Name', 'ID', 'Type', 'Modified Time'])
            for fils in item:
                t.add_row([i, fils.get('name')[:25], fils.get('id'), fils.get(
                    'mimeType').replace('application/', '')[:25], fils.get('modifiedTime')])
                i += 1
            print(t)
            click.confirm('Do you want to continue?', abort=True)
            click.clear()
        page_token = response.get('nextPageToken', None)
        if page_token is None:
            break
    utils.save_history([flags, "", cwd])
예제 #37
0
파일: test_pick.py 프로젝트: eth0izzle/pick
 def test_default_index(self):
     title = 'Please choose an option: '
     options = ['option1', 'option2', 'option3']
     picker = Picker(options, title, default_index=1)
     assert picker.get_selected() == ('option2', 1)