示例#1
0
def get_word_accuracy_of_previous_words():
    accuracy = {}
    for word in words:
        accuracy[word] = []
    if not os.path.isfile(VOCABULARY_CONFIG_FOLDER_PATH + '/results.txt'):
        chalk.red(
            'No words learned in the past. Please use "yoda vocabulary word" for the same')
        return
    with open(VOCABULARY_CONFIG_FOLDER_PATH + '/results.txt') as fp:
        for line in fp.read().split('\n'):
            if len(line) == 0:
                continue
            (date, time, word, correct) = line.split()
            correct = int(correct)
            if word in accuracy:
                accuracy[word].append(correct)

    words_in_history = {}

    for word, lst in accuracy.items():
        if len(lst):
            words_in_history[word] = []
            words_in_history[word].append(len(lst))
            words_in_history[word].append(
                round((sum(lst) * 100) / len(lst)) if len(lst) else 0)

    click.echo(click.style("Words asked in the past: ", bold=True))
    # print(words_in_history)
    for word, ar in words_in_history.items():
        click.echo(word + '-- times used: ' +
                   str(ar[0]) + ' accuracy: ' + str(ar[1]))
def candidate_input(candidates):
    """
    Presents the list of candidates, asks user to vote until done, prints the results of the voting.
    
    :param candidates: dict
    :return: 
    """
    options = {index: goof for index, goof in enumerate(candidates, start=1)}

    while True:
        display_ballot(candidates)
        i_choose = input(
            "Enter your choice for President or type 'done' to see the results. ➙  "
        )

        try:
            i_choose = int(i_choose)

        except ValueError:

            if i_choose == 'done':
                chalk.cyan(f"Total votes per candidate: {candidates}")
                winner = max(candidates.items(), key=lambda t: t[-1])
                chalk.magenta(
                    f"The winner is {winner[0]} with {winner[1]} votes.")
                break

            chalk.red('Please enter the number to the left of the name.')
            continue

        if input_is_valid(i_choose):

            choice = options[i_choose]

            candidates[choice] += 1
示例#3
0
def run_command(command_body,
                cwd=OS_CWD,
                ignore_error=True,
                except_in=MyException.command_error):
    if (DRY_RUN):
        return dummy_run_result()
    else:
        with settings(warn_only=True):
            command_to_run = 'cd {} && {}'.format(cwd, command_body)
            command_result = local(command_to_run, capture=True)
            print(command_result)

            if command_result.failed:
                if ignore_error:
                    print(chalk.red('command: {}'.format(command_to_run)))
                    print(
                        chalk.red(
                            'error found during running command, ignore flag active'
                        ))
                    print_message(command_result.stderr)
                else:
                    print_error(
                        'run_command: error during running command "{}"'.
                        format(command_to_run))

                    print_error('run_command: error message')
                    print_error(command_result.stderr)

                    raise except_in

            return command_result
示例#4
0
def flashcards(domain, action, name):
    """
        Flashcards for learning anything and tracking your progress\n\n
        Domains:\n
        \t sets: Study sets\n
        \t \t Actions:\n
        \t \t list: view study sets\n
        \t \t new <name>: create a new study set\n
        \t \t modify <name>: modify a study set\n
        \t \t select <name>: select an existing study set\n
        \t cards: Flash cards\n
        \t \t Actions:\n
        \t \t add <name>: add a flashcard to the working study set\n
        \t status: Current status of study study set
        \t study: start studying the selected study set
    """
    domain = str(domain)
    action = str(action)
    name = util.tuple_to_string(name)
    domains = {
        'cards': check_sub_command_cards_flashcards,
        'sets': check_sub_command_sets_flashcards,
        'status': status_fc,
        'study': study_fc
    }
    try:
        domains[domain](action, name)
    except KeyError:
        chalk.red('Command does not exist!')
        click.echo('Try "yoda flashcards --help" for more info')
示例#5
0
文件: ux.py 项目: hendrix/hendrix
def main(args=None):
    "The function to execute when running hx"
    if args is None:
        args = sys.argv[1:]
    options, args = HendrixOptionParser.parse_args(args)
    options = vars(options)

    try:
        action = args[0]
    except IndexError:
        HendrixOptionParser.print_help()
        return

    exposeProject(options)

    options = djangoVsWsgi(options)

    options = devFriendly(options)

    redirect = noiseControl(options)

    try:
        launch(*args, **options)
    except Exception:
        chalk.red('\n Encountered an unhandled exception while trying to %s hendrix.\n' % action, pipe=chalk.stderr)
        raise
示例#6
0
def take_away(phonebook):                                           # Remove a person
    banish = input("Enter the name of person to remove from phone book. >> ")

    for index, entry in enumerate(phonebook):
        if banish in entry['First Name']:
            del phonebook[index]
    chalk.red(f"{banish} has been removed form your phonebook forever!")
