idx int64 0 63k | question stringlengths 61 4.03k | target stringlengths 6 1.23k |
|---|---|---|
24,700 | def issuperset ( self , other ) : other = self . _cast_to_frameset ( other ) if other is NotImplemented : return NotImplemented return self . items >= other . items | Check if the contents of self is a superset of the contents of other . |
24,701 | def _maxSizeCheck ( cls , obj ) : fail = False size = 0 if isinstance ( obj , numbers . Number ) : if obj > constants . MAX_FRAME_SIZE : fail = True size = obj elif hasattr ( obj , '__len__' ) : size = len ( obj ) fail = size > constants . MAX_FRAME_SIZE if fail : raise MaxSizeException ( 'Frame size %s > %s (MAX_FRAME_SIZE)' % ( size , constants . MAX_FRAME_SIZE ) ) | Raise a MaxSizeException if obj exceeds MAX_FRAME_SIZE |
24,702 | def padFrameRange ( frange , zfill ) : def _do_pad ( match ) : result = list ( match . groups ( ) ) result [ 1 ] = pad ( result [ 1 ] , zfill ) if result [ 4 ] : result [ 4 ] = pad ( result [ 4 ] , zfill ) return '' . join ( ( i for i in result if i ) ) return PAD_RE . sub ( _do_pad , frange ) | Return the zero - padded version of the frame range string . |
24,703 | def framesToFrameRanges ( frames , zfill = 0 ) : _build = FrameSet . _build_frange_part curr_start = None curr_stride = None curr_frame = None last_frame = None curr_count = 0 for curr_frame in frames : if curr_start is None : curr_start = curr_frame last_frame = curr_frame curr_count += 1 continue if curr_stride is None : curr_stride = abs ( curr_frame - curr_start ) new_stride = abs ( curr_frame - last_frame ) if curr_stride == new_stride : last_frame = curr_frame curr_count += 1 elif curr_count == 2 and curr_stride != 1 : yield _build ( curr_start , curr_start , None , zfill ) curr_start = last_frame curr_stride = new_stride last_frame = curr_frame else : yield _build ( curr_start , last_frame , curr_stride , zfill ) curr_stride = None curr_start = curr_frame last_frame = curr_frame curr_count = 1 if curr_count == 2 and curr_stride != 1 : yield _build ( curr_start , curr_start , None , zfill ) yield _build ( curr_frame , curr_frame , None , zfill ) else : yield _build ( curr_start , curr_frame , curr_stride , zfill ) | Converts a sequence of frames to a series of padded frame range strings . |
24,704 | def framesToFrameRange ( frames , sort = True , zfill = 0 , compress = False ) : if compress : frames = unique ( set ( ) , frames ) frames = list ( frames ) if not frames : return '' if len ( frames ) == 1 : return pad ( frames [ 0 ] , zfill ) if sort : frames . sort ( ) return ',' . join ( FrameSet . framesToFrameRanges ( frames , zfill ) ) | Converts an iterator of frames into a frame range string . |
24,705 | def _parse_optional_params ( self , oauth_params , req_kwargs ) : params = req_kwargs . get ( 'params' , { } ) data = req_kwargs . get ( 'data' ) or { } for oauth_param in OPTIONAL_OAUTH_PARAMS : if oauth_param in params : oauth_params [ oauth_param ] = params . pop ( oauth_param ) if oauth_param in data : oauth_params [ oauth_param ] = data . pop ( oauth_param ) if params : req_kwargs [ 'params' ] = params if data : req_kwargs [ 'data' ] = data | Parses and sets optional OAuth parameters on a request . |
24,706 | def _get_oauth_params ( self , req_kwargs ) : oauth_params = { } oauth_params [ 'oauth_consumer_key' ] = self . consumer_key oauth_params [ 'oauth_nonce' ] = sha1 ( str ( random ( ) ) . encode ( 'ascii' ) ) . hexdigest ( ) oauth_params [ 'oauth_signature_method' ] = self . signature . NAME oauth_params [ 'oauth_timestamp' ] = int ( time ( ) ) if self . access_token is not None : oauth_params [ 'oauth_token' ] = self . access_token oauth_params [ 'oauth_version' ] = self . VERSION self . _parse_optional_params ( oauth_params , req_kwargs ) return oauth_params | Prepares OAuth params for signing . |
24,707 | def sign ( url , app_id , app_secret , hash_meth = 'sha1' , ** params ) : hash_meth_str = hash_meth if hash_meth == 'sha1' : hash_meth = sha1 elif hash_meth == 'md5' : hash_meth = md5 else : raise TypeError ( 'hash_meth must be one of "sha1", "md5"' ) now = datetime . utcnow ( ) milliseconds = now . microsecond // 1000 time_format = '%Y-%m-%dT%H:%M:%S.{0}Z' . format ( milliseconds ) ofly_params = { 'oflyAppId' : app_id , 'oflyHashMeth' : hash_meth_str . upper ( ) , 'oflyTimestamp' : now . strftime ( time_format ) } url_path = urlsplit ( url ) . path signature_base_string = app_secret + url_path + '?' if len ( params ) : signature_base_string += get_sorted_params ( params ) + '&' signature_base_string += get_sorted_params ( ofly_params ) if not isinstance ( signature_base_string , bytes ) : signature_base_string = signature_base_string . encode ( 'utf-8' ) ofly_params [ 'oflyApiSig' ] = hash_meth ( signature_base_string ) . hexdigest ( ) all_params = dict ( tuple ( ofly_params . items ( ) ) + tuple ( params . items ( ) ) ) return get_sorted_params ( all_params ) | A signature method which generates the necessary Ofly parameters . |
24,708 | def _get_auth_header ( self ) : realm = 'realm="{realm}"' . format ( realm = self . realm ) params = [ '{k}="{v}"' . format ( k = k , v = quote ( str ( v ) , safe = '' ) ) for k , v in self . oauth_params . items ( ) ] return 'OAuth ' + ',' . join ( [ realm ] + params ) | Constructs and returns an authentication header . |
24,709 | def _remove_qs ( self , url ) : scheme , netloc , path , query , fragment = urlsplit ( url ) return urlunsplit ( ( scheme , netloc , path , '' , fragment ) ) | Removes a query string from a URL before signing . |
24,710 | def _normalize_request_parameters ( self , oauth_params , req_kwargs ) : normalized = [ ] params = req_kwargs . get ( 'params' , { } ) data = req_kwargs . get ( 'data' , { } ) headers = req_kwargs . get ( 'headers' , { } ) for k , v in params . items ( ) : if v is not None : normalized += [ ( k , v ) ] if 'Content-Type' in headers and headers [ 'Content-Type' ] == FORM_URLENCODED : for k , v in data . items ( ) : normalized += [ ( k , v ) ] all_normalized = [ ] for t in normalized : k , v = t if is_basestring ( v ) and not isinstance ( v , bytes ) : v = v . encode ( 'utf-8' ) all_normalized += [ ( k , v ) ] for k , v in oauth_params . items ( ) : if ( k , v ) in all_normalized : continue all_normalized += [ ( k , v ) ] all_normalized . sort ( ) return urlencode ( all_normalized , True ) . replace ( '+' , '%20' ) . replace ( '%7E' , '~' ) | This process normalizes the request parameters as detailed in the OAuth 1 . 0 spec . |
24,711 | def sign ( self , consumer_secret , access_token_secret , method , url , oauth_params , req_kwargs ) : key = self . _escape ( consumer_secret ) + b'&' if access_token_secret : key += self . _escape ( access_token_secret ) return key . decode ( ) | Sign request using PLAINTEXT method . |
24,712 | def get_request_token ( self , method = 'GET' , decoder = parse_utf8_qsl , key_token = 'oauth_token' , key_token_secret = 'oauth_token_secret' , ** kwargs ) : r = self . get_raw_request_token ( method = method , ** kwargs ) request_token , request_token_secret = process_token_request ( r , decoder , key_token , key_token_secret ) return request_token , request_token_secret | Return a request token pair . |
24,713 | def get_access_token ( self , request_token , request_token_secret , method = 'GET' , decoder = parse_utf8_qsl , key_token = 'oauth_token' , key_token_secret = 'oauth_token_secret' , ** kwargs ) : r = self . get_raw_access_token ( request_token , request_token_secret , method = method , ** kwargs ) access_token , access_token_secret = process_token_request ( r , decoder , key_token , key_token_secret ) return access_token , access_token_secret | Returns an access token pair . |
24,714 | def get_access_token ( self , method = 'POST' , decoder = parse_utf8_qsl , key = 'access_token' , ** kwargs ) : r = self . get_raw_access_token ( method , ** kwargs ) access_token , = process_token_request ( r , decoder , key ) return access_token | Returns an access token . |
24,715 | def is_logged_in ( username = None ) : if username : if not isinstance ( username , ( list , tuple ) ) : username = [ username ] return 'simple_logged_in' in session and get_username ( ) in username return 'simple_logged_in' in session | Checks if user is logged in if username is passed check if specified user is logged in username can be a list |
24,716 | def login_required ( function = None , username = None , basic = False , must = None ) : if function and not callable ( function ) : raise ValueError ( 'Decorator receives only named arguments, ' 'try login_required(username="foo")' ) def check ( validators ) : if validators is None : return if not isinstance ( validators , ( list , tuple ) ) : validators = [ validators ] for validator in validators : error = validator ( get_username ( ) ) if error is not None : return SimpleLogin . get_message ( 'auth_error' , error ) , 403 def dispatch ( fun , * args , ** kwargs ) : if basic and request . is_json : return dispatch_basic_auth ( fun , * args , ** kwargs ) if is_logged_in ( username = username ) : return check ( must ) or fun ( * args , ** kwargs ) elif is_logged_in ( ) : return SimpleLogin . get_message ( 'access_denied' ) , 403 else : flash ( SimpleLogin . get_message ( 'login_required' ) , 'warning' ) return redirect ( url_for ( 'simplelogin.login' , next = request . path ) ) def dispatch_basic_auth ( fun , * args , ** kwargs ) : simplelogin = current_app . extensions [ 'simplelogin' ] auth_response = simplelogin . basic_auth ( ) if auth_response is True : return check ( must ) or fun ( * args , ** kwargs ) else : return auth_response if function : @ wraps ( function ) def simple_decorator ( * args , ** kwargs ) : return dispatch ( function , * args , ** kwargs ) return simple_decorator def decorator ( f ) : @ wraps ( f ) def wrap ( * args , ** kwargs ) : return dispatch ( f , * args , ** kwargs ) return wrap return decorator | Decorate views to require login |
24,717 | def get_message ( message , * args , ** kwargs ) : msg = current_app . extensions [ 'simplelogin' ] . messages . get ( message ) if msg and ( args or kwargs ) : return msg . format ( * args , ** kwargs ) return msg | Helper to get internal messages outside this instance |
24,718 | def check_my_users ( user ) : user_data = my_users . get ( user [ 'username' ] ) if not user_data : return False elif user_data . get ( 'password' ) == user [ 'password' ] : return True return False | Check if user exists and its credentials . Take a look at encrypt_app . py and encrypt_cli . py to see how to encrypt passwords |
24,719 | def create_user ( ** data ) : if 'username' not in data or 'password' not in data : raise ValueError ( 'username and password are required.' ) data [ 'password' ] = generate_password_hash ( data . pop ( 'password' ) , method = 'pbkdf2:sha256' ) db_users = json . load ( open ( 'users.json' ) ) db_users [ data [ 'username' ] ] = data json . dump ( db_users , open ( 'users.json' , 'w' ) ) return data | Creates user with encrypted password |
24,720 | def with_app ( f ) : @ wraps ( f ) def decorator ( * args , ** kwargs ) : app = create_app ( ) configure_extensions ( app ) configure_views ( app ) return f ( app = app , * args , ** kwargs ) return decorator | Calls function passing app as first argument |
24,721 | def adduser ( app , username , password ) : with app . app_context ( ) : create_user ( username = username , password = password ) click . echo ( 'user created!' ) | Add new user with admin access |
24,722 | def _pulse_data ( self , value ) : if self . _i2c_expander == 'PCF8574' : self . bus . write_byte ( self . _address , ( ( value & ~ PCF8574_E ) | self . _backlight ) ) c . usleep ( 1 ) self . bus . write_byte ( self . _address , value | PCF8574_E | self . _backlight ) c . usleep ( 1 ) self . bus . write_byte ( self . _address , ( ( value & ~ PCF8574_E ) | self . _backlight ) ) c . usleep ( 100 ) elif self . _i2c_expander in [ 'MCP23008' , 'MCP23017' ] : self . _mcp_data &= ~ MCP230XX_DATAMASK self . _mcp_data |= value << MCP230XX_DATASHIFT self . _mcp_data &= ~ MCP230XX_E self . bus . write_byte_data ( self . _address , self . _mcp_gpio , self . _mcp_data ) c . usleep ( 1 ) self . _mcp_data |= MCP230XX_E self . bus . write_byte_data ( self . _address , self . _mcp_gpio , self . _mcp_data ) c . usleep ( 1 ) self . _mcp_data &= ~ MCP230XX_E self . bus . write_byte_data ( self . _address , self . _mcp_gpio , self . _mcp_data ) c . usleep ( 100 ) | Pulse the enable flag to process value . |
24,723 | def _write4bits ( self , value ) : for i in range ( 4 ) : bit = ( value >> i ) & 0x01 GPIO . output ( self . pins [ i + 7 ] , bit ) self . _pulse_enable ( ) | Write 4 bits of data into the data bus . |
24,724 | def _pulse_enable ( self ) : GPIO . output ( self . pins . e , 0 ) c . usleep ( 1 ) GPIO . output ( self . pins . e , 1 ) c . usleep ( 1 ) GPIO . output ( self . pins . e , 0 ) c . usleep ( 100 ) | Pulse the enable flag to process data . |
24,725 | def write_string ( self , value ) : encoded = self . codec . encode ( value ) ignored = False for [ char , lookahead ] in c . sliding_window ( encoded , lookahead = 1 ) : if ignored is True : ignored = False continue if char not in [ codecs . CR , codecs . LF ] : self . write ( char ) continue if self . recent_auto_linebreak is True : crlf = ( char == codecs . CR and lookahead == codecs . LF ) lfcr = ( char == codecs . LF and lookahead == codecs . CR ) if crlf or lfcr : ignored = True continue row , col = self . cursor_pos if char == codecs . LF : if row < self . lcd . rows - 1 : self . cursor_pos = ( row + 1 , col ) else : self . cursor_pos = ( 0 , col ) elif char == codecs . CR : if self . text_align_mode == 'left' : self . cursor_pos = ( row , 0 ) else : self . cursor_pos = ( row , self . lcd . cols - 1 ) | Write the specified unicode string to the display . |
24,726 | def clear ( self ) : self . command ( c . LCD_CLEARDISPLAY ) self . _cursor_pos = ( 0 , 0 ) self . _content = [ [ 0x20 ] * self . lcd . cols for _ in range ( self . lcd . rows ) ] c . msleep ( 2 ) | Overwrite display with blank characters and reset cursor position . |
24,727 | def home ( self ) : self . command ( c . LCD_RETURNHOME ) self . _cursor_pos = ( 0 , 0 ) c . msleep ( 2 ) | Set cursor to initial position and reset any shifting . |
24,728 | def shift_display ( self , amount ) : if amount == 0 : return direction = c . LCD_MOVERIGHT if amount > 0 else c . LCD_MOVELEFT for i in range ( abs ( amount ) ) : self . command ( c . LCD_CURSORSHIFT | c . LCD_DISPLAYMOVE | direction ) c . usleep ( 50 ) | Shift the display . Use negative amounts to shift left and positive amounts to shift right . |
24,729 | def write ( self , value ) : row , col = self . _cursor_pos try : if self . _content [ row ] [ col ] != value : self . _send_data ( value ) self . _content [ row ] [ col ] = value unchanged = False else : unchanged = True except IndexError as e : if self . auto_linebreaks is True : raise e self . _send_data ( value ) unchanged = False if self . text_align_mode == 'left' : if self . auto_linebreaks is False or col < self . lcd . cols - 1 : newpos = ( row , col + 1 ) if unchanged : self . cursor_pos = newpos else : self . _cursor_pos = newpos self . recent_auto_linebreak = False else : if row < self . lcd . rows - 1 : self . cursor_pos = ( row + 1 , 0 ) else : self . cursor_pos = ( 0 , 0 ) self . recent_auto_linebreak = True else : if self . auto_linebreaks is False or col > 0 : newpos = ( row , col - 1 ) if unchanged : self . cursor_pos = newpos else : self . _cursor_pos = newpos self . recent_auto_linebreak = False else : if row < self . lcd . rows - 1 : self . cursor_pos = ( row + 1 , self . lcd . cols - 1 ) else : self . cursor_pos = ( 0 , self . lcd . cols - 1 ) self . recent_auto_linebreak = True | Write a raw byte to the LCD . |
24,730 | def cursor ( lcd , row , col ) : warnings . warn ( 'The `cursor` context manager is deprecated' , DeprecationWarning ) lcd . cursor_pos = ( row , col ) yield | Context manager to control cursor position . DEPRECATED . |
24,731 | def sliding_window ( seq , lookahead ) : it = itertools . chain ( iter ( seq ) , ' ' * lookahead ) window_size = lookahead + 1 result = tuple ( itertools . islice ( it , window_size ) ) if len ( result ) == window_size : yield result for elem in it : result = result [ 1 : ] + ( elem , ) yield result | Create a sliding window with the specified number of lookahead characters . |
24,732 | def get_params ( ) : parser = argparse . ArgumentParser ( ) parser . add_argument ( "--connect-timeout" , type = float , default = 10.0 , help = "ZK connect timeout" ) parser . add_argument ( "--run-once" , type = str , default = "" , help = "Run a command non-interactively and exit" ) parser . add_argument ( "--run-from-stdin" , action = "store_true" , default = False , help = "Read cmds from stdin, run them and exit" ) parser . add_argument ( "--sync-connect" , action = "store_true" , default = False , help = "Connect synchronously." ) parser . add_argument ( "--readonly" , action = "store_true" , default = False , help = "Enable readonly." ) parser . add_argument ( "--tunnel" , type = str , help = "Create a ssh tunnel via this host" , default = None ) parser . add_argument ( "--version" , action = "store_true" , default = False , help = "Display version and exit." ) parser . add_argument ( "hosts" , nargs = "*" , help = "ZK hosts to connect" ) params = parser . parse_args ( ) return CLIParams ( params . connect_timeout , params . run_once , params . run_from_stdin , params . sync_connect , params . hosts , params . readonly , params . tunnel , params . version ) | get the cmdline params |
24,733 | def set_unbuffered_mode ( ) : class Unbuffered ( object ) : def __init__ ( self , stream ) : self . stream = stream def write ( self , data ) : self . stream . write ( data ) self . stream . flush ( ) def __getattr__ ( self , attr ) : return getattr ( self . stream , attr ) sys . stdout = Unbuffered ( sys . stdout ) | make output unbuffered |
24,734 | def to_dict ( cls , acl ) : return { "perms" : acl . perms , "id" : { "scheme" : acl . id . scheme , "id" : acl . id . id } } | transform an ACL to a dict |
24,735 | def from_dict ( cls , acl_dict ) : perms = acl_dict . get ( "perms" , Permissions . ALL ) id_dict = acl_dict . get ( "id" , { } ) id_scheme = id_dict . get ( "scheme" , "world" ) id_id = id_dict . get ( "id" , "anyone" ) return ACL ( perms , Id ( id_scheme , id_id ) ) | ACL from dict |
24,736 | def connected ( func ) : @ wraps ( func ) def wrapper ( * args , ** kwargs ) : self = args [ 0 ] if not self . connected : self . show_output ( "Not connected." ) else : try : return func ( * args , ** kwargs ) except APIError : self . show_output ( "ZooKeeper internal error." ) except AuthFailedError : self . show_output ( "Authentication failed." ) except NoAuthError : self . show_output ( "Not authenticated." ) except BadVersionError : self . show_output ( "Bad version." ) except ConnectionLoss : self . show_output ( "Connection loss." ) except NotReadOnlyCallError : self . show_output ( "Not a read-only operation." ) except BadArgumentsError : self . show_output ( "Bad arguments." ) except SessionExpiredError : self . show_output ( "Session expired." ) except UnimplementedError as ex : self . show_output ( "Not implemented by the server: %s." % str ( ex ) ) except ZookeeperError as ex : self . show_output ( "Unknown ZooKeeper error: %s" % str ( ex ) ) return wrapper | check connected fails otherwise |
24,737 | def do_add_auth ( self , params ) : self . _zk . add_auth ( params . scheme , params . credential ) | \ x1b [ 1mNAME \ x1b [ 0m add_auth - Authenticates the session |
24,738 | def do_set_acls ( self , params ) : try : acls = ACLReader . extract ( shlex . split ( params . acls ) ) except ACLReader . BadACL as ex : self . show_output ( "Failed to set ACLs: %s." , ex ) return def set_acls ( path ) : try : self . _zk . set_acls ( path , acls ) except ( NoNodeError , BadVersionError , InvalidACLError , ZookeeperError ) as ex : self . show_output ( "Failed to set ACLs: %s. Error: %s" , str ( acls ) , str ( ex ) ) if params . recursive : for cpath , _ in self . _zk . tree ( params . path , 0 , full_path = True ) : set_acls ( cpath ) set_acls ( params . path ) | \ x1b [ 1mNAME \ x1b [ 0m set_acls - Sets ACLs for a given path |
24,739 | def do_get_acls ( self , params ) : def replace ( plist , oldv , newv ) : try : plist . remove ( oldv ) plist . insert ( 0 , newv ) except ValueError : pass for path , acls in self . _zk . get_acls_recursive ( params . path , params . depth , params . ephemerals ) : replace ( acls , READ_ACL_UNSAFE [ 0 ] , "WORLD_READ" ) replace ( acls , OPEN_ACL_UNSAFE [ 0 ] , "WORLD_ALL" ) self . show_output ( "%s: %s" , path , acls ) | \ x1b [ 1mNAME \ x1b [ 0m get_acls - Gets ACLs for a given path |
24,740 | def do_watch ( self , params ) : wm = get_watch_manager ( self . _zk ) if params . command == "start" : debug = to_bool ( params . debug ) children = to_int ( params . sleep , - 1 ) wm . add ( params . path , debug , children ) elif params . command == "stop" : wm . remove ( params . path ) elif params . command == "stats" : repeat = to_int ( params . debug , 1 ) sleep = to_int ( params . sleep , 1 ) if repeat == 0 : while True : wm . stats ( params . path ) time . sleep ( sleep ) else : for _ in range ( 0 , repeat ) : wm . stats ( params . path ) time . sleep ( sleep ) else : self . show_output ( "watch <start|stop|stats> <path> [verbose]" ) | \ x1b [ 1mNAME \ x1b [ 0m watch - Recursively watch for all changes under a path . |
24,741 | def do_child_count ( self , params ) : for child , level in self . _zk . tree ( params . path , params . depth , full_path = True ) : self . show_output ( "%s: %d" , child , self . _zk . child_count ( child ) ) | \ x1b [ 1mNAME \ x1b [ 0m child_count - Prints the child count for paths |
24,742 | def do_du ( self , params ) : self . show_output ( pretty_bytes ( self . _zk . du ( params . path ) ) ) | \ x1b [ 1mNAME \ x1b [ 0m du - Total number of bytes under a path |
24,743 | def do_find ( self , params ) : for path in self . _zk . find ( params . path , params . match , 0 ) : self . show_output ( path ) | \ x1b [ 1mNAME \ x1b [ 0m find - Find znodes whose path matches a given text |
24,744 | def do_summary ( self , params ) : self . show_output ( "%s%s%s%s" , "Created" . ljust ( 32 ) , "Last modified" . ljust ( 32 ) , "Owner" . ljust ( 23 ) , "Name" ) results = sorted ( self . _zk . stat_map ( params . path ) ) if params . top == 0 : start , end = 0 , len ( results ) elif params . top > 0 : start , end = 0 , params . top if params . top < len ( results ) else len ( results ) else : start = len ( results ) + params . top if abs ( params . top ) < len ( results ) else 0 end = len ( results ) offs = 1 if params . path == "/" else len ( params . path ) + 1 for i in range ( start , end ) : path , stat = results [ i ] self . show_output ( "%s%s%s%s" , time . ctime ( stat . created ) . ljust ( 32 ) , time . ctime ( stat . last_modified ) . ljust ( 32 ) , ( "0x%x" % stat . ephemeralOwner ) . ljust ( 23 ) , path [ offs : ] ) | \ x1b [ 1mNAME \ x1b [ 0m summary - Prints summarized details of a path s children |
24,745 | def do_grep ( self , params ) : self . grep ( params . path , params . content , 0 , params . show_matches ) | \ x1b [ 1mNAME \ x1b [ 0m grep - Prints znodes with a value matching the given text |
24,746 | def do_get ( self , params ) : watcher = lambda evt : self . show_output ( str ( evt ) ) kwargs = { "watch" : watcher } if params . watch else { } value , _ = self . _zk . get ( params . path , ** kwargs ) if value is not None : try : value = zlib . decompress ( value ) except : pass self . show_output ( value ) | \ x1b [ 1mNAME \ x1b [ 0m get - Gets the znode s value |
24,747 | def do_exists ( self , params ) : watcher = lambda evt : self . show_output ( str ( evt ) ) kwargs = { "watch" : watcher } if params . watch else { } pretty = params . pretty_date path = self . resolve_path ( params . path ) stat = self . _zk . exists ( path , ** kwargs ) if stat : session = stat . ephemeralOwner if stat . ephemeralOwner else 0 self . show_output ( "Stat(" ) self . show_output ( " czxid=0x%x" , stat . czxid ) self . show_output ( " mzxid=0x%x" , stat . mzxid ) self . show_output ( " ctime=%s" , time . ctime ( stat . created ) if pretty else stat . ctime ) self . show_output ( " mtime=%s" , time . ctime ( stat . last_modified ) if pretty else stat . mtime ) self . show_output ( " version=%s" , stat . version ) self . show_output ( " cversion=%s" , stat . cversion ) self . show_output ( " aversion=%s" , stat . aversion ) self . show_output ( " ephemeralOwner=0x%x" , session ) self . show_output ( " dataLength=%s" , stat . dataLength ) self . show_output ( " numChildren=%s" , stat . numChildren ) self . show_output ( " pzxid=0x%x" , stat . pzxid ) self . show_output ( ")" ) else : self . show_output ( "Path %s doesn't exist" , params . path ) | \ x1b [ 1mNAME \ x1b [ 0m exists - Gets the znode s stat information |
24,748 | def do_create ( self , params ) : try : kwargs = { "acl" : None , "ephemeral" : params . ephemeral , "sequence" : params . sequence } if not self . in_transaction : kwargs [ "makepath" ] = params . recursive if params . asynchronous and not self . in_transaction : self . client_context . create_async ( params . path , decoded ( params . value ) , ** kwargs ) else : self . client_context . create ( params . path , decoded ( params . value ) , ** kwargs ) except NodeExistsError : self . show_output ( "Path %s exists" , params . path ) except NoNodeError : self . show_output ( "Missing path in %s (try recursive?)" , params . path ) | \ x1b [ 1mNAME \ x1b [ 0m create - Creates a znode |
24,749 | def do_set ( self , params ) : self . set ( params . path , decoded ( params . value ) , version = params . version ) | \ x1b [ 1mNAME \ x1b [ 0m set - Updates the znode s value |
24,750 | def set ( self , path , value , version ) : if self . in_transaction : self . client_context . set_data ( path , value , version = version ) else : self . client_context . set ( path , value , version = version ) | sets a znode s data |
24,751 | def do_rm ( self , params ) : for path in params . paths : try : self . client_context . delete ( path ) except NotEmptyError : self . show_output ( "%s is not empty." , path ) except NoNodeError : self . show_output ( "%s doesn't exist." , path ) | \ x1b [ 1mNAME \ x1b [ 0m rm - Remove the znode |
24,752 | def do_txn ( self , params ) : try : with self . transaction ( ) : for cmd in params . cmds : try : self . onecmd ( cmd ) except AttributeError : pass except BadVersionError : self . show_output ( "Bad version." ) except NoNodeError : self . show_output ( "Missing path." ) except NodeExistsError : self . show_output ( "One of the paths exists." ) | \ x1b [ 1mNAME \ x1b [ 0m txn - Create and execute a transaction |
24,753 | def do_session_info ( self , params ) : fmt_str = content = fmt_str % ( self . _zk . client_state , self . _zk . sessionid , list ( self . _zk . auth_data ) , self . _zk . protocol_version , self . _zk . xid , self . _zk . last_zxid , self . _zk . session_timeout , self . _zk . client , self . _zk . server , "," . join ( self . _zk . data_watches ) , "," . join ( self . _zk . child_watches ) ) output = get_matching ( content , params . match ) self . show_output ( output ) | \ x1b [ 1mNAME \ x1b [ 0m session_info - Shows information about the current session |
24,754 | def do_mntr ( self , params ) : hosts = params . hosts if params . hosts != "" else None if hosts is not None and invalid_hosts ( hosts ) : self . show_output ( "List of hosts has the wrong syntax." ) return if self . _zk is None : self . _zk = XClient ( ) try : content = get_matching ( self . _zk . mntr ( hosts ) , params . match ) self . show_output ( content ) except XClient . CmdFailed as ex : self . show_output ( str ( ex ) ) | \ x1b [ 1mNAME \ x1b [ 0m mntr - Executes the mntr four - letter command |
24,755 | def do_cons ( self , params ) : hosts = params . hosts if params . hosts != "" else None if hosts is not None and invalid_hosts ( hosts ) : self . show_output ( "List of hosts has the wrong syntax." ) return if self . _zk is None : self . _zk = XClient ( ) try : content = get_matching ( self . _zk . cons ( hosts ) , params . match ) self . show_output ( content ) except XClient . CmdFailed as ex : self . show_output ( str ( ex ) ) | \ x1b [ 1mNAME \ x1b [ 0m cons - Executes the cons four - letter command |
24,756 | def do_dump ( self , params ) : hosts = params . hosts if params . hosts != "" else None if hosts is not None and invalid_hosts ( hosts ) : self . show_output ( "List of hosts has the wrong syntax." ) return if self . _zk is None : self . _zk = XClient ( ) try : content = get_matching ( self . _zk . dump ( hosts ) , params . match ) self . show_output ( content ) except XClient . CmdFailed as ex : self . show_output ( str ( ex ) ) | \ x1b [ 1mNAME \ x1b [ 0m dump - Executes the dump four - letter command |
24,757 | def do_rmr ( self , params ) : for path in params . paths : self . _zk . delete ( path , recursive = True ) | \ x1b [ 1mNAME \ x1b [ 0m rmr - Delete a path and all its children |
24,758 | def do_child_watch ( self , params ) : get_child_watcher ( self . _zk , print_func = self . show_output ) . update ( params . path , params . verbose ) | \ x1b [ 1mNAME \ x1b [ 0m child_watch - Watch a path for child changes |
24,759 | def do_diff ( self , params ) : count = 0 for count , ( diff , path ) in enumerate ( self . _zk . diff ( params . path_a , params . path_b ) , 1 ) : if diff == - 1 : self . show_output ( "-- %s" , path ) elif diff == 0 : self . show_output ( "-+ %s" , path ) elif diff == 1 : self . show_output ( "++ %s" , path ) if count == 0 : self . show_output ( "Branches are equal." ) | \ x1b [ 1mNAME \ x1b [ 0m diff - Display the differences between two paths |
24,760 | def do_json_valid ( self , params ) : def check_valid ( path , print_path ) : result = "no" value , _ = self . _zk . get ( path ) if value is not None : try : x = json . loads ( value ) result = "yes" except ValueError : pass if print_path : self . show_output ( "%s: %s." , os . path . basename ( path ) , result ) else : self . show_output ( "%s." , result ) if not params . recursive : check_valid ( params . path , False ) else : for cpath , _ in self . _zk . tree ( params . path , 0 , full_path = True ) : check_valid ( cpath , True ) | \ x1b [ 1mNAME \ x1b [ 0m json_valid - Checks znodes for valid JSON |
24,761 | def do_json_cat ( self , params ) : def json_output ( path , print_path ) : value , _ = self . _zk . get ( path ) if value is not None : try : value = json . dumps ( json . loads ( value ) , indent = 4 ) except ValueError : pass if print_path : self . show_output ( "%s:\n%s" , os . path . basename ( path ) , value ) else : self . show_output ( value ) if not params . recursive : json_output ( params . path , False ) else : for cpath , _ in self . _zk . tree ( params . path , 0 , full_path = True ) : json_output ( cpath , True ) | \ x1b [ 1mNAME \ x1b [ 0m json_cat - Pretty prints a znode s JSON |
24,762 | def do_json_count_values ( self , params ) : try : Keys . validate ( params . keys ) except Keys . Bad as ex : self . show_output ( str ( ex ) ) return path_map = PathMap ( self . _zk , params . path ) values = defaultdict ( int ) for path , data in path_map . get ( ) : try : value = Keys . value ( json_deserialize ( data ) , params . keys ) values [ value ] += 1 except BadJSON as ex : if params . report_errors : self . show_output ( "Path %s has bad JSON." , path ) except Keys . Missing as ex : if params . report_errors : self . show_output ( "Path %s is missing key %s." , path , ex ) results = sorted ( values . items ( ) , key = lambda item : item [ 1 ] , reverse = params . reverse ) results = [ r for r in results if r [ 1 ] >= params . minfreq ] if params . top == 0 : start , end = 0 , len ( results ) elif params . top > 0 : start , end = 0 , params . top if params . top < len ( results ) else len ( results ) else : start = len ( results ) + params . top if abs ( params . top ) < len ( results ) else 0 end = len ( results ) if len ( results ) > 0 and params . print_path : self . show_output ( params . path ) for i in range ( start , end ) : value , frequency = results [ i ] self . show_output ( "%s = %d" , value , frequency ) if len ( results ) == 0 : return False | \ x1b [ 1mNAME \ x1b [ 0m json_count_values - Gets the frequency of the values associated with the given keys |
24,763 | def do_json_dupes_for_keys ( self , params ) : try : Keys . validate ( params . keys ) except Keys . Bad as ex : self . show_output ( str ( ex ) ) return path_map = PathMap ( self . _zk , params . path ) dupes_by_path = defaultdict ( lambda : defaultdict ( list ) ) for path , data in path_map . get ( ) : parent , child = split ( path ) if not child . startswith ( params . prefix ) : continue try : value = Keys . value ( json_deserialize ( data ) , params . keys ) dupes_by_path [ parent ] [ value ] . append ( path ) except BadJSON as ex : if params . report_errors : self . show_output ( "Path %s has bad JSON." , path ) except Keys . Missing as ex : if params . report_errors : self . show_output ( "Path %s is missing key %s." , path , ex ) dupes = [ ] for _ , paths_by_value in dupes_by_path . items ( ) : for _ , paths in paths_by_value . items ( ) : if len ( paths ) > 1 : paths . sort ( ) paths = paths if params . first else paths [ 1 : ] for path in paths : idx = bisect . bisect ( dupes , path ) dupes . insert ( idx , path ) for dup in dupes : self . show_output ( dup ) if len ( dupes ) == 0 : return False | \ x1b [ 1mNAME \ x1b [ 0m json_duples_for_keys - Gets the duplicate znodes for the given keys |
24,764 | def do_edit ( self , params ) : if os . getuid ( ) == 0 : self . show_output ( "edit cannot be run as root." ) return editor = os . getenv ( "EDITOR" , os . getenv ( "VISUAL" , "/usr/bin/vi" ) ) if editor is None : self . show_output ( "No editor found, please set $EDITOR" ) return editor = which ( editor ) if not editor : self . show_output ( "Cannot find executable editor, please set $EDITOR" ) return st = os . stat ( editor ) if ( st . st_mode & statlib . S_ISUID ) or ( st . st_mode & statlib . S_ISUID ) : self . show_output ( "edit cannot use setuid/setgid binaries." ) return value , stat = self . _zk . get ( params . path ) _ , tmppath = tempfile . mkstemp ( ) with open ( tmppath , "w" ) as fh : fh . write ( value if value else "" ) rv = os . system ( "%s %s" % ( editor , tmppath ) ) if rv != 0 : self . show_output ( "%s did not exit successfully" % editor ) try : os . unlink ( tmppath ) except OSError : pass return with open ( tmppath , "r" ) as fh : newvalue = fh . read ( ) if newvalue != value : self . set ( params . path , decoded ( newvalue ) , stat . version ) try : os . unlink ( tmppath ) except OSError : pass | \ x1b [ 1mNAME \ x1b [ 0m edit - Opens up an editor to modify and update a znode . |
24,765 | def do_loop ( self , params ) : repeat = params . repeat if repeat < 0 : self . show_output ( "<repeat> must be >= 0." ) return pause = params . pause if pause < 0 : self . show_output ( "<pause> must be >= 0." ) return cmds = params . cmds i = 0 with self . transitions_disabled ( ) : while True : for cmd in cmds : try : self . onecmd ( cmd ) except Exception as ex : self . show_output ( "Command failed: %s." , ex ) if pause > 0.0 : time . sleep ( pause ) i += 1 if repeat > 0 and i >= repeat : break | \ x1b [ 1mNAME \ x1b [ 0m loop - Runs commands in a loop |
24,766 | def do_session_endpoint ( self , params ) : if invalid_hosts ( params . hosts ) : self . show_output ( "List of hosts has the wrong syntax." ) return try : info_by_id = self . _zk . sessions_info ( params . hosts ) except XClient . CmdFailed as ex : self . show_output ( str ( ex ) ) return info = info_by_id . get ( params . session , None ) if info is None : self . show_output ( "No session info for %s." , params . session ) else : self . show_output ( "%s" , info . resolved_endpoints if params . reverse else info . endpoints ) | \ x1b [ 1mNAME \ x1b [ 0m session_endpoint - Gets the session s IP endpoints |
24,767 | def do_fill ( self , params ) : self . _zk . set ( params . path , decoded ( params . val * params . repeat ) ) | \ x1b [ 1mNAME \ x1b [ 0m fill - Fills a znode with the given value |
24,768 | def do_time ( self , params ) : start = time . time ( ) for cmd in params . cmds : try : self . onecmd ( cmd ) except Exception as ex : self . show_output ( "Command failed: %s." , ex ) elapsed = "{0:.5f}" . format ( time . time ( ) - start ) self . show_output ( "Took %s seconds" % elapsed ) | \ x1b [ 1mNAME \ x1b [ 0m time - Measures elapsed seconds after running commands |
24,769 | def do_echo ( self , params ) : values = [ ] with self . output_context ( ) as context : for cmd in params . cmds : rv = self . onecmd ( cmd ) val = "" if rv is False else context . value . rstrip ( "\n" ) values . append ( val ) context . reset ( ) try : self . show_output ( params . fmtstr , * values ) except TypeError : self . show_output ( "Bad format string or missing arguments." ) | \ x1b [ 1mNAME \ x1b [ 0m echo - displays formatted data |
24,770 | def connected_socket ( address , timeout = 3 ) : sock = socket . create_connection ( address , timeout ) yield sock sock . close ( ) | yields a connected socket |
24,771 | def get_bytes ( self , * args , ** kwargs ) : return super ( XClient , self ) . get ( * args , ** kwargs ) | no string decoding performed |
24,772 | def get_acls_recursive ( self , path , depth , include_ephemerals ) : yield path , self . get_acls ( path ) [ 0 ] if depth == - 1 : return for tpath , _ in self . tree ( path , depth , full_path = True ) : try : acls , stat = self . get_acls ( tpath ) except NoNodeError : continue if not include_ephemerals and stat . ephemeralOwner != 0 : continue yield tpath , acls | A recursive generator wrapper for get_acls |
24,773 | def find ( self , path , match , flags ) : try : match = re . compile ( match , flags ) except sre_constants . error as ex : print ( "Bad regexp: %s" % ( ex ) ) return offset = len ( path ) for cpath in Tree ( self , path ) . get ( ) : if match . search ( cpath [ offset : ] ) : yield cpath | find every matching child path under path |
24,774 | def grep ( self , path , content , flags ) : try : match = re . compile ( content , flags ) except sre_constants . error as ex : print ( "Bad regexp: %s" % ( ex ) ) return for gpath , matches in self . do_grep ( path , match ) : yield ( gpath , matches ) | grep every child path under path for content |
24,775 | def do_grep ( self , path , match ) : try : children = self . get_children ( path ) except ( NoNodeError , NoAuthError ) : children = [ ] for child in children : full_path = os . path . join ( path , child ) try : value , _ = self . get ( full_path ) except ( NoNodeError , NoAuthError ) : value = "" if value is not None : matches = [ line for line in value . split ( "\n" ) if match . search ( line ) ] if len ( matches ) > 0 : yield ( full_path , matches ) for mpath , matches in self . do_grep ( full_path , match ) : yield ( mpath , matches ) | grep s work horse |
24,776 | def tree ( self , path , max_depth , full_path = False , include_stat = False ) : for child_level_stat in self . do_tree ( path , max_depth , 0 , full_path , include_stat ) : yield child_level_stat | DFS generator which starts from a given path and goes up to a max depth . |
24,777 | def do_tree ( self , path , max_depth , level , full_path , include_stat ) : try : children = self . get_children ( path ) except ( NoNodeError , NoAuthError ) : children = [ ] for child in children : cpath = os . path . join ( path , child ) if full_path else child if include_stat : yield cpath , level , self . stat ( os . path . join ( path , child ) ) else : yield cpath , level if max_depth == 0 or level + 1 < max_depth : cpath = os . path . join ( path , child ) for rchild_rlevel_rstat in self . do_tree ( cpath , max_depth , level + 1 , full_path , include_stat ) : yield rchild_rlevel_rstat | tree s work horse |
24,778 | def equal ( self , path_a , path_b ) : content_a , _ = self . get_bytes ( path_a ) content_b , _ = self . get_bytes ( path_b ) return content_a == content_b | compare if a and b have the same bytes |
24,779 | def stat ( self , path ) : try : stat = self . exists ( str ( path ) ) except ( NoNodeError , NoAuthError ) : stat = None return stat | safely gets the Znode s Stat |
24,780 | def reconnect ( self ) : state_change_event = self . handler . event_object ( ) def listener ( state ) : if state is KazooState . SUSPENDED : state_change_event . set ( ) self . add_listener ( listener ) self . _connection . _socket . shutdown ( socket . SHUT_RDWR ) state_change_event . wait ( 1 ) if not state_change_event . is_set ( ) : return False while not self . connected : time . sleep ( 0.1 ) return True | forces a reconnect by shutting down the connected socket return True if the reconnect happened False otherwise |
24,781 | def dump_by_server ( self , hosts ) : dump_by_endpoint = { } for endpoint in self . _to_endpoints ( hosts ) : try : out = self . cmd ( [ endpoint ] , "dump" ) except self . CmdFailed as ex : out = "" dump_by_endpoint [ endpoint ] = out return dump_by_endpoint | Returns the output of dump for each server . |
24,782 | def ephemerals_info ( self , hosts ) : info_by_path , info_by_id = { } , { } for server_endpoint , dump in self . dump_by_server ( hosts ) . items ( ) : server_ip , server_port = server_endpoint sid = None for line in dump . split ( "\n" ) : mat = self . SESSION_REGEX . match ( line ) if mat : sid = mat . group ( 1 ) continue mat = self . PATH_REGEX . match ( line ) if mat : info = info_by_id . get ( sid , None ) if info is None : info = info_by_id [ sid ] = ClientInfo ( sid ) info_by_path [ mat . group ( 1 ) ] = info continue mat = self . IP_PORT_REGEX . match ( line ) if mat : ip , port , sid = mat . groups ( ) if sid not in info_by_id : continue info_by_id [ sid ] ( ip , int ( port ) , server_ip , server_port ) return info_by_path | Returns ClientInfo per path . |
24,783 | def sessions_info ( self , hosts ) : info_by_id = { } for server_endpoint , dump in self . dump_by_server ( hosts ) . items ( ) : server_ip , server_port = server_endpoint for line in dump . split ( "\n" ) : mat = self . IP_PORT_REGEX . match ( line ) if mat is None : continue ip , port , sid = mat . groups ( ) info_by_id [ sid ] = ClientInfo ( sid , ip , port , server_ip , server_port ) return info_by_id | Returns ClientInfo per session . |
24,784 | def update ( self , path , verbose = False ) : if path in self . _by_path : self . remove ( path ) else : self . add ( path , verbose ) | if the path isn t being watched start watching it if it is stop watching it |
24,785 | def from_string ( cls , string , exists = False , asynchronous = False , verbose = False ) : result = cls . parse ( string ) if result . scheme not in cls . TYPES : raise CopyError ( "Invalid scheme: %s" % ( result . scheme ) ) return cls . TYPES [ result . scheme ] ( result , exists , asynchronous , verbose ) | if exists is bool then check it either exists or it doesn t . if exists is None we don t care . |
24,786 | def zk_walk ( self , root_path , branch_path ) : full_path = os . path . join ( root_path , branch_path ) if branch_path else root_path try : children = self . client . get_children ( full_path ) except NoNodeError : children = set ( ) except NoAuthError : raise AuthError ( "read children" , full_path ) for child in children : child_path = os . path . join ( branch_path , child ) if branch_path else child try : stat = self . client . exists ( os . path . join ( root_path , child_path ) ) except NoAuthError : raise AuthError ( "read" , child ) if stat is None or stat . ephemeralOwner != 0 : continue yield child_path for new_path in self . zk_walk ( root_path , child_path ) : yield new_path | skip ephemeral znodes since there s no point in copying those |
24,787 | def write_path ( self , path_value ) : parent_dir = os . path . dirname ( self . path ) try : os . makedirs ( parent_dir ) except OSError : pass with open ( self . path , "w" ) as fph : fph . write ( path_value . value ) | this will overwrite dst path - be careful |
24,788 | def get ( self , exclude_recurse = None ) : reqs = Queue ( ) pending = 1 path = self . path zk = self . zk def child_of ( path ) : return zk . get_children_async ( path ) def dispatch ( path ) : return Request ( path , child_of ( path ) ) stat = zk . exists ( path ) if stat is None or stat . numChildren == 0 : return reqs . put ( dispatch ( path ) ) while pending : req = reqs . get ( ) try : children = req . value for child in children : cpath = os . path . join ( req . path , child ) if exclude_recurse is None or exclude_recurse not in child : pending += 1 reqs . put ( dispatch ( cpath ) ) yield cpath except ( NoNodeError , NoAuthError ) : pass pending -= 1 | Paths matching exclude_recurse will not be recursed . |
24,789 | def to_type ( value , ptype ) : if ptype == 'str' : return str ( value ) elif ptype == 'int' : return int ( value ) elif ptype == 'float' : return float ( value ) elif ptype == 'bool' : if value . lower ( ) == 'true' : return True elif value . lower ( ) == 'false' : return False raise ValueError ( 'Bad bool value: %s' % value ) elif ptype == 'json' : return json . loads ( value ) return ValueError ( 'Unknown type' ) | Convert value to ptype |
24,790 | def validate_one ( cls , keystr ) : regex = r'%s$' % cls . ALLOWED_KEY if re . match ( regex , keystr ) is None : raise cls . Bad ( "Bad key syntax for: %s. Should be: key1.key2..." % ( keystr ) ) return True | validates one key string |
24,791 | def validate ( cls , keystr ) : if "#{" in keystr : keys = cls . from_template ( keystr ) for k in keys : cls . validate_one ( cls . extract ( k ) ) else : cls . validate_one ( keystr ) | raises cls . Bad if keys has errors |
24,792 | def fetch ( cls , obj , keys ) : current = obj for key in keys . split ( "." ) : if type ( current ) == list : try : key = int ( key ) except TypeError : raise cls . Missing ( key ) try : current = current [ key ] except ( IndexError , KeyError , TypeError ) as ex : raise cls . Missing ( key ) return current | fetches the value corresponding to keys from obj |
24,793 | def value ( cls , obj , keystr ) : if "#{" in keystr : keys = cls . from_template ( keystr ) for k in keys : v = cls . fetch ( obj , cls . extract ( k ) ) keystr = keystr . replace ( k , str ( v ) ) value = keystr else : value = cls . fetch ( obj , keystr ) return value | gets the value corresponding to keys from obj . if keys is a template string it extrapolates the keys in it |
24,794 | def set ( cls , obj , keys , value , fill_list_value = None ) : current = obj keys_list = keys . split ( "." ) for idx , key in enumerate ( keys_list , 1 ) : if type ( current ) == list : try : key = int ( key ) except ValueError : raise cls . Missing ( key ) try : if idx == len ( keys_list ) : if type ( current ) == list : safe_list_set ( current , key , lambda : copy . copy ( fill_list_value ) , value ) else : current [ key ] = value return if type ( key ) == int : try : current [ key ] except IndexError : cnext = container_for_key ( keys_list [ idx ] ) if type ( cnext ) == list : def fill_with ( ) : return [ ] else : def fill_with ( ) : return { } safe_list_set ( current , key , fill_with , [ ] if type ( cnext ) == list else { } ) else : if key not in current : current [ key ] = container_for_key ( keys_list [ idx ] ) current = current [ key ] except ( IndexError , KeyError , TypeError ) : raise cls . Missing ( key ) | sets the value for the given keys on obj . if any of the given keys does not exist create the intermediate containers . |
24,795 | def pretty_bytes ( num ) : for unit in [ '' , 'KB' , 'MB' , 'GB' ] : if num < 1024.0 : if unit == '' : return "%d" % ( num ) else : return "%3.1f%s" % ( num , unit ) num /= 1024.0 return "%3.1f%s" % ( num , 'TB' ) | pretty print the given number of bytes |
24,796 | def valid_ipv4 ( ip ) : match = _valid_ipv4 . match ( ip ) if match is None : return False octets = match . groups ( ) if len ( octets ) != 4 : return False first = int ( octets [ 0 ] ) if first < 1 or first > 254 : return False for i in range ( 1 , 4 ) : octet = int ( octets [ i ] ) if octet < 0 or octet > 255 : return False return True | check if ip is a valid ipv4 |
24,797 | def valid_host ( host ) : for part in host . split ( "." ) : if not _valid_host_part . match ( part ) : return False return True | check valid hostname |
24,798 | def valid_host_with_port ( hostport ) : host , port = hostport . rsplit ( ":" , 1 ) if ":" in hostport else ( hostport , None ) if not valid_ipv4 ( host ) and not valid_host ( host ) : return False if port is not None and not valid_port ( port ) : return False return True | matches hostname or an IP optionally with a port |
24,799 | def split ( path ) : if path == '/' : return ( '/' , None ) parent , child = path . rsplit ( '/' , 1 ) if parent == '' : parent = '/' return ( parent , child ) | splits path into parent child |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.