Esempio n. 1
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'")
Esempio n. 2
0
def setup():
    """
    create new setup config
    :return:
    """
    create_folder(MONEY_CONFIG_FOLDER_PATH)

    if ask_overwrite(MONEY_CONFIG_FILE_PATH):
        return

    click.echo(chalk.blue('Enter default currency code:'))
    currency_code = (raw_input().strip())
    click.echo(currency_rates.get_rates(currency_code))
    click.echo(currency_codes.get_symbol(currency_code))
    click.echo(currency_codes.get_currency_name(currency_code))

    click.echo(chalk.blue('Enter initial amount:'))
    initial_money = int(raw_input().strip())

    setup_data = dict(
        currency_code=currency_code,
        initial_money=initial_money
    )

    input_data(setup_data, MONEY_CONFIG_FILE_PATH)
Esempio n. 3
0
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))
Esempio n. 4
0
def view_reading_list(opts):
    """
    get the current reading list
    :param opts:
    """
    if os.path.isfile(READING_LIST_ENTRY_FILE_PATH):
        with open(READING_LIST_ENTRY_FILE_PATH) as reading_list_entry:
            file_contents = yaml.load(reading_list_entry)
            file_contents = dict(file_contents)
            last_updated = time.ctime(
                os.path.getmtime(READING_LIST_ENTRY_FILE_PATH))
            query = opts[1]
            params = opts[0]
            search = ''

            if query != 'None':
                search = "(filtered by " + params + ": " + query + ")"
                filtered_contents = [
                    article for article in file_contents['entries']
                    if is_in_params(params, query, article)
                ]
                file_contents = dict(entries=filtered_contents)

            click.echo(chalk.blue("Your awesome reading list " + search))
            click.echo(chalk.blue("Last updated: " + last_updated))
            print_reading_list(file_contents)
    else:
        empty_list_prompt()
Esempio n. 5
0
File: love.py Progetto: W3SS/yoda
def setup():
    """
    create new setup
    :return:
    """
    create_folder(LOVE_CONFIG_FOLDER_PATH)

    if ask_overwrite(LOVE_CONFIG_FILE_PATH):
        return

    click.echo(chalk.blue('Enter their name:'))
    name = (raw_input().strip())

    click.echo(chalk.blue('Enter sex(M/F):'))
    sex = (raw_input().strip())

    click.echo(chalk.blue('Where do they live?'))
    place = (raw_input().strip())

    setup_data = dict(
        name=name,
        place=place,
        sex=sex
    )

    input_data(setup_data, LOVE_CONFIG_FILE_PATH)
Esempio n. 6
0
File: chat.py Progetto: sahwar/yoda
def process(input_string):
    request.query = input_string
    response = request.getresponse().read()
    output = json.loads(response)
    answer = output["result"]["fulfillment"]["speech"]
    chalk.blue('Yoda speaks:')
    click.echo(answer)
Esempio n. 7
0
def add_person():
    add_in = input('Please enter a name >>')
    phone_number = input('Please enter a phone number >>')
    chalk.blue(
        f'Thanks. You have added, {add_in} who has a phone number of:  {phone_number}'
    )
    phonebook[add_in] = {'Name': add_in, 'Phone': phone_number}
Esempio n. 8
0
def start(resource, options):
    "sets up the desired services and runs the requested action"
    neji = Neji(resource, options=options)
    neji.spinUp(options['fd'])
    chalk.blue(
        'Ready and Listening on port %d...' % options.get('port')
    )
    neji.reactor.run()
Esempio n. 9
0
 def _add_tls_websocket_service_after_running(self, websocket_factory,
                                              *args, **kwargs):
     chalk.blue("TLS websocket listener on port {}".format(
         websocket_factory.port))
     listenWS(factory=websocket_factory,
              contextFactory=self.tls_service.tls_context,
              *args,
              **kwargs)
Esempio n. 10
0
def curvesMenu():
    clear()
    Wellcome()
    print(chalk.blue('  1: ', bold=True) + 'Regresion Polinomica grado N')
    print(chalk.blue('  2: ', bold=True) + 'Regresion Logaritmica')
    print(chalk.blue('  3: ', bold=True) + 'Regresion Exponencial')
    print(chalk.blue('  4: ', bold=True) + 'Regresion Potencial')
    print(chalk.blue('  5: ', bold=True) + 'Volver...')

    return input('\n ► ')
Esempio n. 11
0
def auto_load_tasks():
    for app in settings.INSTALLED_APPS:
        module = importlib.import_module(app)
        try:
            importlib.import_module(app + '.tasks')
            chalk.blue('imported tasks from %s' % app)
        except ImportError as e:
            # print traceback.format_exc()
            pass
    if DEBUG:
        pass