示例#7
0
文件: learn.py 项目: dclems93/yoda
def select_set_fc(name):
    """
    select working study set
    :param name:
    """
    sets = get_set_statuses()
    if not sets:
        click.echo(
            chalk.red(
                'There are no sets right now. Type "yoda flashcards sets new <name>" to create one'
            ))
    else:
        try:
            if sets[name] == 0:
                click.echo(
                    chalk.red(
                        'Looks like the study set you want to select is closed. Please modify it first'
                    ))
            elif sets[name] == 1:
                SELECTED_STUDY_SET = name
                with open(
                        FLASHCARDS_CONFIG_FOLDER_PATH + '/selected_study_set',
                        'w') as fp:
                    fp.write(SELECTED_STUDY_SET)
                click.echo(
                    chalk.blue('Selected study set: ' + SELECTED_STUDY_SET))
        except KeyError:
            click.echo(chalk.red('Set does not exist'))
示例#8
0
async def start_somewhere(runner):
    print("Searching for an open port...")
    for port in range(48654, 49150):
        if port == 49000:  # reserved
            continue

        site = web.TCPSite(runner, "", port)
        try:
            await site.start()
        except Exception as e:
            print(chalk.red(f"Unable to start on port {port}: {e}"))
            continue
        print(chalk.green(f"Started server on port {port} successfully!"))
        break
    else:
        print(chalk.red("Could not use any available port."))
        raise SystemExit(1)

    print("Opening port via UPnP...")
    upnp = miniupnpc.UPnP()
    upnp.discoverdelay = 10
    upnp.discover()
    upnp.selectigd()
    if upnp.addportmapping(port, "TCP", upnp.lanaddr, port, "PijulGit proxy",
                           ""):
        print(chalk.green(f"Opened port {port} successfully!"))
    else:
        print(chalk.red(f"Failed to open port {port} :("))

    return site, port
示例#9
0
文件: learn.py 项目: dclems93/yoda
def list_sets_fc(dummy):
    """
    gives you a list of all the study sets
    :param dummy:
    """
    sets = get_set_statuses()
    if not sets:
        click.echo(
            chalk.red(
                'There are no sets right now. Type "yoda flashcards sets new <name>" to create one'
            ))
    else:
        i = 0
        there_are_sets = False
        for _set in sets:
            if sets[_set] >= 1:
                if not there_are_sets:
                    click.echo('List of all the study sets:')
                    there_are_sets = True
                i += 1
                click.echo(str(i) + ') ' + _set)
        if not there_are_sets:
            click.echo(
                chalk.red(
                    'Looks like all the sets are closed. Please create a new one or open an existing one'
                ))
示例#10
0
文件: learn.py 项目: dclems93/yoda
def modify_set_fc(name):
    """
    modify a set
    :param name:
    """
    sets = get_set_statuses()
    if not sets:
        click.echo(
            chalk.red(
                'There are no sets right now. Type "yoda flashcards sets new <name>" to create one'
            ))
    else:
        if not sets[name]:
            click.echo(chalk.red('There is no set named ' + name + '.'))
        else:
            click.echo(
                chalk.blue(
                    'Edit a new name for this set: (If you wish to keep it the same, just type a single \'-\' without the '
                    'quotes)'))
            new_name = raw_input().strip()
            if not (new_name is None or new_name == '-' or new_name == ''):
                modify_set_fc_name(name, new_name)
                modify_set_fc_description(name, new_name)
                print('The name was modified from \'' + name + '\' to \'' +
                      new_name + '\'')
示例#11
0
def ideas(subcommand, task, project, inside):
	'''
		Keep track of ideas
	
		yoda ideas SUBCOMMAND [OPTIONAL ARGUMENTS]
	
		ACTION:
		
			show   : list out all the exiting ideas
		
			add    : add a project or a task inside a project
		
			remove : delete a task or a complete project
			
	'''
	if subcommand != 'show' and (project or inside) == None:
		chalk.red('You have not selected any project, Operation aborted.')
		return
	subcommands = {
		'show' : show,
		'add' : add_task,
		'remove' : remove,
	}
	try:
		subcommands[subcommand]((project or inside), task)
	except KeyError:
		chalk.red('Command ' + subcommand + ' does not exist.')
		click.echo('Try "yoda ideas --help" for more info')
示例#12
0
文件: ux.py 项目: damonworx/hendrix
def launch(*args, **options):
    "launch acts on the user specified action and options by executing Hedrix.run"
    action = args[0]
    if options['reload']:
        event_handler = Reload(options)
        observer = Observer()
        observer.schedule(event_handler, path='.', recursive=True)
        observer.start()
        try:
            while True:
                time.sleep(1)
        except KeyboardInterrupt:
            observer.stop()
            pid = os.getpid()
            chalk.eraser()
            chalk.green('\nHendrix successfully closed.')
            os.kill(pid, 15)
        observer.join()
        exit('\n')
    else:
        try:
            deploy = HendrixDeploy(action, options)
            deploy.run()
        except Exception, e:
            if options.get('traceback'):
                tb = sys.exc_info()[2]
                msg = traceback.format_exc(tb)
            else:
                msg = str(e)
            chalk.red(msg, pipe=chalk.stderr)
            os._exit(1)
