Example #1
0
    def _decrypt(self, cipher):
        """Decrypts a cipher string using self.key as the key and the first 16 byte of the cipher as the IV"""
        if not crypto_installed:
            sys.exit("Error: PyCrypto is not installed.")
        if not cipher:
            return ""
        crypto = AES.new(self.key, AES.MODE_CBC, cipher[:16])
        try:
            plain = crypto.decrypt(cipher[16:])
        except ValueError:
            util.prompt(
                "ERROR: Your journal file seems to be corrupted. You do have a backup, don't you?"
            )
            sys.exit(1)

        padding_length = util.byte2int(plain[-1])
        if padding_length > AES.block_size and padding_length != 32:
            # 32 is the space character and is kept for backwards compatibility
            return None
        elif padding_length == 32:
            plain = plain.strip()
        elif plain[-padding_length:] != util.int2byte(
                padding_length) * padding_length:
            # Invalid padding!
            return None
        else:
            plain = plain[:-padding_length]
        return plain.decode("utf-8")
Example #2
0
def do_prompts():
    context = {}
    context['namespace'] = prompt(
        'Enter a kubernetes namespace for the elasticsearch cluster',
        '^[a-z][-a-z0-9]{1,19}$', 'default')
    context['cluster_name'] = prompt(
        'Enter a name for the elasticsearch cluster', '^[a-z][-a-z0-9]{1,19}$',
        'my-es-cluster')
    print('Select the node size: ')
    for i, key in enumerate(data_node_configs):
        print(f'{i+1}: {key}')
    config_count = len(data_node_configs)  # Will break regex if > 9 configs
    node_size_choice = int(
        prompt(f'[1-{config_count}]: ', f'^[1-{config_count}]$', '2'))
    context['data_node'] = data_node_configs[list(
        data_node_configs.keys())[node_size_choice - 1]]
    if node_size_choice != 1:
        context['data_node']['replicas'] = int(
            prompt('Enter the number of nodes (2-9)', '^[2-9]$', '2'))
    context['data_node']['volume_size'] = prompt(
        'Enter the data volume size in GB [10-9999]', '^[1-9][0-9]{1,3}$',
        '250')
    prompt_for_logstash_certs(
        context,
        os.path.join(clusters_dir, context['namespace'], "logstash-ssl-keys"))
    prompt_for_oauth_config(context)
    return context
Example #3
0
def check_table_schema(tablename, force=False, backupname="_backup"):
    """Compare existing table schema with that specified in schema above
    and make corrections as needed.  This checks for new tables, new
    fields, new (foreign key) constraints, and altered field specificaitons.
    For schema changes beyond just adding fields, it renames the old table
    to a "backup" table, and then copies its content into a freshly built
    new version of the table.
    For really complex schema changs, move the old database aside and
    either build from scratch or manually alter it.
    """
    table_fields = schema[tablename]
    with getCur() as cur:
        cur.execute("PRAGMA table_info('{0}')".format(tablename))
        actual_fields = cur.fetchall()
        cur.execute("PRAGMA foreign_key_list('{0}')".format(tablename))
        actual_fkeys = cur.fetchall()
        if len(actual_fields) == 0:
            cur.execute("CREATE TABLE IF NOT EXISTS {0} ({1});".format(
                tablename, ", ".join(table_fields)))
        else:
            fields_to_add = missing_fields(table_fields, actual_fields)
            fkeys_to_add = missing_constraints(table_fields, actual_fkeys)
            altered = altered_fields(table_fields, actual_fields)
            deleted = deleted_fields(table_fields, actual_fields)
            if (len(fields_to_add) > 0 and len(fkeys_to_add) == 0 and
                len(altered) == 0):
                # Only new fields to add
                if force or util.prompt(
                        "SCHEMA CHANGE: Add {0} to table {1}".format(
                            ", ".join(fields_to_add), tablename)):
                    for field_spec in fields_to_add:
                        cur.execute("ALTER TABLE {0} ADD COLUMN {1};".format(
                            tablename, field_spec))
            elif len(fkeys_to_add) > 0 or len(altered) > 0:
                # Fields have changed significantly; try copying old into new
                if force or util.prompt(
                        ("SCHEMA CHANGE: Backup and recreate table {0} "
                         "to add {1}, impose {2}, correct {3}, and delete {4}))").format(
                             tablename, fields_to_add, fkeys_to_add,
                             altered, deleted)):
                    make_backup()
                    backup = tablename + backupname
                    sql = "ALTER TABLE {0} RENAME TO {1};".format(
                        tablename, backup)
                    cur.execute(sql)
                    sql = "CREATE TABLE {0} ({1});".format(
                        tablename, ", ".join(table_fields))
                    cur.execute(sql)
                    # Copy all actual fields that have a corresponding field
                    # in the new schema
                    common_fields = [
                        f[1] for f in actual_fields if
                        find_field_spec_for_pragma(table_fields, f)]
                    sql = "INSERT INTO {0} ({1}) SELECT {1} FROM {2};".format(
                        tablename, ", ".join(common_fields), backup)
                    cur.execute(sql)
                    sql = "DROP TABLE {0};".format(backup)
                    cur.execute(sql)
Example #4
0
 def getType(commd):
     t = _getType(commd[0:2])
     if t: return t
     t = _getType(car(commd))
     if t: 
         return t
     else:
         prompt("error type analysis in %s"%commd)
         raise TypeError