Esempio n. 12
0
def new_task():
    today_entry_check()

    chalk.blue('Input your entry for task:')
    note = raw_input().strip()

    if os.path.isfile(TODAYS_TASKS_ENTRY_FILE_PATH):
        setup_data = dict(time=now_time(), text=note, status=0)
        append_data_into_file(setup_data, TODAYS_TASKS_ENTRY_FILE_PATH)
    else:
        setup_data = dict(entries=[dict(time=now_time(), text=note, status=0)])
        input_data(setup_data, TODAYS_TASKS_ENTRY_FILE_PATH)
Esempio n. 13
0
def define(word):
    """
        Get the meaning of a word
    """
    _word = str(word)
    r = requests.get('https://wordsapiv1.p.mashape.com/words/' + _word +
                     '/definitions',
                     headers={
                         'X-Mashape-Key':
                         'Yq72o8odIlmshPTjxnTMN1xixyy5p1lgtd0jsn2NsJfn7pflhR',
                         "Accept": "application/json"
                     })
    data = r.json()

    try:
        _word = data['word']
        posted = False
        if len(data['definitions']):
            if not posted:
                click.echo(
                    chalk.blue(
                        'A few definitions of the word "' + _word +
                        '" with their parts of speech are given below:'))
                click.echo('---------------------------------')
                posted = True

            for definition in data['definitions']:
                print(definition['partOfSpeech'] + ': ' +
                      definition['definition'])

        # if this word is not in the vocabulary list, add to it!
        if posted:
            words = get_words_list()
            if _word in words:
                click.echo(
                    chalk.blue(
                        'This word already exists in the vocabulary set, so you can practice it while using that'
                    ))
            else:
                with open('resources/vocab-words.txt', 'a') as fp:
                    fp.write('{} - {}\n'.format(
                        _word, data['definitions'][0]['definition']))
                click.echo(
                    chalk.blue(
                        'This word does not exist in the vocabulary set, so it has been added to it so that you can '
                        'practice it while using that'))
        else:
            click.echo(
                chalk.red('Sorry, no definitions were found for this word'))
    except KeyError:
        click.echo(chalk.red('Sorry, no definitions were found for this word'))
        print('Sorry, no definitions were found for this word')
Esempio n. 14
0
def process(input_string):
    request.query = input_string
    try:
        response = request.getresponse().read()
    except socket.gaierror:
        # if the user is not connected to internet dont give a response
        click.echo('Yoda cannot sense the internet right now!')
        sys.exit(1)

    output = json.loads(response)
    answer = output["result"]["fulfillment"]["speech"]
    chalk.blue('Yoda speaks:')
    click.echo(answer)
Esempio n. 15
0
def import_tasks():
    for app in TASK_PATHS:
        if not app.split('.')[-1] == 'tasks':
            module = importlib.import_module(app)
            filename = os.path.join(module.__path__[0], 'tasks.py')
            if not os.path.isfile(filename):
                chalk.yellow(app + ' does not have a tasks module.')
                continue
            else:
                app = app + '.tasks'

        chalk.blue(app.upper() + ': imported tasks from %s' % app)
        importlib.import_module(app)
Esempio n. 16
0
def import_tasks():
    for app in TASK_PATHS:
        if not app.split('.')[-1] == 'tasks':
            module = importlib.import_module(app)
            filename = os.path.join(module.__path__[0], 'tasks.py')
            if not os.path.isfile(filename):
                chalk.yellow(app + ' does not have a tasks module.')
                continue
            else:
                app = app + '.tasks'

        chalk.blue(app.upper() + ': imported tasks from %s' % app)
        importlib.import_module(app)
Esempio n. 17
0
def responseInColor(request, status, headers, prefix='Response', opts=None):
    "Prints the response info in color"
    code, message = status.split(None, 1)
    message = '%s [%s] => Request %s %s %s on pid %d' % (
        prefix, code, str(
            request.host), request.method, request.path, os.getpid())
    signal = int(code) / 100
    if signal == 2:
        chalk.green(message, opts=opts)
    elif signal == 3:
        chalk.blue(message, opts=opts)
    else:
        chalk.red(message, opts=opts)
Esempio n. 18
0
def new_note():
    today_entry_check()

    chalk.blue('Input your entry for note:')
    note = raw_input().strip()

    if os.path.isfile(TODAYS_NOTES_ENTRY_FILE_PATH):
        with open(TODAYS_NOTES_ENTRY_FILE_PATH, "r") as todays_notes_entry:
            setup_data = dict(time=now_time(), text=note)
            append_data_into_file(setup_data, TODAYS_NOTES_ENTRY_FILE_PATH)
    else:
        setup_data = dict(entries=[dict(time=now_time(), text=note)])
        input_data(setup_data, TODAYS_NOTES_ENTRY_FILE_PATH)