示例#13
0
def remove(proj, task = None):
	try:
		with open(IDEA_CONFIG_FILE_PATH, 'r') as f:
			data = f.read()
			data = decryption(data)
			data = json.loads(data)
		f.close()
	except:
		chalk.red("File not exist, operation aborted.")
		return
	f.close()
	try:
		if task == None:
			del data[proj]												# a project deleted
			chalk.blue('Project deleted successfully.')
		else:
			data[proj] = filter(lambda x : x[0] != task, data[proj])	# task inside a respective project deleted
			chalk.blue('Task deleted successfully.')
		with open(IDEA_CONFIG_FILE_PATH, 'w') as f:
			#yaml.dump(data, f, default_flow_style = False)
			data = json.dumps(data)
			data = encryption(data)
			f.write(data)
		f.close()
	except:
		chalk.red("Wrong task or project entered. Please check using 'yoda ideas show'")
示例#14
0
def rlist(subcommand, params, query):
    '''
        Reading list for your daily life

        yoda rlist [OPTIONS] SUBCOMMAND [QUERY]

        ACTION:

            view [--params="tags"] [query]: view your reading list

                params: reading list parameter to be filtered (defaults to tags)

                query: keyword to be searched

            add: add something to your reading list
    '''
    subcommand = str(subcommand)
    params = str(params)
    query = str(query)
    opts = (params, query) if params and query else ()
    #print opts
    subcommands = {
        'view': view_rlist,
        'add': add_to_rlist,
    }
    try:
        subcommands[subcommand](opts)
    except KeyError:
        chalk.red("Command " + subcommand  + " does not exist!")
        click.echo("Try 'yoda rlist --help' for more info'")
示例#15
0
def add_to_rlist(query=""):
    chalk.blue("Title of the article:")
    _title = get_input()
    while len(_title) == 0:
        chalk.red("No title, cannot be.")
        chalk.blue("Title of the article:")
        _title = get_input()

    chalk.blue("Author of the article:")
    _author = get_input()

    chalk.blue("Article type/kind/genre (e.g. book, article, blog, sci-fi):")
    _kind = get_input()

    chalk.blue("Tags for easier filtering/searching (seperated by spaces):")
    _tags = get_input().split()

    setup_data = dict(
        title=_title,
        author=_author,
        kind=_kind,
        tags=_tags
    )

    if os.path.isfile(READING_LIST_ENTRY_FILE_PATH):
        append_data_into_file(setup_data, READING_LIST_ENTRY_FILE_PATH)
    else:
        setup_data = dict(entries=[setup_data])
        create_folder(os.path.join(LIFE_CONFIG_FOLDER_PATH, 'rlist'))
        input_data(setup_data, READING_LIST_ENTRY_FILE_PATH)

    chalk.blue("Added " + _title + " to your reading list!")
示例#16
0
def main(args=None):
    "The function to execute when running hx"
    if args is None:
        args = sys.argv[1:]
    options, args = HendrixOptionParser.parse_args(args)
    options = vars(options)

    try:
        action = args[0]
    except IndexError:
        HendrixOptionParser.print_help()
        return

    exposeProject(options)

    options = djangoVsWsgi(options)

    options = devFriendly(options)

    redirect = noiseControl(options)

    try:
        launch(*args, **options)
    except Exception:
        chalk.red('\n Encountered an unhandled exception while trying to %s hendrix.\n' % action, pipe=chalk.stderr)
        raise
示例#17
0
文件: diary.py 项目: epodolsk/dude
def tasks():
    if os.path.isfile(TODAYS_TASKS_ENTRY_FILE_PATH):
        click.echo('Today\'s agenda:')
        click.echo('----------------')
        click.echo("Status |  Time   | Text")
        click.echo("-------|---------|-----")
        incomplete_tasks = 0
        total_tasks = 0
        with open(TODAYS_TASKS_ENTRY_FILE_PATH, 'r') as todays_tasks_entry:
            contents = yaml.load(todays_tasks_entry)
            for entry in contents['entries']:
                total_tasks += 1
                incomplete_tasks += (1 if entry['status'] == 0 else 0)
                time = entry['time']
                text = entry['text'] if entry['status'] == 0 else strike(
                    entry['text'])
                status = "O" if entry['status'] == 0 else "X"
                click.echo("   " + status + "   | " + time + ": " + text)
        click.echo('----------------')
        click.echo('')
        click.echo('Summary:')
        click.echo('----------------')
        if incomplete_tasks == 0:
            chalk.green(
                'All tasks have been competed! Add a new task by entering "dude  diary nt"'
            )
        else:
            chalk.red("Incomplete tasks: " + str(incomplete_tasks))
            chalk.green("Completed tasks: " +
                        str(total_tasks - incomplete_tasks))

    else:
        click.echo(
            'There are no tasks for today. Add a new task by entering "dude diary nt"'
        )