Example #5
0
File: cli.py Project: bentsai/jrnl
def encrypt(journal, filename=None):
    """ Encrypt into new file. If filename is not set, we encrypt the journal file itself. """
    password = util.getpass("Enter new password: "******"Do you want to store the password in your keychain?", default=True):
        util.set_keychain(journal.name, password)
    util.prompt("Journal encrypted to {0}.".format(filename or journal.config['journal']))
Example #6
0
def encrypt(journal, filename=None):
    """ Encrypt into new file. If filename is not set, we encrypt the journal file itself. """
    password = util.getpass("Enter new password: "******"Do you want to store the password in your keychain?", default=True):
        util.set_keychain(journal.name, password)
    util.prompt("Journal encrypted to {0}.".format(filename or journal.config['journal']))
Example #7
0
File: cli.py Project: bentsai/jrnl
def get_text_from_editor(config):
    tmpfile = os.path.join(tempfile.gettempdir(), "jrnl")
    subprocess.call(config['editor'].split() + [tmpfile])
    if os.path.exists(tmpfile):
        with open(tmpfile) as f:
            raw = f.read()
        os.remove(tmpfile)
    else:
        util.prompt('[Nothing saved to file]')
        raw = ''

    return raw
Example #8
0
 def cleanup_obsolete(self, game, sha):
     htdocs = self.args.htdocs
     if not htdocs:
         return
     c = self.db.cursor()
     c.execute('SELECT file FROM file WHERE game_sha = ?', (sha, ))
     exclude = self.settings['obsolete_exclude'].split(',')
     obsolete = list()
     for (fname, ) in c:
         contentless = re.sub('^content/', '', fname)
         path = os.path.abspath(os.path.join(htdocs, contentless))
         rel = os.path.relpath(path, htdocs)
         if os.path.isfile(path):
             if any([fnmatch.fnmatch(rel, rule) for rule in exclude]):
                 print('Obsolete (excluded):', rel)
                 continue
             obsolete.append(path)
             print('Obsolete:', rel)
     if len(obsolete) < int(self.settings['obsolete_threshold']):
         message = f'only {len(obsolete)}' if obsolete else 'no'
         pcolor(
             'yellow',
             f'Warning: An htdocs path was provided but {message} files were found. Possibly a bad conversion?'
         )
     if not obsolete:
         sys.exit(0)
     if util.prompt(f'Delete {len(obsolete)} files?'):
         delete_paths(htdocs, obsolete)
Example #9
0
 def _decrypt(self, cipher):
     """Decrypts a cipher string using self.key as the key and the first 16 byte of the cipher as the IV"""
     if not crypto_installed:
         sys.exit("Error: PyCrypto is not installed.")
     if not cipher:
         return ""
     crypto = AES.new(self.key, AES.MODE_CBC, cipher[:16])
     try:
         plain = crypto.decrypt(cipher[16:])
     except ValueError:
         util.prompt("ERROR: Your journal file seems to be corrupted. You do have a backup, don't you?")
         sys.exit(1)
     padding = " ".encode("utf-8")
     if not plain.endswith(padding):  # Journals are always padded
         return None
     else:
         return plain.decode("utf-8")
Example #10
0
def prompt_for_logstash_certs(context, cert_dir):
    if check_cert_presence(cert_dir):
        print(f"Using keys and certs for Logstash found in {cert_dir}.")
        context['skip_logstash'] = False
    else:
        do_logstash = prompt("Would you like to set up Logstash (with SSL beats input)? (Y/n)",
            "^[yYnN]?$"
        )
        if do_logstash and do_logstash.lower() != 'y':
            context['skip_logstash'] = True
            return
        else:
            context['skip_logstash'] = False
        print("Provide the following information to generate self-signed certificates: ")
        ca_name = prompt("Certificate Authority Name", default='Logstash CA')
        url = prompt("CN - Common Name for Logstash",
            regex='^[a-zA-Z.-0-9]+$',
            default='logstash.my-domain.com'
        )
        country = prompt("C - Country Code",
            regex='[A-Z]{1,4}',
            default='US'
        )
        state = prompt("ST - State",
            regex='[A-Z]{1,4}',
            default='CA'
        )
        loc = prompt("L - Location",
            regex='[A-Za-z 0-9-_.]+',
            default='San Francisco'
        )
        org = prompt("O - Org",
            regex='[A-Za-z 0-9-_.]+',
            default='Acme'
        )
        org_unit = prompt("OU - Org Unit",
            regex='[A-Za-z 0-9-_.]+',
            default='Computers'
        )
        ensure_dir(os.path.join(cert_dir,'afile'))
        subprocess.run([
            os.path.join(dirname, 'templates', '6_logstash', 'ssl-gen.sh'),
            ca_name, url, country, state, loc, org, org_unit, cert_dir
        ], check=True)
        if not check_cert_presence(cert_dir):
            raise RuntimeError('certs failed to generate')
    try:
        shutil.rmtree(template_secrets_dir)
    except:
        pass
    shutil.copytree(cert_dir, template_secrets_dir)
    context['logstash_beats_port'] = '8751'
