Best Python code snippet using tavern
entombed.py
Source:entombed.py  
...65                for line in option.get_desc().split('\n')[1::]:66                    print(" "*28 + line)67            except:68                pass69    def add_opts(self, s, l, desc, callback=None, takes_argument=False):70        rs = s71        rl = l72        if (takes_argument):73            rs += ":"74            rl += "="75        opt = Option(rs, rl, desc, callback, takes_argument)76        self.options[s] = opt77        self.options[l] = opt78    def set_title(self, title):79        self.usage_title = title80    def getopt(self, args):81        sopts = ''.join((map(lambda x: x.get_short(), self.options.values())))82        lopts = list(map(lambda x: x.get_long(), self.options.values()))83        optlist, args = getopt.getopt(args, sopts, lopts)84        for optname, optval in optlist:85            if (optname[1] != "-"):86                optname = optname[1::]87                opt = self.options[optname]88                result_key = opt.get_long().split('=')[0]89            else:90                optname = optname[2::]91                result_key = optname92            self.results[result_key] = self.options[optname].execute(optval)93        return args94    # Get result of an option set95    def get(self, key, default=None):96        return self.results.get(key, default)97NO_WALL       = 098WALL          = 199RANDOM_CHOICE = 2100# Default row value101rows                    = 25102# Default column value103columns                 = 39104# Do not print rules by default105print_rules_opt         = False106# Print maze by default107no_maze                 = False108# Print a symmetrical maze109no_symmetry             = False110# Do not print probabilities by default111print_probabilities_opt = False112# How much rules to print in one row113rules_blocks            = 8114# Save the maze to print it to a file115saved_maze              = None116# Truecolor117truecolor               = False118# Output file119output                  = None120# Default output background color121output_bg               = 0x3f3f3f122# Default output foreground color123output_fg               = 0x775577124# Default output scale when outputting to image125output_scale            = 10126# Default rules127lut = [128        # Selection algorithm129        #    _ _ _130        #  _|c|d|e|131        # |a|b|X132        #133        # key, bits: edcba134        # edcba135        WALL,          WALL,       WALL,          RANDOM_CHOICE,136        NO_WALL,       NO_WALL,    RANDOM_CHOICE, RANDOM_CHOICE,137        WALL,          WALL,       WALL,          WALL,138        RANDOM_CHOICE, NO_WALL,    NO_WALL,       NO_WALL,139        WALL,          WALL,       WALL,          RANDOM_CHOICE,140        NO_WALL,       NO_WALL,    NO_WALL,       NO_WALL,141        RANDOM_CHOICE, NO_WALL,    WALL,          RANDOM_CHOICE,142        RANDOM_CHOICE, NO_WALL,    NO_WALL,       NO_WALL,143]144def hex_to_truecolor(c, fg=True):145    red   = (c&0xff0000) >> 16146    green = (c&0x00ff00) >> 8147    blue  = (c&0x0000ff) >> 0148    if fg:149        return "\x1b[38;2;{};{};{}m".format(red,green,blue)150    return "\x1b[48;2;{};{};{}m".format(red,green,blue)151def randombit():152    return random.choice([0,1])153def print_row(r, specular=True, truecolors=False, foreground=0x0, background=0x0):154    start_color_fg = ""155    start_color_bg = ""156    reset_color = ""157    if truecolors:158        start_color_fg = hex_to_truecolor(foreground, True)159        start_color_bg = hex_to_truecolor(background, False)160        reset_color = "\x1b[0m"161    wallitem = "{}ââ{}".format(start_color_fg, reset_color)162    nowallitem = "{}  {}".format(start_color_bg, reset_color)163    for item in r:164        if item:165            print(wallitem, end ='')166        else:167            print(nowallitem, end ='')168    # Create specular labyrinth169    if (not specular):170        print()171        return172    for item in r[::-1]:173        if item:174            print(wallitem, end ='')175        else:176            print(nowallitem, end ='')177    print()178def get_idx(a, b, c, d, e):179    return (a << 0) | (b << 1) | (c << 2) | (d << 3) | (e << 4)180def generate_row(r):181    out = [ 0 for _ in range(len(r))]182    for i in range(len(r)):183        if i == 0 or i == 1:184            a = 0185        else:186            a = out[i - 2]187        if i == 0:188            b = 0189        else:190            b = out[i - 1]191        if i == 0:192            c = 0193        else:194            c = r[i-1]195        d = r[i]196        if i == len(r) - 1:197            e = 0198        else:199            e = r[i+1]200        idx = get_idx(a,b,c,d,e)201        #print(a, b, c, d, e, idx)202        out[i] = lut[idx]203        if out[i] == RANDOM_CHOICE:204            out[i] = randombit()205    return out206def lut_to_str(lut):207    outs = ""208    for v in lut:209        outs+="{},".format(v)210    return outs211def lut_from_str(lutstr):212    return list(map(int, lutstr.split(",")))213def print_rules(rules, blocksize=8):214    cline = "â"215    nline = "â"216    nextline=""217    print("âââââ"+"â¬ââââ"*(blocksize-1)+"â")218    for rule_idx in range(len(rules)):219        out = ''220        a = '.'221        if (rule_idx & 1) >> 0:222            a = 'â'223        b = '.'224        if (rule_idx & 2) >> 1:225            b = 'â'226        c = '.'227        if (rule_idx & 4) >> 2:228            c = 'â'229        d = '.'230        if (rule_idx & 8) >> 3:231            d = 'â'232        e = '.'233        if (rule_idx & 16) >> 4:234            e = 'â'235        if rules[rule_idx] == RANDOM_CHOICE:236            out = '?'237        if rules[rule_idx] == NO_WALL:238            out = ' '239        if rules[rule_idx] == WALL:240            out = 'â'241        sep1 = "â"242        if (((rule_idx + 1) % blocksize)!=0):243            sep1 = "â"244        sep2 = "â "245        if (((rule_idx + 1) % blocksize)!=0):246            sep2 = "â"247        cline += (" {}{}{}{}".format(c, d, e, sep1))248        nline += ("{}{}{}{}{} {}".format(a, b, "\x1b[0;35;40m", out,249            "\x1b[0m", sep2))250        if (((rule_idx + 1) % blocksize)==0):251            print(nextline, end ='')252            print(cline)253            cline = "â"254            print(nline)255            nline = "â"256            if (rule_idx < (len(rules) - 1)):257                nextline = "âââââ"+"â¼ââââ"*(blocksize-1)+"â¤\n"258    print("âââââ"+"â´ââââ"*(blocksize-1)+"â")259def probselect(V, cell):260    # Probability to have a 1 in A261    if V:262        return cell263    return 1 - cell264def probabilities(rows, cols, start_row = 0, start_col = 0):265    # Matrix of probabilities266    prob = [ [0, 0]+ [ 0 for c in range(cols) ] + [0,0] for _ in range(rows + 1)]267    for k in range(len(prob[0]) - 2):268        prob[0][k + 2] = .5269    scan = 0 + 2270    for r in range(start_row + 1, rows + 1):271        for c in range(start_col + 2, cols + 2):272            psum = 0273            # Calculate conditioned probabilities274            for A,B,C,D,E in itertools.product([0,1], repeat=5):275                probabilities = [276                    probselect(A, prob[r][c-2]),277                    probselect(B, prob[r][c-1]),278                    probselect(C, prob[r-1][c-1]),279                    probselect(D, prob[r-1][c]),280                    probselect(E, prob[r-1][c+1])281                ]282                p = reduce(lambda x,y: x*y, probabilities)283                idx = (A << 0) | (B << 1) | (C << 2) | (D << 3) | (E << 4)284                if (lut[idx] == RANDOM_CHOICE):285                    psum += (.5 * p)286                else:287                    psum += (lut[idx] * p)288            prob[r][c]=psum289    return prob290# Option parser, argparse like291opt = Options()292opt.set_title("Entombed\nGenerate Mazes with Entombed algorithm")293opt.add_opts("h", "help", "This help",294        callback=lambda _: (opt.usage(),exit(0)))295opt.add_opts("b", "rules-block",296    "How much rules to print on a single line".format(rules_blocks),297    callback = lambda x: int(x),298    takes_argument=True)299opt.add_opts("p", "print-rules", "Print rules in pretty format",300    callback = lambda _: True)301opt.add_opts("B", "output-bg",302    "Output background color, default RGB:#{:06x}\n".format(output_bg) +303    "set to \"random\" to choose a random color",304    callback = lambda x:305        random.randint(0,0xffffff) if (x == "random") else int(x,16),306    takes_argument=True)307opt.add_opts("F", "output-fg",308    "Output foreground color, default RGB:#{:06x}\n".format(output_fg) +309    "set to \"random\" to choose a random color",310    callback = lambda x:311        random.randint(0,0xffffff) if (x == "random") else int(x,16),312    takes_argument=True)313opt.add_opts("P", "print-prob", "Print calculated probability",314    callback = lambda x: True)315opt.add_opts("M", "no-maze", "Do not generate maze",316    callback = lambda x: True)317opt.add_opts("S", "no-symmetry", "Disable maze symmetry",318    callback = lambda x: True)319opt.add_opts("O", "output", "Output to an image",320    takes_argument=True,321    callback = lambda x: x)322opt.add_opts("s", "output-scale", "Output image scale",323    takes_argument=True,324    callback = lambda x: int(x))325opt.add_opts("t", "colors", "Colorize the output using truecolors",326    callback = lambda _: True)327opt.add_opts("c", "columns",328    "Number of columns to generate, default:{}".format(columns),329    callback = lambda x: int(x),330    takes_argument=True)331opt.add_opts("r", "rows",332    "Number of rows to generate, default: {}".format(rows),333    callback = lambda x: int(x),334    takes_argument=True)335opt.add_opts("R", "rules",336    "Load different rules for the maze generation\n" +337    "The rules should be an array of 32 items:\n"    +338    "{} -> No wall\n".format(NO_WALL)                +339    "{} -> Wall\n".format(WALL)                     +340    "{} -> Random value\n".format(RANDOM_CHOICE)      +341    "    âââââ¬ââââ¬ââââ\n"                            +342    "    â c â d â e â\n"                            +343    "âââââ¼ââââ¼ââââ¼ââââ\n"                            +344    "â a â b â V â    \n"                            +345    "âââââ´ââââ´ââââ    \n"                            +346    "with V as the resultant value\n"                +347    "          edcba bits      ecdba           ecdba           ecdba\n"+348    "value_for_00000,value_for_00001,value_for_00010,value_for_00011,...\n"+349    "default value is {}".format(lut_to_str(lut)),...zato_command.py
Source:zato_command.py  
...18     create_web_admin as create_web_admin_mod, crypto as crypto_mod, delete_odb as delete_odb_mod, \19     enmasse as enmasse_mod, FromConfig, info as info_mod, migrate as migrate_mod, quickstart as quickstart_mod, run_command, \20     service as service_mod, start as start_mod, stop as stop_mod, web_admin_auth as web_admin_auth_mod21from zato.common import version22def add_opts(parser, opts):23    """ Adds parser-specific options.24    """25    for opt in opts:26        arguments = {}27        for name in('help', 'action', 'default'):28            try:29                arguments[name] = opt[name]30            except KeyError:31                # Almost no command uses 'action' or 'default' parameters32                pass33        parser.add_argument(opt['name'], **arguments)34def get_parser():35    base_parser = argparse.ArgumentParser(add_help=False)36    base_parser.add_argument('--store-log', help='Whether to store an execution log', action='store_true')37    base_parser.add_argument('--verbose', help='Show verbose output', action='store_true')38    base_parser.add_argument(39        '--store-config',40        help='Whether to store config options in a file for a later use', action='store_true')41    parser = argparse.ArgumentParser(prog='zato')42    parser.add_argument('--version', action='version', version=version)43    subs = parser.add_subparsers()44    #45    # ca46    #47    ca = subs.add_parser('ca', description='Basic certificate authority (CA) management')48    ca_subs = ca.add_subparsers()49    ca_create = ca_subs.add_parser('create', description='Creates crypto material for Zato components')50    ca_create_subs = ca_create.add_subparsers()51    ca_create_ca = ca_create_subs.add_parser('ca', description=ca_create_ca_mod.Create.__doc__, parents=[base_parser])52    ca_create_ca.set_defaults(command='ca_create_ca')53    ca_create_ca.add_argument('path', help='Path to an empty directory to hold the CA')54    add_opts(ca_create_ca, ca_create_ca_mod.Create.opts)55    ca_create_lb_agent = ca_create_subs.add_parser('lb_agent', description=ca_create_lb_agent_mod.Create.__doc__, parents=[base_parser])56    ca_create_lb_agent.set_defaults(command='ca_create_lb_agent')57    ca_create_lb_agent.add_argument('path', help='Path to a CA directory')58    add_opts(ca_create_lb_agent, ca_create_lb_agent_mod.Create.opts)59    ca_create_server = ca_create_subs.add_parser('server', description=ca_create_server_mod.Create.__doc__, parents=[base_parser])60    ca_create_server.set_defaults(command='ca_create_server')61    ca_create_server.add_argument('path', help='Path to a CA directory')62    add_opts(ca_create_server, ca_create_server_mod.Create.opts)63    ca_create_web_admin = ca_create_subs.add_parser('web_admin', description=ca_create_web_admin_mod.Create.__doc__, parents=[base_parser])64    ca_create_web_admin.set_defaults(command='ca_create_web_admin')65    ca_create_web_admin.add_argument('path', help='Path to a CA directory')66    add_opts(ca_create_web_admin, ca_create_web_admin_mod.Create.opts)67    #68    # check-config69    #70    check_config = subs.add_parser(71        'check-config',72        description='Checks config of a Zato component (currently limited to servers only)',73        parents=[base_parser])74    check_config.set_defaults(command='check_config')75    check_config.add_argument('path', help='Path to a Zato component')76    add_opts(check_config, check_config_mod.CheckConfig.opts)77    #78    # component-version79    #80    component_version = subs.add_parser(81        'component-version',82        description='Shows the version of a Zato component installed in a given directory',83        parents=[base_parser])84    component_version.set_defaults(command='component_version')85    component_version.add_argument('path', help='Path to a Zato component')86    add_opts(component_version, component_version_mod.ComponentVersion.opts)87    #88    # create89    #90    create = subs.add_parser('create', description='Creates new Zato components')91    create_subs = create.add_subparsers()92    create_cluster = create_subs.add_parser('cluster', description=create_cluster_mod.Create.__doc__, parents=[base_parser])93    create_cluster.set_defaults(command='create_cluster')94    add_opts(create_cluster, create_cluster_mod.Create.opts)95    create_lb = create_subs.add_parser('load_balancer', description=create_lb_mod.Create.__doc__, parents=[base_parser])96    create_lb.add_argument('path', help='Path to an empty directory to install the load-balancer in')97    create_lb.set_defaults(command='create_lb')98    add_opts(create_lb, create_lb_mod.Create.opts)99    create_odb = create_subs.add_parser('odb', description=create_odb_mod.Create.__doc__, parents=[base_parser])100    create_odb.set_defaults(command='create_odb')101    add_opts(create_odb, create_odb_mod.Create.opts)102    create_server = create_subs.add_parser('server', description=create_server_mod.Create.__doc__, parents=[base_parser])103    create_server.add_argument('path', help='Path to an empty directory to install the server in')104    create_server.set_defaults(command='create_server')105    add_opts(create_server, create_server_mod.Create.opts)106    create_user = create_subs.add_parser('user', description=web_admin_auth_mod.CreateUser.__doc__, parents=[base_parser])107    create_user.add_argument('path', help='Path to a web admin')108    create_user.set_defaults(command='create_user')109    add_opts(create_user, web_admin_auth_mod.CreateUser.opts)110    create_web_admin = create_subs.add_parser('web_admin', description=create_web_admin_mod.Create.__doc__, parents=[base_parser])111    create_web_admin.add_argument('path', help='Path to an empty directory to install a new web admin in')112    create_web_admin.set_defaults(command='create_web_admin')113    add_opts(create_web_admin, create_web_admin_mod.Create.opts)114    #115    # decrypt116    #117    decrypt = subs.add_parser('decrypt', description=crypto_mod.Decrypt.__doc__, parents=[base_parser])118    decrypt.add_argument('path', help='Path to the private key in PEM')119    decrypt.set_defaults(command='decrypt')120    add_opts(decrypt, crypto_mod.Decrypt.opts)121    #122    # delete123    #124    delete = subs.add_parser('delete', description=delete_odb_mod.Delete.__doc__)125    delete_subs = delete.add_subparsers()126    delete_odb = delete_subs.add_parser('odb', description='Deletes a Zato ODB', parents=[base_parser])127    delete_odb.set_defaults(command='delete_odb')128    add_opts(delete_odb, delete_odb_mod.Delete.opts)129    #130    # encrypt131    #132    encrypt = subs.add_parser('encrypt', description=crypto_mod.Encrypt.__doc__, parents=[base_parser])133    encrypt.add_argument('path', help='Path to the public key in PEM')134    encrypt.set_defaults(command='encrypt')135    add_opts(encrypt, crypto_mod.Encrypt.opts)136    #137    # enmasse138    #139    enmasse = subs.add_parser('enmasse', description=enmasse_mod.EnMasse.__doc__, parents=[base_parser])140    enmasse.add_argument('path', help='Path to a running Zato server')141    enmasse.set_defaults(command='enmasse')142    add_opts(enmasse, enmasse_mod.EnMasse.opts)143    #144    # info145    #146    info = subs.add_parser('info', description=info_mod.Info.__doc__, parents=[base_parser])147    info.add_argument('path', help='Path to a Zato component')148    info.set_defaults(command='info')149    add_opts(info, info_mod.Info.opts)150    #151    # from-config-file152    #153    from_config = subs.add_parser('from-config', description=FromConfig.__doc__, parents=[base_parser])154    from_config.add_argument('path', help='Path to a Zato command config file')155    from_config.set_defaults(command='from_config')156    #157    # migrate158    #159    migrate = subs.add_parser('migrate', description=migrate_mod.Migrate.__doc__, parents=[base_parser])160    migrate.add_argument('path', help='Path to a Zato component')161    migrate.set_defaults(command='migrate')162    add_opts(migrate, migrate_mod.Migrate.opts)163    #164    # quickstart165    #166    quickstart = subs.add_parser('quickstart', description='Quickly set up and manage Zato clusters', parents=[base_parser])167    quickstart_subs = quickstart.add_subparsers()168    quickstart_create = quickstart_subs.add_parser('create', description=quickstart_mod.Create.__doc__, parents=[base_parser])169    quickstart_create.add_argument('path', help='Path to an empty directory for the quickstart cluster')170    quickstart_create.set_defaults(command='quickstart_create')171    add_opts(quickstart_create, quickstart_mod.Create.opts)172    #173    # service174    #175    service = subs.add_parser('service', description='Commands related to the management of Zato services')176    service_subs = service.add_subparsers()177    service_invoke = service_subs.add_parser('invoke', description=service_mod.Invoke.__doc__, parents=[base_parser])178    service_invoke.set_defaults(command='service_invoke')179    add_opts(service_invoke, service_mod.Invoke.opts)180    #181    # start182    #183    start = subs.add_parser('start', description=start_mod.Start.__doc__, parents=[base_parser], formatter_class=argparse.RawDescriptionHelpFormatter)184    start.add_argument('path', help='Path to the Zato component to be started')185    start.set_defaults(command='start')186    add_opts(start, start_mod.Start.opts)187    #188    # stop189    #190    stop = subs.add_parser('stop', description=stop_mod.Stop.__doc__, parents=[base_parser])191    stop.add_argument('path', help='Path to the Zato component to be stopped')192    stop.set_defaults(command='stop')193    #194    # update195    #196    update = subs.add_parser('update', description='Updates Zato components and users')197    update_subs = update.add_subparsers()198    # .. update crypto199    update_crypto = update_subs.add_parser('crypto', description=crypto_mod.UpdateCrypto.__doc__, parents=[base_parser])200    update_crypto.add_argument('path', help='Path to a Zato component')201    update_crypto.set_defaults(command='update_crypto')202    add_opts(update_crypto, crypto_mod.UpdateCrypto.opts)203    # .. update password204    update_password = update_subs.add_parser('password', description=web_admin_auth_mod.UpdatePassword.__doc__, parents=[base_parser])205    update_password.add_argument('path', help='Path to a web admin directory')206    update_password.set_defaults(command='update_password')207    add_opts(update_password, web_admin_auth_mod.UpdatePassword.opts)208    # .. update password209    update_open_id = update_subs.add_parser('openid', description=web_admin_auth_mod.UpdateOpenID.__doc__, parents=[base_parser])210    update_open_id.add_argument('path', help='Path to a web admin directory')211    update_open_id.set_defaults(command='update_openid')212    add_opts(update_open_id, web_admin_auth_mod.UpdateOpenID.opts)213    return parser214def main():...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