Esempio n. 19
0
def import_tasks():
    for app in TASK_PATHS:
        if not app.split(".")[-1] == "tasks":
            module = importlib.import_module(app)
            filename = os.path.join(module.__path__[0], "tasks.py")
            if not os.path.isfile(filename):
                chalk.yellow(app + " does not have a tasks module.")
                continue
            else:
                app = app + ".tasks"

        chalk.blue(app.upper() + ": imported tasks from %s" % app)
        importlib.import_module(app)
Esempio n. 20
0
 def __init__(self, config):
     self.config = config
     if config['DEFAULT']['LoadImage'] == 'True':
         print(
             chalk.blue(
                 f'[INFO] Loading Image from: {config["DEFAULT"]["ImageSource"]}'
             ))
         if config['DEFAULT']['ImageSource'].upper() == "S3":
             self.loadS3 = True
         else:
             self.loadLocal = True
     else:
         print(chalk.blue("[INFO] Using Raspberry Pi Camera module."))
         self.loadPi = True
def friendly_interaction(good_guy, friend):
    file_name = friend.get_kind() + '_dialog.txt'
    with open(file_name) as dialog:
        lines = [line.strip() for line in dialog]
        print(chalk.blue(lines[0]))
        if (hero.get_health() >= 60 and friend.get_kind()
                == 'unicorn') or (found_map and friend.get_kind() == 'troll'):
            print(chalk.blue(lines[1]))
            ans = answer_question(lines[2], ['y', 'n'])
            if ans == 'y':
                print(chalk.blue(random.choice(lines[3:6])))
            else:
                print(chalk.blue(lines[6]))

        else:
            ans = answer_question(lines[7], ['y', 'n'])
            if ans == 'n':
                print(chalk.blue(lines[10]))
            else:
                print(chalk.blue(lines[8]))
                if friend.get_kind() == 'troll':
                    print(
                        chalk.blue(lines[9] + ' ' + str(t_map.get_location())))
                elif friend.get_kind() == 'unicorn':
                    good_guy.update_health(60 - good_guy.get_health())

    print(chalk.blue('You have also earned some experience points'))
    hero.update_level(friend.get_level())

    return good_guy, None
def friendly_interaction(friend):
    file_name = './text/' + friend.get_kind() + '_dialog.txt'
    with open(file_name, 'r') as dialog:
        lines = [line.strip() for line in dialog]

    print(chalk.blue(lines[0]))
    time.sleep(2)
    if (hero.get_health() >= 50 and friend.get_kind()
            == 'unicorn') or (found_map and friend.get_kind() == 'troll'):
        print(chalk.blue(lines[1]))
        ans = answer_question(lines[2], ['y', 'n'])
        time.sleep(2)
        if ans == 'y':
            print(chalk.blue(random.choice(lines[3:6])))
        else:
            print(chalk.blue(lines[6]))

    else:
        ans = answer_question(lines[7], ['y', 'n'])
        time.sleep(2)
        if ans == 'n':
            print(chalk.blue(lines[10]))
        else:
            print(chalk.blue(lines[8]))
            if friend.get_kind() == 'troll':
                print(chalk.blue(lines[9] + ' ' + str(t_map.get_location())))
            elif friend.get_kind() == 'unicorn':
                hero.update_health(60 - hero.get_health())
    time.sleep(3)
    print(chalk.blue('You have also earned some experience points'))
    time.sleep(2)
    hero.update_level(friend.get_level())

    return Empty('empty', location, True)
Esempio n. 23
0
def main(arg):
    print(chalk.blue("[INFO] Looping"))

    # Load the image appropriately
    image = loader.load()

    print(chalk.blue("[INFO] Analyzing Colors..."))
    # Analyze colors in the image
    colors = get_colors(image, 8, True)

    print(chalk.blue("[INFO] Colors: " + str(colors)))

    print(chalk.blue("[INFO] Setting Hue Lights to color..."))
    hue.set_color(7, rgb_to_xy(round(colors[0][0], 0), round(colors[0][1], 0), round(colors[0][2], 0)))
Esempio n. 24
0
    def run(self):
        "sets up the desired services and runs the requested action"
        self.addServices()
        action = self.action
        fd = self.options['fd']

        if action.startswith('start'):
            chalk.blue('Ready and Listening...')
            getattr(self, action)(fd)
            self.reactor.run()
        elif action == 'restart':
            getattr(self, action)(fd=fd)
        else:
            getattr(self, action)()
