Best Python code snippet using avocado_python
shell.py
Source:shell.py  
...87    if config.get('local_address', '') in [b'0.0.0.0']:88        logging.warning('warning: local set to listen on 0.0.0.0, it\'s not safe')89    if config.get('server', '') in ['127.0.0.1', 'localhost']:90        logging.warning('warning: server set to listen on %s:%s, are you sure?' %91                     (to_str(config['server']), config['server_port']))92    if config.get('timeout', 300) < 100:93        logging.warning('warning: your timeout %d seems too short' %94                     int(config.get('timeout')))95    if config.get('timeout', 300) > 600:96        logging.warning('warning: your timeout %d seems too long' %97                     int(config.get('timeout')))98    if config.get('password') in [b'mypassword']:99        logging.error('DON\'T USE DEFAULT PASSWORD! Please change it in your '100                      'config.json!')101        sys.exit(1)102    if config.get('user', None) is not None:103        if os.name != 'posix':104            logging.error('user can be used only on Unix')105            sys.exit(1)106    encrypt.try_cipher(config['password'], config['method'])107def get_config(is_local):108    global verbose109    config = {}110    config_path = None111    logging.basicConfig(level=logging.INFO,112                        format='%(levelname)-s: %(message)s')113    if is_local:114        shortopts = 'hd:s:b:p:k:l:m:O:o:G:g:c:t:vq'115        longopts = ['help', 'fast-open', 'pid-file=', 'log-file=', 'user=',116                    'version']117    else:118        shortopts = 'hd:s:p:k:m:O:o:G:g:c:t:vq'119        longopts = ['help', 'fast-open', 'pid-file=', 'log-file=', 'workers=',120                    'forbidden-ip=', 'user=', 'manager-address=', 'version']121    try:122        optlist, args = getopt.getopt(sys.argv[1:], shortopts, longopts)123        for key, value in optlist:124            if key == '-c':125                config_path = value126            elif key in ('-h', '--help'):127                print_help(is_local)128                sys.exit(0)129            elif key == '--version':130                print_shadowsocks()131                sys.exit(0)132            else:133                continue134        if config_path is None:135            config_path = find_config()136        if config_path:137            logging.debug('loading config from %s' % config_path)138            with open(config_path, 'rb') as f:139                try:140                    config = parse_json_in_str(remove_comment(f.read().decode('utf8')))141                except ValueError as e:142                    logging.error('found an error in config.json: %s', str(e))143                    sys.exit(1)144        v_count = 0145        for key, value in optlist:146            if key == '-p':147                config['server_port'] = int(value)148            elif key == '-k':149                config['password'] = to_bytes(value)150            elif key == '-l':151                config['local_port'] = int(value)152            elif key == '-s':153                config['server'] = to_str(value)154            elif key == '-m':155                config['method'] = to_str(value)156            elif key == '-O':157                config['protocol'] = to_str(value)158            elif key == '-o':159                config['obfs'] = to_str(value)160            elif key == '-G':161                config['protocol_param'] = to_str(value)162            elif key == '-g':163                config['obfs_param'] = to_str(value)164            elif key == '-b':165                config['local_address'] = to_str(value)166            elif key == '-v':167                v_count += 1168                # '-vv' turns on more verbose mode169                config['verbose'] = v_count170            elif key == '-t':171                config['timeout'] = int(value)172            elif key == '--fast-open':173                config['fast_open'] = True174            elif key == '--workers':175                config['workers'] = int(value)176            elif key == '--manager-address':177                config['manager_address'] = value178            elif key == '--user':179                config['user'] = to_str(value)180            elif key == '--forbidden-ip':181                config['forbidden_ip'] = to_str(value)182            elif key == '-d':183                config['daemon'] = to_str(value)184            elif key == '--pid-file':185                config['pid-file'] = to_str(value)186            elif key == '--log-file':187                config['log-file'] = to_str(value)188            elif key == '-q':189                v_count -= 1190                config['verbose'] = v_count191            else:192                continue193    except getopt.GetoptError as e:194        print(e, file=sys.stderr)195        print_help(is_local)196        sys.exit(2)197    if not config:198        logging.error('config not specified')199        print_help(is_local)200        sys.exit(2)201    config['password'] = to_bytes(config.get('password', b''))202    config['method'] = to_str(config.get('method', 'aes-256-cfb'))203    config['protocol'] = to_str(config.get('protocol', 'origin'))204    config['protocol_param'] = to_str(config.get('protocol_param', ''))205    config['obfs'] = to_str(config.get('obfs', 'plain'))206    config['obfs_param'] = to_str(config.get('obfs_param', ''))207    config['port_password'] = config.get('port_password', None)208    config['additional_ports'] = config.get('additional_ports', {})209    config['additional_ports_only'] = config.get('additional_ports_only', False)210    config['timeout'] = int(config.get('timeout', 300))211    config['udp_timeout'] = int(config.get('udp_timeout', 120))212    config['udp_cache'] = int(config.get('udp_cache', 64))213    config['fast_open'] = config.get('fast_open', False)214    config['workers'] = config.get('workers', 1)215    config['pid-file'] = config.get('pid-file', '/var/run/shadowsocksr.pid')216    config['log-file'] = config.get('log-file', '/var/log/shadowsocksr.log')217    config['verbose'] = config.get('verbose', False)218    config['connect_verbose_info'] = config.get('connect_verbose_info', 0)219    config['local_address'] = to_str(config.get('local_address', '127.0.0.1'))220    config['local_port'] = config.get('local_port', 1080)221    if is_local:222        if config.get('server', None) is None:223            logging.error('server addr not specified')224            print_local_help()225            sys.exit(2)226        else:227            config['server'] = to_str(config['server'])228    else:229        config['server'] = to_str(config.get('server', '0.0.0.0'))230        try:231            config['forbidden_ip'] = \232                IPNetwork(config.get('forbidden_ip', '127.0.0.0/8,::1/128'))233        except Exception as e:234            logging.error(e)235            sys.exit(2)236        try:237            config['forbidden_port'] = PortRange(config.get('forbidden_port', ''))238        except Exception as e:239            logging.error(e)240            sys.exit(2)241        try:242            config['ignore_bind'] = \243                IPNetwork(config.get('ignore_bind', '127.0.0.0/8,::1/128,10.0.0.0/8,192.168.0.0/16'))244        except Exception as e:245            logging.error(e)246            sys.exit(2)247    config['server_port'] = config.get('server_port', 8388)248    logging.getLogger('').handlers = []249    logging.addLevelName(VERBOSE_LEVEL, 'VERBOSE')250    if config['verbose'] >= 2:251        level = VERBOSE_LEVEL252    elif config['verbose'] == 1:253        level = logging.DEBUG254    elif config['verbose'] == -1:255        level = logging.WARN256    elif config['verbose'] <= -2:257        level = logging.ERROR258    else:259        level = logging.INFO260    verbose = config['verbose']261    logging.basicConfig(level=level,262                        format='%(asctime)s %(levelname)-8s %(filename)s:%(lineno)s %(message)s',263                        datefmt='%Y-%m-%d %H:%M:%S')264    check_config(config, is_local)265    return config266def print_help(is_local):267    if is_local:268        print_local_help()269    else:270        print_server_help()271def print_local_help():272    print('''usage: sslocal [OPTION]...273A fast tunnel proxy that helps you bypass firewalls.274You can supply configurations via either config file or command line arguments.275Proxy options:276  -c CONFIG              path to config file277  -s SERVER_ADDR         server address278  -p SERVER_PORT         server port, default: 8388279  -b LOCAL_ADDR          local binding address, default: 127.0.0.1280  -l LOCAL_PORT          local port, default: 1080281  -k PASSWORD            password282  -m METHOD              encryption method, default: aes-256-cfb283  -o OBFS                obfsplugin, default: http_simple284  -t TIMEOUT             timeout in seconds, default: 300285  --fast-open            use TCP_FASTOPEN, requires Linux 3.7+286General options:287  -h, --help             show this help message and exit288  -d start/stop/restart  daemon mode289  --pid-file PID_FILE    pid file for daemon mode290  --log-file LOG_FILE    log file for daemon mode291  --user USER            username to run as292  -v, -vv                verbose mode293  -q, -qq                quiet mode, only show warnings/errors294  --version              show version information295Online help: <https://github.com/shadowsocks/shadowsocks>296''')297def print_server_help():298    print('''usage: ssserver [OPTION]...299A fast tunnel proxy that helps you bypass firewalls.300You can supply configurations via either config file or command line arguments.301Proxy options:302  -c CONFIG              path to config file303  -s SERVER_ADDR         server address, default: 0.0.0.0304  -p SERVER_PORT         server port, default: 8388305  -k PASSWORD            password306  -m METHOD              encryption method, default: aes-256-cfb307  -o OBFS                obfsplugin, default: http_simple308  -t TIMEOUT             timeout in seconds, default: 300309  --fast-open            use TCP_FASTOPEN, requires Linux 3.7+310  --workers WORKERS      number of workers, available on Unix/Linux311  --forbidden-ip IPLIST  comma seperated IP list forbidden to connect312  --manager-address ADDR optional server manager UDP address, see wiki313General options:314  -h, --help             show this help message and exit315  -d start/stop/restart  daemon mode316  --pid-file PID_FILE    pid file for daemon mode317  --log-file LOG_FILE    log file for daemon mode318  --user USER            username to run as319  -v, -vv                verbose mode320  -q, -qq                quiet mode, only show warnings/errors321  --version              show version information322Online help: <https://github.com/shadowsocks/shadowsocks>323''')324def _decode_list(data):325    rv = []326    for item in data:327        if hasattr(item, 'encode'):328            item = item.encode('utf-8')329        elif isinstance(item, list):330            item = _decode_list(item)331        elif isinstance(item, dict):332            item = _decode_dict(item)333        rv.append(item)334    return rv335def _decode_dict(data):336    rv = {}337    for key, value in data.items():338        if hasattr(value, 'encode'):339            value = value.encode('utf-8')340        elif isinstance(value, list):341            value = _decode_list(value)342        elif isinstance(value, dict):343            value = _decode_dict(value)344        rv[key] = value345    return rv346class JSFormat:347    def __init__(self):348        self.state = 0349    def push(self, ch):350        ch = ord(ch)351        if self.state == 0:352            if ch == ord('"'):353                self.state = 1354                return to_str(chr(ch))355            elif ch == ord('/'):356                self.state = 3357            else:358                return to_str(chr(ch))359        elif self.state == 1:360            if ch == ord('"'):361                self.state = 0362                return to_str(chr(ch))363            elif ch == ord('\\'):364                self.state = 2365            return to_str(chr(ch))366        elif self.state == 2:367            self.state = 1368            if ch == ord('"'):369                return to_str(chr(ch))370            return "\\" + to_str(chr(ch))371        elif self.state == 3:372            if ch == ord('/'):373                self.state = 4374            else:375                return "/" + to_str(chr(ch))376        elif self.state == 4:377            if ch == ord('\n'):378                self.state = 0379                return "\n"380        return ""381def remove_comment(json):382    fmt = JSFormat()383    return "".join([fmt.push(c) for c in json])384def parse_json_in_str(data):385    # parse json and convert everything from unicode to str...high_score.py
Source:high_score.py  
1__author__ = 'cmotevasselani'2class HighScore:3  def __init__(self, name, score, player_class, player_race, date, turns, level, dungeon_level, message):4    self.name = name5    self.score = score6    self.player_class = player_class7    self.player_race = player_race8    self.date = date9    self.turns = turns10    self.level = level11    self.dungeon_level = dungeon_level12    self.message = message13  def to_quick_str(self):14    to_str = ""15    to_str += "Score: " + str(self.score) + ", "16    to_str += "Name: " + str(self.name) + ", "17    to_str += "Class: " + str(self.player_class) + ", "18    to_str += "Race: " + str(self.player_race) + " "19    return to_str20  def __str__(self):21    to_str = "\n"22    to_str += "Score: " + str(self.score) + " \n\n"23    to_str += "Name: " + str(self.name) + " \n\n"24    to_str += "Class: " + str(self.player_class) + " \n\n"25    to_str += "Race: " + str(self.player_race) + " \n\n"26    to_str += "Date: " + str(self.date) + " \n\n"27    to_str += "Turns: " + str(self.turns) + " \n\n"28    to_str += "Level: " + str(self.level) + " \n\n"29    to_str += "Dungeon Level: " + str(self.dungeon_level) + " \n\n"30    to_str += "Message: " + str(self.message) + " \n\n"...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!!