Example #11
0
def commandParse(commd,std=stdPrint):
    commd = replaceAlias(commd)
    rest = commd.strip()
    lop, rop = [[]], [[]]
    exps = lop
    iotype = None
    while rest:
        etp, frt, rest = getEle(rest)
        if etp.startswith('IO'):
            if iotype is not None:
                prompt('invalid syntax: two IO operationes in command')
                raise SyntaxError
            iotype = etp
            exps = rop
        elif etp is 'PIPE':
            exps.append([])
        else:
            exps[-1].append((etp,frt))
    if iotype == None:
        val = pipeEval(lop)
        if std: std(val)
    elif iotype == 'IO RASSIGN': 
        var, val = eleVal(caar(rop)), pipeEval(lop)
        assign(var, val)
    elif iotype == 'IO LASSIGN':
        var, val = eleVal(caar(lop)), pipeEval(rop)
        assign(var, val)
    elif iotype == "IO APPEND":
        var, val = pipeEval(rop), pipeEval(lop)
        ioredirect(var,val, mode = 'a')
    elif iotype == "IO WRITE":
        var, val = pipeEval(rop), pipeEval(lop)
        ioredirect(var,val, mode = 'w')
    else:
        prompt('undefined syntax')

    return val
Example #12
0
def commandShell():
    while True:
        prompt()
        commd = raw_input().strip()
        addToHistory(commd)
        if commd == 'quit':
            prompt('good bye!')
            return
        try:
            commandParse(commd) 
        except Exception,e:
            exstr = traceback.format_exc()
            prompt(exstr)
Example #13
0
def prompt_for_oauth_config(context):
    do_oauth = prompt("Would you like to configure oauth2_proxy to authorize a GitHub team? (y/N)",
        "^[yYnN]?$"
    )
    if not do_oauth or do_oauth.lower() != 'y':
        context['skip_oauth'] = True
        return
    else:
        context['skip_oauth'] = False
    context['github_org'] = prompt('Enter the GitHub org', '^[a-z0-9-_]+$')
    context['github_team'] = prompt('Enter the GitHub team (optional)', '^[a-z0-9-_]*$')
    context['oauth_client_id'] = prompt('Enter the OAuth Client ID', '^[a-z0-9-]+$')
    context['oauth_client_secret'] = prompt('Enter the OAuth Client Secret', '^[a-z0-9-]+$')
    context['oauth_cookie_name'] = '_ghoauth'
    context['oauth_cookie_secret'] = random_token()
    context['ssl_crt'] = prompt('Enter the path to the SSL certificate', readFile=True)
    context['ssl_key'] = prompt('Enter the path to the SSL private key', readFile=True)
Example #14
0
def rollback(db, session):
    c = db.cursor()
    c.execute(
        "SELECT id, time FROM session WHERE operation != 'ROLLBACK' AND rollback IS NULL ORDER BY time DESC LIMIT 1"
    )
    data = c.fetchone()
    if not data:
        print('Nothing to rollback.')
        return
    prev_session, tstamp = data
    date = datetime.datetime.fromtimestamp(tstamp)
    print(f'Rolling back database to {date}')
    if not util.prompt('Proceed?'):
        sys.exit(0)
    db.execute(
        'DELETE FROM file WHERE game_sha IN (SELECT sha256 FROM game WHERE session = ?)',
        (prev_session, ))
    db.execute('DELETE FROM game WHERE session = ?', (prev_session, ))
    db.execute('UPDATE session SET rollback = ? WHERE id = ?',
               (session, prev_session))
    db.commit()
Example #15
0
 def lexerErrorAna(etype, rtype):
     if etype is not 'ALL' and etype is not rtype:
         prompt('invalid syntax: after $ need function; given %s:'%ltype)
         raise TypeError
Example #16
0
import core, races, classes, enemies, moves, util
import random

unlocked = dict(gladiator=False,
                sage=False,
                saint=False,
                joker=False,
                master=False)

name = input('Name: ').capitalize()
race = util.prompt('Race: ', races.races)
class_ = util.prompt('Class: ', classes.classes)
player = type('Player', (core.Player, race, class_), {})(race, class_, name)
for i in player.moves:
    print(i.desc())
#p(x.__dict__)
while True:
    enemy_choices, dl = [], 2
    while len(enemy_choices) == 0:
        enemy_choices = [
            x for x in enemies.enemies if abs(player.level - x.level) < dl
        ]
        dl += 1
    enemy = random.choice(enemy_choices)()
    print('A {} has spotted you!'.format(str(enemy).lower()))
    ps, es = (x * random.random() / 4 + 0.875
              for x in (player.stats['speed'], enemy.stats['speed']))
    attacker, attacked = (player, enemy) if ps > es else (enemy, player)
    while True:
        attacker.every_round()
        move = attacker.choose_move()
Example #17
0
File: cli.py Project: bentsai/jrnl
def decrypt(journal, filename=None):
    """ Decrypts into new file. If filename is not set, we encrypt the journal file itself. """
    journal.config['encrypt'] = False
    journal.config['password'] = ""
    journal.write(filename)
    util.prompt("Journal decrypted to {0}.".format(filename or journal.config['journal']))
Example #18
0
def stdPrint(s):
    prompt()
    print str(s)