Esempio n. 25
0
def complete_task():
    not_valid_task_number = 1
    if os.path.isfile(TODAYS_TASKS_ENTRY_FILE_PATH):
        with open(TODAYS_TASKS_ENTRY_FILE_PATH, 'r') as todays_tasks_entry:
            contents = yaml.load(todays_tasks_entry)
            i = 0
            no_task_left = True
            for entry in contents['entries']:
                i += 1
                if entry['status'] == 0:
                    no_task_left = False

            if no_task_left:
                chalk.green(
                    'All tasks have been competed! Add a new task by entering "yoda  diary nt"'
                )
            else:
                click.echo('Today\'s agenda:')
                click.echo('----------------')
                click.echo("Number |  Time   | Task")
                click.echo("-------|---------|-----")

                i = 0
                for entry in contents['entries']:
                    i += 1
                    time = entry['time']
                    text = entry['text'] if entry['status'] == 0 else strike(
                        entry['text'])
                    status = "O" if entry['status'] == 0 else "X"
                    if entry['status'] == 0:
                        no_task_left = False
                        click.echo("   " + str(i) + "   | " + time + ": " +
                                   text)
                while not_valid_task_number:
                    chalk.blue(
                        'Enter the task number that you would like to set as completed'
                    )
                    task_to_be_completed = int(raw_input())
                    if (task_to_be_completed > len(contents['entries'])):
                        chalk.red('Please Enter a valid task number!')
                    else:
                        contents['entries'][task_to_be_completed -
                                            1]['status'] = 1
                        input_data(contents, TODAYS_TASKS_ENTRY_FILE_PATH)
                        not_valid_task_number = 0
    else:
        chalk.red(
            'There are no tasks for today. Add a new task by entering "yoda diary nt"'
        )
Esempio n. 26
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)
def print_image(file_name):
    with open(file_name) as image:
        for line in image:
            line = line.strip('\n')
            print(chalk.magenta(line))
    input(chalk.blue('Press any key to continue...'))
    return
Esempio n. 28
0
def get_weather_data(c, city, today_date):
    if (query_table(c, city, today_date)):
        print(query_table(c, city, today_date))
        print(chalk.blue('Got the value from db, did not made api call'))
        return
    else:
        try:
            openweatherurl = 'https://api.openweathermap.org/data/2.5/weather/'
            q_params = {'q': city, 'appid': '367734831231fafde06835375aa51401'}
            response = requests.get(url=openweatherurl, params=q_params)
            resp = response.json()
            try:

                c.execute(
                    "INSERT into weatherdata (city,weather,temp,date) VALUES(?,?,?,?)",
                    (city, resp['weather'][0]['description'],
                     resp['main']['temp'], today_date))
            except Exception as e:
                print('Unable to save data into database: ', e)
                return
            print(f"Current temperature is : {resp['main']['temp']}")
            print(f"Description is : {resp['weather'][0]['description']}")
            return

        except Exception as e:
            print(
                'Unable to get data from Internet. Please try after sometime. ',
                e)
            return
Esempio n. 29
0
File: chat.py Progetto: zuziik/yoda
def process(input_string):
    """
    minimal chat bot
    :param input_string:
    """
    if 'inspire' in input_string:
        send_data = {
            'method': 'getQuote',
            'format': 'json',
            'lang': 'en',
            'key': ""
        }
        hdr = {'User-Agent': "Magic Browser"}
        full_url = QUOTE_API_URL + '?' + urllib.urlencode(send_data)
        response = urlopen(Request(full_url, headers=hdr))
        response = response.read()
        output = json.loads(response)
        quote = output["quoteText"]
        author = output["quoteAuthor"]
        click.echo(quote)
        click.echo("- " + author)
    else:
        request.query = input_string
        try:
            response = request.getresponse().read()
        except socket.gaierror:
            # if the user is not connected to internet don't give a response
            click.echo(chalk.red('Yoda cannot sense the internet right now!'))
            sys.exit(1)

        output = json.loads(response)
        answer = output["result"]["fulfillment"]["speech"]
        click.echo(chalk.blue('Yoda speaks:'))
        click.echo(answer)