示例#18
0
文件: setup.py 项目: tulikaiam/yoda
def new():
    chalk.blue('Tell me your name, yoda:')
    name = raw_input().strip()
    while len(name) == 0:
        chalk.red("You entered nothing, yoda!")
        chalk.blue('Tell me your name, yoda:')
        name = raw_input().strip()

    chalk.blue('What\'s your email id, yoda?')
    email = raw_input().strip()
    email_validator = lepl.apps.rfc3696.Email()
    while not email_validator(email):
        chalk.red("Invalid email, yoda!")
        chalk.blue('What\'s your email id, yoda?')
        email = raw_input().strip()

    chalk.blue('What\'s your github username, yoda?')
    gh_username = raw_input().strip()
    while len(gh_username) == 0:
        chalk.red("You entered nothing, yoda!")
        chalk.blue('What\'s your github username, yoda?')
        gh_username = raw_input().strip()

    chalk.blue('Enter your github password:'******'Enter your github password:'******'s encrypt our password
    cipher_key = cypher_pass_generator()
    cipher_IV456 = cypher_pass_generator()

    encrypted_gh_password = encrypt_password(cipher_key, cipher_IV456,
                                             gh_password)

    setup_data = dict(name=name,
                      email=email,
                      github=dict(username=gh_username,
                                  password=encrypted_gh_password),
                      encryption=dict(cipher_key=cipher_key,
                                      cipher_IV456=cipher_IV456))

    if not os.path.exists(os.path.dirname(CONFIG_FILE_PATH)):
        try:
            os.makedirs(os.path.dirname(CONFIG_FILE_PATH))
        except OSError as exc:  # Guard against race condition
            if exc.errno != errno.EEXIST:
                raise

    if os.path.isfile(CONFIG_FILE_PATH):
        chalk.red(
            'A configuration file already exists. Are you sure you want to overwrite it? (y/n)'
        )
        overwrite_response = raw_input().lower()
        if not (overwrite_response == 'y' or overwrite_response == 'yes'):
            return

    with open(CONFIG_FILE_PATH, 'w') as config_file:
        yaml.dump(setup_data, config_file, default_flow_style=False)
示例#19
0
文件: dev.py 项目: sahwar/yoda
def check_sub_command_url(action, url):
    sub_commands = {'shorten': url_shorten, 'expand': url_expand}
    try:
        return sub_commands[action](url)
    except KeyError:
        chalk.red('Command does not exist!')
        click.echo('Try "yoda url --help" for more info')
示例#20
0
    def load(self):
        print(
            chalk.blue(
                f'[INFO] Loading Image from S3: {self.config["DEFAULT"]["ImagePath"]}'
            ))
        s3 = boto3.resource('s3', region_name='us-east-1')
        if (os.getenv("AWS_ACCESS_KEY_ID") == None
                or os.getenv("AWS_SECRET_ACCESS_KEY") == None):
            print(
                chalk.red(
                    "[ERROR] Missing aws credentials. Ensure access key id and secret access key values are properly set."
                ))
            os._exit(1)

        if not self.config["DEFAULT"]["ImagePath"].startswith("s3://"):
            print(
                chalk.red(
                    "[ERROR] S3 Image location configuration option must begin with the \"s3://\" prefix."
                ))
            os._exit(1)

        # Parse bucket and path from given configuration
        idx = self.config["DEFAULT"]["ImagePath"][5:].index('/')
        bucketName = self.config["DEFAULT"]["ImagePath"][5:][:idx]
        path = self.config["DEFAULT"]["ImagePath"][5:][idx + 1:]

        bucket = s3.Bucket(bucketName)
        object = bucket.Object(path)

        file_stream = io.StringIO()
        object.download_fileobj(file_stream)
        image = Image.open(file_stream)
        return image
示例#21
0
文件: setup.py 项目: tulikaiam/yoda
def check_sub_command(c):
    sub_commands = {'new': new, 'check': check, 'delete': delete}
    try:
        return sub_commands[c]()
    except KeyError:
        chalk.red('Command does not exist!')
        click.echo('Try "yoda setup --help" for more info')
示例#22
0
文件: gif.py 项目: zhongyujian/yoda
def from_images(ctx):
    args = {
        ctx.args[i].strip("--"): ctx.args[i + 1]
        for i in range(0, len(ctx.args), 2)
    }
    try:
        source = args.pop("source")
    except KeyError:
        click.echo(
            chalk.red("Source parameter is missing. "
                      "Use --source to provide the path."))
        return
    try:
        output = args.pop("output")
    except KeyError:
        click.echo(
            chalk.red("Output path is missing. "
                      "Use --output to provide the path."))
        return
    images = []
    if not os.path.isdir(source):
        click.echo(chalk.red("Source should be a directory."))
    for filename in os.listdir(source):
        if os.path.isfile(os.path.join(source, filename)):
            images.append(imageio.imread(os.path.join(source, filename)))

    try:
        with open(output, "w") as outfile:
            imageio.mimsave(outfile, images, format="gif", **args)
        click.echo(chalk.green("GIF exported at {}".format(output)))
    except (OSError, IOError):
        click.echo(
            chalk.red("Could not write to file {}. "
                      "Please check the path".format(output)))
    async def on_command_error(self, ctx, error):

        if hasattr(ctx.command, 'on_error'):
            return

        error = getattr(error, 'original', error)

        if isinstance(error, commands.DisabledCommand):
            print(chalk.red(f"{ctx.command} is disabled with the command deco"))

        elif isinstance(error, commands.CommandNotFound):
            return
 
        elif isinstance(error, checks.blank):
            return

        elif isinstance(error, commands.MissingPermissions):
            await ctx.send("Sorry, but you don't have permission to use this command. You might need to ask the Club Leader to switch this. (PS! You need Admin to use this command!)")

        else:
            tra = traceback.format_exception_only(type(error), error)
            e = discord.Embed(description="`Oops! That's not supposed to happen, here's the traceback below.` ```py\n%s\n``` \nLooks like you encountered an issue! If you want, you can report this by clicking [here!](https://forms.gle/hJ3KHVwKMFzfs5eq9) (It takes you to a form where you can explain the bug in detail.)" % ''.join(tra), file=sys.stderr, color=conf.err)
            e.set_author(name="That's an issue!",icon_url=ctx.message.author.avatar_url)
            e.set_footer(text="v"+ver)
            await ctx.send(embed=e)
            print(chalk.yellow(f"Warning! The command '{ctx.command}' has just Errored!")) 
            print(chalk.red(f"Traceback: %s" % ''.join(tra)))
示例#24
0
def check_sub_command_cards_flashcards(c, name):
    sub_commands = {'add': add_card_fc}
    try:
        return sub_commands[c](name)
    except KeyError:
        chalk.red('Command does not exist!')
        click.echo('Try "yoda flashcards --help" for more info')
示例#25
0
文件: life.py 项目: dclems93/yoda
def ideas(subcommand, task, project, inside):
    """
        Keep track of your precious ideas.

        yoda ideas SUBCOMMAND [OPTIONAL ARGUMENTS]

        ACTION:

            show   : list out all the exiting ideas

            add    : add a project or a task inside a project. You need to use either --project or --inside flag to
            add a new project/task

            remove : delete a task or a complete project. You need to use either --project or --inside flag to
            remove a project/task

    """
    if subcommand != 'show' and (project or inside) is None:
        click.echo(
            chalk.red(
                'Operation aborted. You have not selected any project or task. Please use this command with either '
                '--project or --inside flag'))
        return
    sub_commands = {
        'show': show,
        'add': add_idea,
        'remove': remove,
    }
    try:
        sub_commands[subcommand]((project or inside), task)
    except KeyError:
        click.echo(chalk.red('Command ' + subcommand + ' does not exist.'))
        click.echo('Try "yoda ideas --help" for more info')
示例#26
0
文件: diary.py 项目: rishabh3/dude
def current_month_task_analysis():
    now = datetime.datetime.now()
    no_of_days_current_month = calendar.monthrange(now.year, now.month)[1]
    total_tasks = 0
    total_incomplete_tasks = 0
    list_of_files = list_of_tasks_files()
    for i in range(0, len(list_of_files)):
        list_of_files[i] = os.path.join(DIARY_CONFIG_FOLDER_PATH,
                                        list_of_files[i])
    for i in list_of_files:
        with open(i, 'r') as fp:
            contents = yaml.load(fp)
            for entry in contents['entries']:
                total_tasks += 1
                total_incomplete_tasks += (1 if entry['status'] == 0 else 0)
    if total_tasks != 0:
        percent_incomplete_task = total_incomplete_tasks * 100 / total_tasks
        percent_complete_task = 100 - percent_incomplete_task
        entry_frequency = total_tasks * 100 / no_of_days_current_month
    else:
        percent_complete_task = 'NA'
        percent_incomplete_task = 'NA'
        entry_frequency = 0
    chalk.red('Percentage of incomplete task : ' +
              str(percent_incomplete_task))
    chalk.green('Percentage of complete task : ' + str(percent_complete_task))
    chalk.blue("Frequency of adding task (Task/Day) : " + str(entry_frequency))
示例#27
0
    def error(self, name: str = "Main Process", output: str = None):
        if output is None:
            return print(
                chalk.red(
                    f"{time.strftime('%c')} - [{name}]: No output provided!"))

        print(chalk.red(f"{time.strftime('%c')} - [{name}]: {output}"))
示例#28
0
def assignDeploymentInstance(action, options):
    try:
        hendrixLauncher(action, options)
    except Exception as e:
        tb = sys.exc_info()[2]
        msg = traceback.format_exc(tb)
        chalk.red(msg, pipe=chalk.stderr)
        os._exit(1)
示例#29
0
    def stat_printer(self, rain_stat: tuple) -> None:
        """display results"""

        date, rain_amount = rain_stat[0], int(rain_stat[1][0] / 24)
        year, month, day = date[-4:], date[3:6].capitalize(), date[1:2]

        chalk.red(
            f"{month}. {day}, {year} had the most rain with {rain_amount} hunderedths of an inch on an hourly average.")
示例#30
0
def status():
    if os.path.isfile(LOVE_CONFIG_FILE_PATH):
        with open(LOVE_CONFIG_FILE_PATH, 'r') as config_file:
            contents = yaml.load(config_file)
            click.echo((contents))
    else:
        chalk.red(
            'The configuration file for this module does not exist. Please type "yoda love setup" to create a new one')
示例#31
0
文件: ux.py 项目: frmdstryr/hendrix
def assignDeploymentInstance(action, options):
    try:
        hendrixLauncher(action, options)
    except Exception as e:
        tb = sys.exc_info()[2]
        msg = traceback.format_exc(tb)
        chalk.red(msg, pipe=chalk.stderr)
        os._exit(1)
示例#32
0
def delete_file(file_path):
    """
    Delete a file
    :param file_path:
    """
    if os.path.exists(file_path):
        os.remove(file_path)
    else:
        chalk.red('The file does not exist')
示例#33
0
def status_fc(set, dummy):
    if not SELECTED_STUDY_SET:
        chalk.red('No set selected')
    else:
        description = get_set_descriptions()[SELECTED_STUDY_SET]
        click.echo('Selected set: ' + SELECTED_STUDY_SET)
        click.echo('Description: ' + description)
        cards_in_selected_set = str(len(listdir(FLASHCARDS_CONFIG_FOLDER_PATH + '/' + SELECTED_STUDY_SET)))
        click.echo('No. of cards in selected set: ' + cards_in_selected_set)
示例#34
0
文件: base.py 项目: dmpayton/hendrix
 def importWSGI(cls, wsgi_dot_path):
     try:
         wsgi_module, application_name = wsgi_dot_path.rsplit('.', 1)
     except AttributeError:
         pid = os.getpid()
         chalk.red(
             "Unable to discern a WSGI application from '%s'" %
             wsgi_dot_path
         )
         os.kill(pid, 15)
     wsgi = importlib.import_module(wsgi_module)
     return getattr(wsgi, application_name, None)
示例#35
0
文件: ux.py 项目: frmdstryr/hendrix
def subprocessLaunch():
    """
    This function is called by the hxw script.
    It takes no arguments, and returns an instance of HendrixDeploy
    """
    if not redis_available:
        raise RedisException("can't launch this subprocess without tiempo/redis.")
    try:
        action='start'
        options = REDIS.get('worker_args')
        assignDeploymentInstance(action='start', options=options)
    except Exception, Argument:
        print Argument
        chalk.red('\n Could not %s hendrix.\n' % action, pipe=chalk.stderr)   
示例#36
0
def main():
    "The function to execute when running hx"
    options, args = HendrixOptionParser.parse_args(sys.argv[1:])
    options = vars(options)

    try:
        action = args[0]
    except IndexError:
        HendrixOptionParser.print_help()
        return

    exposeProject(options)

    options = djangoVsWsgi(options)

    options = devFriendly(options)

    redirect = noiseControl(options)

    try:
        if action == 'start' and not options['daemonize']:
            chalk.eraser()
            chalk.blue('Starting Hendrix...')
        elif action == 'stop':
            chalk.green('Stopping Hendrix...')
        if options['daemonize']:
            daemonize, _reload, opts = cleanOptions(options)
            process = subprocess.Popen(
                ['hx', action] + opts, stdout=redirect, stderr=redirect
            )
            time.sleep(2)
            if process.poll():
                raise RuntimeError
        else:
            launch(*args, **options)
            if action not in ['start_reload', 'restart']:
                chalk.eraser()
                chalk.green('\nHendrix successfully closed.')
    except Exception, e:
        msg = (
            'ERROR: %s\nCould not %s hendrix. Try again using the --traceback '
            'flag for more information.'
        )
        chalk.red(msg % (str(e), action), pipe=chalk.stderr)
        if options['traceback']:
            raise
        else:
            os._exit(1)
示例#37
0
文件: ux.py 项目: hendrix/hendrix
def findSettingsModule():
    "Find the settings module dot path within django's manage.py file"
    try:
        with open('manage.py', 'r') as manage:
            manage_contents = manage.read()

            search = re.search(
                r"([\"\'](?P<module>[a-z\.]+)[\"\'])", manage_contents
            )
            if search:  # django version < 1.7
                settings_mod = search.group("module")

            else:
                # in 1.7, manage.py settings declaration looks like:
                # os.environ.setdefault(
                #     "DJANGO_SETTINGS_MODULE", "example_app.settings"
                # )
                search = re.search(
                    "\".*?\"(,\\s)??\"(?P<module>.*?)\"\\)$",
                    manage_contents, re.I | re.S | re.M
                )
                settings_mod = search.group("module")

        os.environ.setdefault('DJANGO_SETTINGS_MODULE', settings_mod)
    except IOError as e:
        msg = (
                str(e) + '\nPlease ensure that you are in the same directory '
                         'as django\'s "manage.py" file.'
        )
        raise IOError(chalk.red(msg), None, sys.exc_info()[2])
    except AttributeError:
        settings_mod = ''
    return settings_mod
示例#38
0
文件: ux.py 项目: hendrix/hendrix
def djangoVsWsgi(options):
    # settings logic
    if not options['wsgi']:
        settings_mod = findSettingsModule()
        user_settings = options['settings']
        if not settings_mod and not user_settings:
            msg = (
                '\nEither specify:\n--settings mysettings.dot.path\nOR\n'
                'export DJANGO_SETTINGS_MODULE="mysettings.dot.path"\nOR\n'
                'in your manage.py file specify '
                'os.environ.setdefault("DJANGO_SETTINGS_MODULE", '
                '"mysettings.dot.path")'
            )
            raise SettingsError(chalk.red(msg), None, sys.exc_info()[2])
        elif user_settings:
            # if the user specified the settings to use then these take
            # precedence
            options['settings'] = user_settings
        elif settings_mod:
            options['settings'] = settings_mod
    else:
        try:
            base.HendrixDeploy.importWSGI(options['wsgi'])
        except ImportError:
            raise ImportError("The path '%s' does not exist" % options['wsgi'])

    return options
示例#39
0
def responseInColor(request, prefix='Response', opts=None):
    "Prints the response info in color"
    message = '%s [%s] => Request %s %s %s on pid %d' % (
        prefix,
        request.code,
        str(request.host),
        request.method,
        request.path,
        os.getpid()
    )
    signal = int(request.code)/100
    if signal == 2:
        chalk.green(message, opts=opts)
    elif signal == 3:
        chalk.blue(message, opts=opts)
    else:
        chalk.red(message, opts=opts)
示例#40
0
文件: ux.py 项目: pombredanne/hendrix
def launch(*args, **options):
    """
    launch acts on the user specified action and options by executing
    Hedrix.run
    """
    action = args[0]
    if options["reload"]:
        event_handler = Reload(options)
        observer = Observer()
        observer.schedule(event_handler, path=".", recursive=True)
        observer.start()
        try:
            while True:
                time.sleep(1)
        except KeyboardInterrupt:
            observer.stop()
            pid = os.getpid()
            chalk.eraser()
            chalk.green("\nHendrix successfully closed.")
            os.kill(pid, 15)
        observer.join()
        exit("\n")
    else:
        try:
            if options["key"] and options["cert"] and options["cache"]:
                from hendrix.deploy import hybrid

                HendrixDeploy = hybrid.HendrixDeployHybrid
            elif options["key"] and options["cert"]:
                from hendrix.deploy import ssl

                HendrixDeploy = ssl.HendrixDeploySSL
            elif options["cache"]:
                HendrixDeploy = cache.HendrixDeployCache
            else:
                HendrixDeploy = base.HendrixDeploy
            deploy = HendrixDeploy(action, options)
            deploy.run()
        except Exception, e:
            tb = sys.exc_info()[2]
            msg = traceback.format_exc(tb)
            chalk.red(msg, pipe=chalk.stderr)
            os._exit(1)
示例#41
0
文件: ux.py 项目: pombredanne/hendrix
def main():
    "The function to execute when running hx"
    options, args = HendrixOptionParser.parse_args(sys.argv[1:])
    options = vars(options)

    try:
        action = args[0]
    except IndexError:
        HendrixOptionParser.print_help()
        return

    exposeProject(options)

    options = djangoVsWsgi(options)

    options = devFriendly(options)

    redirect = noiseControl(options)

    try:
        if action == "start" and not options["daemonize"]:
            chalk.eraser()
            chalk.blue("Starting Hendrix...")
        elif action == "stop":
            chalk.green("Stopping Hendrix...")
        if options["daemonize"]:
            daemonize, _reload, opts = cleanOptions(options)
            process = subprocess.Popen(["hx", action] + opts, stdout=redirect, stderr=redirect)
            time.sleep(2)
            if process.poll():
                raise RuntimeError
        else:
            launch(*args, **options)
            if action not in ["start_reload", "restart"]:
                chalk.eraser()
                chalk.green("\nHendrix successfully closed.")
    except Exception, Argument:
        print Argument
        chalk.red("\n Could not %s hendrix.\n" % action, pipe=chalk.stderr)
示例#42
0
文件: ux.py 项目: dmpayton/hendrix
def main():
    "The function to execute when running hx"
    options, args = HendrixOptionParser.parse_args(sys.argv[1:])
    options = vars(options)

    action = args[0]

    exposeProject(options)

    options = djangoVsWsgi(options)

    options = devFriendly(options)

    redirect = noiseControl(options)

    try:
        if action == "start" and not options["daemonize"]:
            chalk.eraser()
            chalk.blue("Starting Hendrix...")
        elif action == "stop":
            chalk.green("Stopping Hendrix...")
        if options["daemonize"]:
            daemonize, _reload, opts = cleanOptions(options)
            process = subprocess.Popen(["hx", action] + opts, stdout=redirect, stderr=redirect)
            time.sleep(2)
            if process.poll():
                raise RuntimeError
        else:
            launch(*args, **options)
            if action not in ["start_reload", "restart"]:
                chalk.eraser()
                chalk.green("\nHendrix successfully closed.")
    except Exception, e:
        msg = "ERROR: %s\nCould not %s hendrix. Try again using the --traceback " "flag for more information."
        chalk.red(msg % (str(e), action), pipe=chalk.stderr)
        if options["traceback"]:
            raise
        else:
            os._exit(1)
示例#43
0
文件: ux.py 项目: frmdstryr/hendrix
def main():
    "The function to execute when running hx"
    options, args = HendrixOptionParser.parse_args(sys.argv[1:])
    options = vars(options)

    try:
        action = args[0]
    except IndexError:
        HendrixOptionParser.print_help()
        return

    exposeProject(options)

    options = djangoVsWsgi(options)

    options = devFriendly(options)

    redirect = noiseControl(options)

    try:
        launch(*args, **options)
    except Exception, Argument:
        print Argument
        chalk.red('\n Could not %s hendrix.\n' % action, pipe=chalk.stderr)
示例#44
0
def some_callable():
    chalk.red("This is some callable.")
示例#45
0
def something():
    chalk.red("something")
示例#46
0
#!/usr/bin/env python

import chalk

chalk.red("Hello world!!")
chalk.yellow("This looks like a warning...")
chalk.cyan('...more formatting', opts=('bold', 'underscore'))
示例#47
0
 def formatException(self, ei):
     exception = super(ChalkFormatter, self).formatException(ei)
     return chalk.red(exception)
示例#48
0
    def control(self):
        if self.active_task:
            msg = '%r currently busy with a task from %r'%(self, self.active_task)
            chalk.red(msg)
            logger.debug(msg)

        """
            First we check our task registry and check if there are any
            tasks that should be running right this second.

            If there are, we queue them.

            Next we execute queued tasks

        """

        now = utc_now()
        tomorrow = now + datetime.timedelta(days=1)

        time_tasks = get_task_keys(self.task_groups)

        _tasks = [
            t for t in TIEMPO_REGISTRY.values()
            if t.group in self.task_groups and t.periodic
        ]
        for _task in _tasks:
            stop_key = '%s:schedule:%s:stop' % (resolve_group_namespace(_task.group), _task.key)

            if hasattr(_task, 'force_interval'):
                expire_key = now + datetime.timedelta(
                    seconds=_task.force_interval
                )
            else:
                expire_key = time_tasks.get(_task.get_schedule())
            # the expire key is a datetime which signifies the NEXT time this
            # task would run if it was to be run right now.
            #
            # if there is no expire key it means that there are no tasks that
            # should run right now.

            if expire_key:
                # if we are here, it means we have a task that could run
                # right now if no other worker has already started it.
                try:

                    # create a key whose existence prevents this task
                    # from executing.  This will ensure that it only runs
                    # once across the whole network.

                    if REDIS.setnx(stop_key, 0):
                        logger.debug(
                            'running task %r because: %r',
                            _task, _task.get_schedule()
                        )
                        logger.debug('expire key: %r', expire_key)
                        logger.debug('now: %r', now)
                        logger.debug('stop key: %r', stop_key)
                        logger.debug(
                            'seconds: %r', (expire_key - now).total_seconds()
                        )
                        # the creation of the key was successful.
                        # this means that previous keys whose existence
                        # postponed execution for this task have expired.

                        # We will now set the expiration on this key to expire
                        # at the time of the next appropriate running of this
                        # task

                        REDIS.expire(
                            stop_key,
                            int(float((expire_key - now).total_seconds())) - 1
                        )

                        # queue it up
                        _task.soon()

                        logger.debug('next will be: %r', expire_key)

                except ResponseError as e:
                    print e
                except BaseException as e:
                    print e

        try:
            for g in self.task_groups:
                if not self.active_task:
                    msg = '%r checking for work in group %r' % (self, g)
                    chalk.blue(msg)
                    logger.debug(msg)
                    task = REDIS.lpop(resolve_group_namespace(g))
                    if task:
                        logger.debug(
                            'RUNNING TASK on thread %r: %s' % (self, task)
                        )
                        self.active_task = resolve_group_namespace(g)
                        return threads.deferToThread(run_task, task, self)

        except BaseException as e:
            chalk.red('%s got an error' % self)
            print traceback.format_exc()
示例#49
0
#!/usr/bin/env python

import chalk

chalk.blue("Hello world!!")
chalk.yellow("Listen to me!!!")
chalk.red("ERROR", pipe=chalk.stderr)
chalk.magenta('This is pretty cool', opts='bold')
chalk.cyan('...more stuff', opts=('bold', 'underscore'))