Example #19
0
def run(manual_args=None):
    args = parse_args(manual_args)
    configure_logger(args.debug)
    args.text = [p.decode('utf-8') if util.PY2 and not isinstance(p, unicode) else p for p in args.text]
    if args.version:
        version_str = "{0} version {1}".format(jrnl.__title__, jrnl.__version__)
        print(util.py2encode(version_str))
        sys.exit(0)

    if not os.path.exists(CONFIG_PATH):
        log.debug('Configuration file not found, installing jrnl...')
        config = install.install_jrnl(CONFIG_PATH)
    else:
        log.debug('Reading configuration from file %s', CONFIG_PATH)
        config = util.load_and_fix_json(CONFIG_PATH)
        install.upgrade_config(config, config_path=CONFIG_PATH)

    if args.ls:
        print(util.py2encode(list_journals(config)))
        sys.exit(0)

    log.debug('Using configuration "%s"', config)
    original_config = config.copy()
    # check if the configuration is supported by available modules
    if config['encrypt'] and not PYCRYPTO:
        util.prompt("According to your jrnl_conf, your journal is encrypted, however PyCrypto was not found. To open your journal, install the PyCrypto package from http://www.pycrypto.org.")
        sys.exit(1)

    # If the first textual argument points to a journal file,
    # use this!
    journal_name = args.text[0] if (args.text and args.text[0] in config['journals']) else 'default'
    if journal_name is not 'default':
        args.text = args.text[1:]
    # If the first remaining argument looks like e.g. '-3', interpret that as a limiter
    if not args.limit and args.text and args.text[0].startswith("-"):
        try:
            args.limit = int(args.text[0].lstrip("-"))
            args.text = args.text[1:]
        except:
            pass

    log.debug('Using journal "%s"', journal_name)
    journal_conf = config['journals'].get(journal_name)
    if type(journal_conf) is dict:  # We can override the default config on a by-journal basis
        log.debug('Updating configuration with specific jourlnal overrides %s', journal_conf)
        config.update(journal_conf)
    else:  # But also just give them a string to point to the journal file
        config['journal'] = journal_conf

    if config['journal'] is None:
        util.prompt("You have not specified a journal. Either provide a default journal in your config file, or specify one of your journals on the command line.")
        sys.exit(1)

    config['journal'] = os.path.expanduser(os.path.expandvars(config['journal']))
    touch_journal(config['journal'])
    log.debug('Using journal path %(journal)s', config)
    mode_compose, mode_export = guess_mode(args, config)

    # open journal file or folder
    if os.path.isdir(config['journal']):
        if config['journal'].strip("/").endswith(".dayone") or \
           "entries" in os.listdir(config['journal']):
            journal = DayOneJournal.DayOne(**config)
        else:
            util.prompt("[Error: {0} is a directory, but doesn't seem to be a DayOne journal either.".format(config['journal']))
            sys.exit(1)
    else:
        journal = Journal.Journal(journal_name, **config)

    # How to quit writing?
    if "win32" in sys.platform:
        _exit_multiline_code = "on a blank line, press Ctrl+Z and then Enter"
    else:
        _exit_multiline_code = "press Ctrl+D"

    if mode_compose and not args.text:
        if not sys.stdin.isatty():
            # Piping data into jrnl
            raw = util.py23_read()
        elif config['editor']:
            raw = util.get_text_from_editor(config)
        else:
            try:
                raw = util.py23_read("[Compose Entry; " + _exit_multiline_code + " to finish writing]\n")
            except KeyboardInterrupt:
                util.prompt("[Entry NOT saved to journal.]")
                sys.exit(0)
        if raw:
            args.text = [raw]
        else:
            mode_compose = False

    journal.open()

    # Writing mode
    if mode_compose:
        raw = " ".join(args.text).strip()
        if util.PY2 and type(raw) is not unicode:
            raw = raw.decode(sys.getfilesystemencoding())
        log.debug('Appending raw line "%s" to journal "%s"', raw, journal_name)
        journal.new_entry(raw)
        util.prompt("[Entry added to {0} journal]".format(journal_name))
        journal.write()
    else:
        old_entries = journal.entries
        if args.on_date:
            args.start_date = args.end_date = args.on_date
        journal.filter(tags=args.text,
                       start_date=args.start_date, end_date=args.end_date,
                       strict=args.strict,
                       short=args.short,
                       starred=args.starred)
        journal.limit(args.limit)

    # Reading mode
    if not mode_compose and not mode_export:
        print(util.py2encode(journal.pprint()))

    # Various export modes
    elif args.short:
        print(util.py2encode(journal.pprint(short=True)))

    elif args.tags:
        print(util.py2encode(exporters.to_tag_list(journal)))

    elif args.export is not False:
        print(util.py2encode(exporters.export(journal, args.export, args.output)))

    elif (args.encrypt is not False or args.decrypt is not False) and not PYCRYPTO:
        util.prompt("PyCrypto not found. To encrypt or decrypt your journal, install the PyCrypto package from http://www.pycrypto.org.")

    elif args.encrypt is not False:
        encrypt(journal, filename=args.encrypt)
        # Not encrypting to a separate file: update config!
        if not args.encrypt or args.encrypt == config['journal']:
            update_config(original_config, {"encrypt": True}, journal_name, force_local=True)
            install.save_config(original_config, config_path=CONFIG_PATH)

    elif args.decrypt is not False:
        decrypt(journal, filename=args.decrypt)
        # Not decrypting to a separate file: update config!
        if not args.decrypt or args.decrypt == config['journal']:
            update_config(original_config, {"encrypt": False}, journal_name, force_local=True)
            install.save_config(original_config, config_path=CONFIG_PATH)

    elif args.edit:
        if not config['editor']:
            util.prompt("[You need to specify an editor in {0} to use the --edit function.]".format(CONFIG_PATH))
            sys.exit(1)
        other_entries = [e for e in old_entries if e not in journal.entries]
        # Edit
        old_num_entries = len(journal)
        edited = util.get_text_from_editor(config, journal.editable_str())
        journal.parse_editable_str(edited)
        num_deleted = old_num_entries - len(journal)
        num_edited = len([e for e in journal.entries if e.modified])
        prompts = []
        if num_deleted:
            prompts.append("{0} {1} deleted".format(num_deleted, "entry" if num_deleted == 1 else "entries"))
        if num_edited:
            prompts.append("{0} {1} modified".format(num_edited, "entry" if num_edited == 1 else "entries"))
        if prompts:
            util.prompt("[{0}]".format(", ".join(prompts).capitalize()))
        journal.entries += other_entries
        journal.sort()
        journal.write()