Esempio n. 30
0
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'))
Esempio n. 31
0
def add_idea(project_name, task_name):
    """
    a new entry created
    :param project_name:
    :param task_name:
    """
    try:
        with open(IDEA_CONFIG_FILE_PATH) as f:
            data = f.read()
            data = decryption(data)
            data = json.loads(data)
        f.close()
    except:
        data = None
    if not isinstance(data, dict):
        data = dict()
    if project_name in data:
        task = data[project_name]
    else:
        task = []

    click.echo(chalk.blue('Brief desc of the current task : '))
    desc = raw_input()
    task.append((task_name, desc))  # a new entry created
    data[project_name] = task
    with open(IDEA_CONFIG_FILE_PATH, 'w') as f:
        data = json.dumps(data)
        data = encryption(data)
        f.write(data)
    f.close()
Esempio n. 32
0
    def run(self):
        "sets up the desired services and runs the requested action"
        self.addServices()
        self.catalogServers(self.hendrix)
        action = self.action
        fd = self.options['fd']

        if action.startswith('start'):
            chalk.blue('Ready and Listening on port %d...' %
                       self.options.get('http_port'))
            getattr(self, action)(fd)
            self.reactor.run()
        elif action == 'restart':
            getattr(self, action)(fd=fd)
        else:
            getattr(self, action)()
Esempio n. 33
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
Esempio n. 34
0
def process(input_string):
    """
    minimal chat bot
    :param input_string:
    """
    if "inspire" in input_string:
        send_data = {
            "method": "getQuote",
            "format": "json",
            "lang": "en",
            "key": ""
        }
        hdr = {"User-Agent": "Magic Browser"}
        full_url = QUOTE_API_URL + "?" + urllib.parse.urlencode(send_data)
        response = urlopen(Request(full_url, headers=hdr))
        response = response.read()
        output = json.loads(response)
        quote = output["quoteText"]
        author = output["quoteAuthor"]
        click.echo(quote)
        click.echo("- " + author)
    else:
        request.query = input_string
        try:
            response = request.getresponse().read()
        except socket.gaierror:
            # if the user is not connected to internet don't give a response
            click.echo(chalk.red("Yoda cannot sense the internet right now!"))
            sys.exit(1)

        output = json.loads(response.decode("utf-8"))
        answer = output["result"]["fulfillment"]["speech"]
        click.echo(chalk.blue("Yoda speaks:"))
        click.echo(answer)
Esempio n. 35
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)
Esempio n. 36
0
    def run(self):
        "sets up the desired services and runs the requested action"
        self.addServices()
        self.catalogServers(self.hendrix)
        action = self.action
        fd = self.options['fd']

        if action.startswith('start'):
            chalk.blue(
                'Ready and Listening on port %d...' % self.options.get(
                    'http_port'
                )
            )
            getattr(self, action)(fd)
            self.reactor.run()
        elif action == 'restart':
            getattr(self, action)(fd=fd)
        else:
            getattr(self, action)()
Esempio n. 37
0
 def start(self, fd=None):
     if fd is None:
         # anything in this block is only run once
         self.addGlobalServices()
         self.hendrix.startService()
         pids = [str(os.getpid())]  # script pid
         if self.options['workers']:
             self.launchWorkers(pids)
         self.pid_file = self.openPidList(pids)
     else:
         fds = pickle.loads(fd)
         factories = {}
         for name in self.servers:
             factory = self.disownService(name)
             factories[name] = factory
         self.hendrix.startService()
         for name, factory in factories.iteritems():
             self.addSubprocess(fds, name, factory)
         chalk.eraser()
         chalk.blue('Starting Hendrix...')
Esempio n. 38
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, Argument:
        print Argument
        chalk.red("\n Could not %s hendrix.\n" % action, pipe=chalk.stderr)
Esempio n. 39
0
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)
Esempio n. 40
0
    def run(self):
        "sets up the desired services and runs the requested action"
        self.addServices()
        self.catalogServers(self.hendrix)
        action = self.action
        fd = self.options['fd']

        if action.startswith('start'):
            chalk.blue(self._listening_message())
            getattr(self, action)(fd)

            ###########################
            # annnnd run the reactor! #
            ###########################
            try:
                self.reactor.run()
            finally:
                shutil.rmtree(PID_DIR, ignore_errors=True)  # cleanup tmp PID dir

        elif action == 'restart':
            getattr(self, action)(fd=fd)
        else:
            getattr(self, action)()
Esempio n. 41
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'))
Esempio n. 42
0
def blue(str2):
    if not enable:
        return
    chalk.blue(str2)
Esempio n. 43
0
def call(function_name, str):
    try:
        fun = getattr(chalk, function_name)
        fun(str)
    except:
        chalk.blue(str)
Esempio n. 44
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()
Esempio n. 45
0
File: lidard.py Progetto: sli/lidard
 def close():
     chalk.blue('shutting down')
     server.server_close()