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...
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 No...
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 . framesToFrameRang...
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...
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_timesta...
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...
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...
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_tok...
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 , acces...
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 ( validat...
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 [ 'usernam...
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 . _...
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_lin...
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 ) u...
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-fr...
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_out...
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 , InvalidACLE...
\ 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"...
\ 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 == "st...
\ 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...
\ 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 st...
\ 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 , ...
\ 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 ( ...
\ 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...
\ 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 ) , pa...
\ 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 ) , pa...
\ 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 ) , pa...
\ 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 cou...
\ 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...
\ 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 ) el...
\ 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 ( d...
\ 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...
\ 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 edit...
\ 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...
\ 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 ( par...
\ 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 TypeErr...
\ 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 . e...
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 Non...
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 (...
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_e...
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 ) c...
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...
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 ch...
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 r...
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' ...
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 ) == l...
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 : retur...
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