Example #20
0
def decrypt(journal, filename=None):
    """ Decrypts into new file. If filename is not set, we decrypt the journal file itself. """
    journal.config['encrypt'] = False
    journal.config['password'] = ""
    journal.write(filename)
    util.prompt("Journal decrypted to {0}.".format(filename or journal.config['journal']))
Example #21
0
	def choose_move(self):
		return util.prompt('What move do you want to use? ', {k: v for k, v in moves.moves.items() if v in self.moves})
Example #22
0
def cli(manual_args=None):
    if not os.path.exists(CONFIG_PATH):
        config = install.install_jrnl(CONFIG_PATH)
    else:
        with open(CONFIG_PATH) as f:
            try:
                config = json.load(f)
            except ValueError as e:
                util.prompt("[There seems to be something wrong with your jrnl config at {0}: {1}]".format(CONFIG_PATH, e.message))
                util.prompt("[Entry was NOT added to your journal]")
                sys.exit(1)
        install.upgrade_config(config, config_path=CONFIG_PATH)

    original_config = config.copy()
    # check if the configuration is supported by available modules
    if config['encrypt'] and not PYCRYPTO:
        util.prompt("According to your jrnl_conf, your journal is encrypted, however PyCrypto was not found. To open your journal, install the PyCrypto package from http://www.pycrypto.org.")
        sys.exit(1)

    args = parse_args(manual_args)

    # If the first textual argument points to a journal file,
    # use this!
    journal_name = args.text[0] if (args.text and args.text[0] in config['journals']) else 'default'
    if journal_name is not 'default':
        args.text = args.text[1:]
    journal_conf = config['journals'].get(journal_name)
    if type(journal_conf) is dict:  # We can override the default config on a by-journal basis
        config.update(journal_conf)
    else:  # But also just give them a string to point to the journal file
        config['journal'] = journal_conf
    config['journal'] = os.path.expanduser(config['journal'])
    touch_journal(config['journal'])
    mode_compose, mode_export = guess_mode(args, config)

    # open journal file or folder
    if os.path.isdir(config['journal']):
        if config['journal'].strip("/").endswith(".dayone") or \
           "entries" in os.listdir(config['journal']):
            journal = Journal.DayOne(**config)
        else:
            util.prompt("[Error: {0} is a directory, but doesn't seem to be a DayOne journal either.".format(config['journal']))
            sys.exit(1)
    else:
        journal = Journal.Journal(journal_name, **config)

    if mode_compose and not args.text:
        if config['editor']:
            raw = get_text_from_editor(config)
        else:
            raw = util.py23_input("[Compose Entry] ")
        if raw:
            args.text = [raw]
        else:
            mode_compose = False

    # Writing mode
    if mode_compose:
        raw = " ".join(args.text).strip()
        if util.PY2 and type(raw) is not unicode:
            raw = raw.decode(sys.getfilesystemencoding())
        entry = journal.new_entry(raw, args.date)
        entry.starred = args.star
        util.prompt("[Entry added to {0} journal]".format(journal_name))
        journal.write()
    else:
        journal.filter(tags=args.text,
                       start_date=args.start_date, end_date=args.end_date,
                       strict=args.strict,
                       short=args.short)
        journal.limit(args.limit)

    # Reading mode
    if not mode_compose and not mode_export:
        print(journal.pprint())

    # Various export modes
    elif args.tags:
        print(exporters.to_tag_list(journal))

    elif args.export is not False:
        print(exporters.export(journal, args.export, args.output))

    elif (args.encrypt is not False or args.decrypt is not False) and not PYCRYPTO:
        util.prompt("PyCrypto not found. To encrypt or decrypt your journal, install the PyCrypto package from http://www.pycrypto.org.")

    elif args.encrypt is not False:
        encrypt(journal, filename=args.encrypt)
        # Not encrypting to a separate file: update config!
        if not args.encrypt:
            update_config(original_config, {"encrypt": True}, journal_name, force_local=True)
            install.save_config(original_config, config_path=CONFIG_PATH)

    elif args.decrypt is not False:
        decrypt(journal, filename=args.decrypt)
        # Not decrypting to a separate file: update config!
        if not args.decrypt:
            update_config(original_config, {"encrypt": False}, journal_name, force_local=True)
            install.save_config(original_config, config_path=CONFIG_PATH)

    elif args.delete_last:
        last_entry = journal.entries.pop()
        util.prompt("[Deleted Entry:]")
        print(last_entry.pprint())
        journal.write()
Example #23
0
        if move == -1 :
            trace_char = '/'
        elif move == 1 :
            trace_char = '\\'
        board[i-1][curr_col] = trace_char
        curr_col = max(0,min(curr_col+move,game_width))
        board[i][curr_col] = 'o'

        print '\n'.join(''.join(_) for _ in board)
        print '\n'.join(bins)
        time.sleep(0.2)

    final_bin = curr_col/6
    payout = [10,2,0,2,10][final_bin]
    if payout == 10 :
        print("\"Brilliant! The maximum payout indeed! Here are your hard earned lucky coins \n"
              "good sir. Spend them all but naught in the same place! Adieu!\"")
    elif payout == 2 :
        print("\"Not bad, not bad. As they say, two winks are as good as a nod to a blind bat. \n"
              "Spend them all but naught in the same place! Adieu!\"")
    elif payout == 0 :
        print("\"Alas poor victim of cruel vagary, you won naught but a sense of loss and regret. \n"
              "Hone your skills, polish your mind, and return again!\"")
    gamestate.inventory()['monies'] += -skill['bet_amount']+payout*skill['bet_amount']

if __name__ == '__main__' :
    while True :
        resp = prompt("Care to play a game of chahnce?",'yn')
        if resp == 'y' : game_of_chance()
        else : break
Example #24
0
def pipeEval(exps):
    if not exps: 
        prompt('empty expression')
    else:
        vals = map(funcEval, exps)
        return reduce(pipetransfer,vals)
Example #25
0
def main():
    global DIST_DIR
    parser = argparse.ArgumentParser()
    parser.add_argument('path', nargs='?')
    parser.add_argument('-c', '--convert', action='store_true')
    parser.add_argument('-b', '--batch', action='store_true')
    parser.add_argument('-o', '--output', metavar='PATH')
    parser.add_argument('--htdocs', metavar='PATH')
    parser.add_argument('--hooks', choices=['add', 'remove'])
    parser.add_argument('--rollback', action='store_true')
    parser.add_argument('--dat', metavar='FILE')
    parser.add_argument('--set', nargs='?', metavar='KEY=VALUE', const=[])
    parser.add_argument('-n', '--no-color', action='store_true')
    args = parser.parse_args()

    if args.no_color:
        TermColor.ENABLE = False
    elif os.name == 'nt':
        os.system('color')

    db = sqlite3.connect('bluezip.db')
    db.execute(
        'CREATE TABLE IF NOT EXISTS setting (key TEXT PRIMARY KEY, value TEXT)'
    )
    db.execute(
        'CREATE TABLE IF NOT EXISTS session (id TEXT PRIMARY KEY, user TEXT, operation TEXT, time INTEGER, rollback TEXT)'
    )
    db.execute(
        'CREATE TABLE IF NOT EXISTS file (game_sha BLOB, file TEXT, size INTEGER, crc INTEGER, md5 BLOB, sha1 BLOB)'
    )
    db.execute(
        'CREATE TABLE IF NOT EXISTS game (id TEXT, revision INTEGER, sha256 BLOB UNIQUE, title TEXT, platform TEXT, session TEXT, PRIMARY KEY (id, revision))'
    )
    session = os.urandom(6).hex()
    user = '******' % (getpass.getuser(), socket.gethostname())
    settings = Settings(db)
    settings.setdefault('version', DATABASE_VERSION)
    settings.setdefault('set_altapps', '1')
    settings.setdefault('archive_extensions', 'zip,7z')
    settings.setdefault('obsolete_threshold', '1')
    settings.setdefault('obsolete_exclude', '')

    if settings['version'] > DATABASE_VERSION:
        pcolor(
            'yellow',
            'The database was created in a newer version of bluezip. Bluezip might not work correctly and could cause data loss.'
        )
        if not util.prompt('Proceed?'):
            sys.exit(0)

    def log_session(operation):
        db.execute(
            'INSERT INTO session (id, user, operation, time) VALUES (?,?,?,?)',
            (session, user, operation, int(time.time())))
        db.commit()

    if args.output:
        DIST_DIR = args.output

    try:
        os.mkdir(DIST_DIR)
    except FileExistsError:
        pass

    bluezip = Bluezip(db, settings, session, args)
    if args.path:
        if args.batch:
            log_session('BUILD')
            bluezip.process_all(args.path)
        else:
            log_session('BUILD')
            try:
                bluezip.process_auto(args.path, args.convert)
            except ValueError as e:
                pcolor('red', f'\nError: {e}')
                sys.exit(1)
        sys.exit(0)

    if args.dat:
        bluezip_dat.export_dat(db, args.dat)
    elif args.hooks:
        bluezip_hook.run(db, args.hooks)
    elif args.rollback:
        log_session('ROLLBACK')
        rollback(db, session)
    elif args.set != None:
        pcolor(
            'yellow',
            'This command allows modification of internal database attributes. Be careful!'
        )
        if args.set:
            if '=' not in args.set:
                parser.error('use KEY=VALUE')
                sys.exit(1)
            key, value = args.set.split('=')
            append = False
            if key.endswith('+'):
                append = True
                key = key[:-1]
            if key not in settings:
                parser.error(f'unknown attribute: {key}')
                sys.exit(1)
            old = settings[key]
            if append:
                settings[key] += value
            else:
                settings[key] = value
            print(f'Set {key}: "{old}" -> "{settings[key]}"')
        else:
            for key, value in settings:
                print(f'{key}={value}')
    else:
        parser.error('no flags specified')
Example #26
0
 def choose_move(self):
     return util.prompt(
         'What move do you want to use? ',
         {k: v
          for k, v in moves.moves.items() if v in self.moves})
Example #27
0
File: cli.py Project: bentsai/jrnl
def touch_journal(filename):
    """If filename does not exist, touch the file"""
    if not os.path.exists(filename):
        util.prompt("[Journal created at {0}]".format(filename))
        open(filename, 'a').close()
Example #28
0
def calibrate(ball_stats):
    print('Calibrating Analysis')
    if os.path.exists('settings.json'):
        with open('settings.json', 'r') as inf:
            settings = json.load(inf)
    else:
        settings = {}

    settings['num_balls_per_draw'] = num_balls_per_draw = settings.get('num_balls_per_draw',
                                                                       max([len(x) for x in ball_stats]))

    draw_balls_list = [x for x in ball_stats if len(x) == num_balls_per_draw]

    print('Analysis based on %s draws' % len(draw_balls_list))
    print('Number of balls per draw: %s' % settings['num_balls_per_draw'])
    print('\nOdd Ratios')
    odd_ratios = {}
    for draw_balls_item in draw_balls_list:
        odd, even = odd_even_ratio(draw_balls_item)

        ratio = odd_ratios.get(odd, 0) + 1
        odd_ratios[odd] = ratio

    print(odd_ratios)
    default = ','.join([str(x) for x in settings.get('allowed_odd_ratios', [])])
    prompt('Allowed Odd Ratios', default)

    value_str = input()
    if len(value_str) == 0:
        value_str = default

    values = [int(x) for x in value_str.split(',')]
    settings['allowed_odd_ratios'] = values

    print('\nHigh Ratios')
    high_ratios = {}
    for draw_balls_item in draw_balls_list:
        high, low = high_low_ratio(draw_balls_item)
        high_ratios[high] = high_ratios.get(high, 0) + 1

    print(high_ratios)
    default = ','.join([str(x) for x in settings.get('allowed_high_ratios', [])])
    prompt('Allowed High Ratios', default)

    value_str = input()
    if len(value_str) == 0:
        value_str = default

    values = [int(x) for x in value_str.split(',')]
    settings['allowed_high_ratios'] = values

    print('\nAllowed Draw Sums')
    default = settings.get('sum_percentile', None)
    prompt('Allowed Percentile', default)

    value_str = input()
    if len(value_str) == 0:
        value_str = default

    settings['sum_percentile'] = value_str
    value = float(int(value_str) / 100)

    draw_sums = []
    for draw_balls_item in draw_balls_list:
        draw_sums.append(draw_sum(draw_balls_item))

    mean = statistics.mean(draw_sums)
    standard_dev = statistics.stdev(draw_sums)
    low_z = norm.ppf(0.5 - (value / 2))
    high_z = norm.ppf(0.5 + (value / 2))
    min_value = low_z * standard_dev + mean
    max_value = high_z * standard_dev + mean

    settings['max_sum'] = math.ceil(max_value)
    settings['min_sum'] = math.floor(min_value)
    print('Max Sum: %s Min Sum: %s' % (settings['max_sum'], settings['min_sum']))
    print('\nHot Ratios')
    hot_ratios = {}
    for draw_balls_item in draw_balls_list:
        ratio = hot_ratio(draw_balls_item, ball_stats)
        hot_ratios[ratio] = hot_ratios.get(ratio, 0) + 1

    print(hot_ratios)
    default = ','.join([str(x) for x in settings.get('allowed_hot_ratios', [])])
    prompt('Allowed Hot Ratios', default)

    value_str = input()
    if len(value_str) == 0:
        value_str = default

    print('Value Str: %s' % value_str)
    if len(value_str) == 0:
        values = []
    else:
        values = [int(x) for x in value_str.split(',')]

    settings['allowed_hot_ratios'] = values

    sequences_dict = {}
    for ball_item in ball_stats:
        diff = is_number_sequence(ball_item)
        if diff is not None:
            sequence_count = sequences_dict.setdefault(len(ball_item), {})
            sequence_count[diff] = sequence_count.get(diff, 0) + 1

    print('\nNumber Sequences')
    settings.setdefault('allowed_sequences', {})
    for sequence_value, sequence_item in sequences_dict.items():
        print(sequence_value, str(sequence_item))
        default = ','.join([str(x) for x in settings['allowed_sequences'].get(str(sequence_value), [])])
        prompt('Allowed Sequences for Set Len (%d)' % sequence_value, default)

        value_str = input()
        if len(value_str) == 0:
            value_str = default

        if len(value_str) > 0:
            settings['allowed_sequences'][str(sequence_value)] = [int(x) for x in value_str.split(',')]

    total_draws_dict = {}
    for stat_key, stat_value in ball_stats.items():
        if len(stat_key) == 1:
            continue

        total_draws = stat_value.total_draws
        total_draw_count = total_draws_dict.setdefault(len(stat_key), {})
        total_draw_count[total_draws] = total_draw_count.get(total_draws, 0) + 1

    print('\nTotal Draws')
    settings.setdefault('allowed_total_draws', {})
    for total_draws_key, total_draws_value in total_draws_dict.items():
        print(total_draws_key, str(total_draws_value))
        default = ','.join([str(x) for x in settings['allowed_total_draws'].get(str(total_draws_key), [])])
        prompt('Total Draws (min,max) for Set Len (%d)' % total_draws_key, default)

        value_str = input()
        if len(value_str) == 0:
            value_str = default

        settings['allowed_total_draws'][str(total_draws_key)] = [int(x) for x in value_str.split(',')]

    with open('settings.json', 'w') as outf:
        json.dump(settings, outf)
Example #29
0
def touch_journal(filename):
    """If filename does not exist, touch the file"""
    if not os.path.exists(filename):
        log.debug('Creating journal file %s', filename)
        util.prompt("[Journal created at {0}]".format(filename))
        open(filename, 'a').close()
Example #30
0
File: cli.py Project: bentsai/jrnl
def run(manual_args=None):
    if not os.path.exists(CONFIG_PATH):
        config = install.install_jrnl(CONFIG_PATH)
    else:
        config = util.load_and_fix_json(CONFIG_PATH)
        install.upgrade_config(config, config_path=CONFIG_PATH)

    original_config = config.copy()
    # check if the configuration is supported by available modules
    if config['encrypt'] and not PYCRYPTO:
        util.prompt("According to your jrnl_conf, your journal is encrypted, however PyCrypto was not found. To open your journal, install the PyCrypto package from http://www.pycrypto.org.")
        sys.exit(1)

    args = parse_args(manual_args)

    if args.version:
        print("{0} version {1}".format(jrnl.__title__, jrnl.__version__))
        sys.exit(0)

    # If the first textual argument points to a journal file,
    # use this!
    journal_name = args.text[0] if (args.text and args.text[0] in config['journals']) else 'default'
    if journal_name is not 'default':
        args.text = args.text[1:]
    journal_conf = config['journals'].get(journal_name)
    if type(journal_conf) is dict:  # We can override the default config on a by-journal basis
        config.update(journal_conf)
    else:  # But also just give them a string to point to the journal file
        config['journal'] = journal_conf
    config['journal'] = os.path.expanduser(config['journal'])
    touch_journal(config['journal'])
    mode_compose, mode_export = guess_mode(args, config)

    # open journal file or folder
    if os.path.isdir(config['journal']):
        if config['journal'].strip("/").endswith(".dayone") or \
           "entries" in os.listdir(config['journal']):
            journal = Journal.DayOne(**config)
        else:
            util.prompt("[Error: {0} is a directory, but doesn't seem to be a DayOne journal either.".format(config['journal']))
            sys.exit(1)
    else:
        journal = Journal.Journal(journal_name, **config)

    if "win32" in sys.platform:
        # for Windows systems
        _exit_multiline_code = "on a blank line, press Ctrl+Z and then Enter"
    else:
        # for *nix systems (and others?)
        _exit_multiline_code = "press Ctrl+D"

    if mode_compose and not args.text:
        if not sys.stdin.isatty():
            # Piping data into jrnl
            raw = util.py23_read()
        elif config['editor']:
            raw = get_text_from_editor(config)
        else:
            raw = util.py23_read("[Compose Entry; " +  _exit_multiline_code + " to finish writing]\n")
        if raw:
            args.text = [raw]
        else:
            mode_compose = False

    # Writing mode
    if mode_compose:
        raw = " ".join(args.text).strip()
        if util.PY2 and type(raw) is not unicode:
            raw = raw.decode(sys.getfilesystemencoding())
        entry = journal.new_entry(raw)
        util.prompt("[Entry added to {0} journal]".format(journal_name))
        journal.write()
    else:
        journal.filter(tags=args.text,
                       start_date=args.start_date, end_date=args.end_date,
                       strict=args.strict,
                       short=args.short,
                       starred=args.starred)
        journal.limit(args.limit)

    # Reading mode
    if not mode_compose and not mode_export:
        print(journal.pprint())

    # Various export modes
    elif args.short:
        print(journal.pprint(short=True))

    elif args.tags:
        print(exporters.to_tag_list(journal))

    elif args.export is not False:
        print(exporters.export(journal, args.export, args.output))

    elif (args.encrypt is not False or args.decrypt is not False) and not PYCRYPTO:
        util.prompt("PyCrypto not found. To encrypt or decrypt your journal, install the PyCrypto package from http://www.pycrypto.org.")

    elif args.encrypt is not False:
        encrypt(journal, filename=args.encrypt)
        # Not encrypting to a separate file: update config!
        if not args.encrypt:
            update_config(original_config, {"encrypt": True}, journal_name, force_local=True)
            install.save_config(original_config, config_path=CONFIG_PATH)

    elif args.decrypt is not False:
        decrypt(journal, filename=args.decrypt)
        # Not decrypting to a separate file: update config!
        if not args.decrypt:
            update_config(original_config, {"encrypt": False}, journal_name, force_local=True)
            install.save_config(original_config, config_path=CONFIG_PATH)

    elif args.delete_last:
        last_entry = journal.entries.pop()
        util.prompt("[Deleted Entry:]")
        print(last_entry.pprint())
        journal.write()
Example #31
0
import core, races, classes, enemies, moves, util
import random

unlocked = dict(gladiator=False, sage=False, saint=False, joker=False, master=False)

name = input('Name: ').capitalize()
race = util.prompt('Race: ', races.races)
class_ = util.prompt('Class: ', classes.classes)
player = type('Player', (core.Player, race, class_), {})(race, class_, name)
for i in player.moves: print(i.desc())
#p(x.__dict__)
while True:
	enemy_choices, dl = [], 2
	while len(enemy_choices) == 0:
		enemy_choices = [x for x in enemies.enemies if abs(player.level - x.level) < dl]
		dl += 1
	enemy = random.choice(enemy_choices)()
	print('A {} has spotted you!'.format(str(enemy).lower()))
	ps, es = (x*random.random()/4+0.875 for x in (player.stats['speed'], enemy.stats['speed']))
	attacker, attacked = (player, enemy) if ps > es else (enemy, player)
	while True:
		attacker.every_round()
		move = attacker.choose_move()
		attacker.attack(attacked, move)
		if attacked.dead or attacker.dead:
			print()
			break
		attacker, attacked = attacked, attacker
Example #32
0
def assign(var,val):
    assert(val is not None)
    if not isPreDefined(var):
        _assign(var,val)
    else:
        prompt('can not cover predefined functions')