idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
19,700
def net ( self ) : try : return NetData ( self . inspect ( cached = True ) . response ) except docker . errors . NotFound : raise NotAvailableAnymore ( )
get ACTIVE port mappings of a container
19,701
def top ( self ) : ps_args = "-eo pid,ppid,wchan,args" try : response = self . d . top ( self . container_id , ps_args = ps_args ) except docker . errors . APIError as ex : logger . warning ( "error getting processes: %r" , ex ) return [ ] logger . debug ( json . dumps ( response , indent = 2 ) ) return [ dict ( zip ( ...
list of processes in a running container
19,702
def filter ( self , containers = True , images = True , stopped = True , cached = False , sort_by_created = True ) : content = [ ] containers_o = None images_o = None if containers or not stopped : containers_o = self . get_containers ( cached = cached , stopped = stopped ) content += containers_o . response if images ...
since django is so awesome let s use their ORM API
19,703
def column_widths ( self , size , focus = False ) : maxcol = size [ 0 ] self . _cache_maxcol = maxcol widths = [ width for i , ( w , ( t , width , b ) ) in enumerate ( self . contents ) ] self . _cache_column_widths = widths return widths
Return a list of column widths .
19,704
def query ( self , query_string = "" ) : def query_notify ( operation ) : w = get_operation_notify_widget ( operation , display_always = False ) if w : self . ui . notify_widget ( w ) if query_string is not None : self . filter_query = query_string . strip ( ) backend_query = { "cached" : False , "containers" : True , ...
query and display also apply filters
19,705
def get_command ( self , command_input , docker_object = None , buffer = None , size = None ) : logger . debug ( "get command for command input %r" , command_input ) if not command_input : return if command_input [ 0 ] in [ "/" ] : command_name = command_input [ 0 ] unparsed_command_args = shlex . split ( command_input...
return command instance which is the actual command to be executed
19,706
def read ( self ) : val = self . _fd . read ( ) self . _fd . seek ( 0 ) return int ( val )
Read pin value
19,707
def getVersion ( ) : print ( 'epochs version:' , str ( CDFepoch . version ) + '.' + str ( CDFepoch . release ) + '.' + str ( CDFepoch . increment ) )
Shows the code version .
19,708
def getLeapSecondLastUpdated ( ) : print ( 'Leap second last updated:' , str ( CDFepoch . LTS [ - 1 ] [ 0 ] ) + '-' + str ( CDFepoch . LTS [ - 1 ] [ 1 ] ) + '-' + str ( CDFepoch . LTS [ - 1 ] [ 2 ] ) )
Shows the latest date a leap second was added to the leap second table .
19,709
def close ( self ) : if self . compressed_file is None : with self . path . open ( 'rb+' ) as f : f . seek ( 0 , 2 ) eof = f . tell ( ) self . _update_offset_value ( f , self . gdr_head + 36 , 8 , eof ) if self . checksum : f . write ( self . _md5_compute ( f ) ) return with self . path . open ( 'rb+' ) as f : f . seek...
Closes the CDF Class .
19,710
def _write_var_data_sparse ( self , f , zVar , var , dataType , numElems , recVary , oneblock ) : rec_start = oneblock [ 0 ] rec_end = oneblock [ 1 ] indata = oneblock [ 2 ] numValues = self . _num_values ( zVar , var ) _ , data = self . _convert_data ( dataType , numElems , numValues , indata ) if zVar : vdr_offset = ...
Writes a VVR and a VXR for this block of sparse data
19,711
def _create_vxr ( self , f , recStart , recEnd , currentVDR , priorVXR , vvrOffset ) : vxroffset = self . _write_vxr ( f ) self . _use_vxrentry ( f , vxroffset , recStart , recEnd , vvrOffset ) if ( priorVXR == 0 ) : self . _update_offset_value ( f , currentVDR + 28 , 8 , vxroffset ) else : self . _update_offset_value ...
Create a VXR AND use a VXR
19,712
def _use_vxrentry ( self , f , VXRoffset , recStart , recEnd , offset ) : f . seek ( VXRoffset + 20 ) numEntries = int . from_bytes ( f . read ( 4 ) , 'big' , signed = True ) usedEntries = int . from_bytes ( f . read ( 4 ) , 'big' , signed = True ) self . _update_offset_value ( f , VXRoffset + 28 + 4 * usedEntries , 4 ...
Adds a VVR pointer to a VXR
19,713
def _add_vxr_levels_r ( self , f , vxrhead , numVXRs ) : newNumVXRs = int ( numVXRs / CDF . NUM_VXRlvl_ENTRIES ) remaining = int ( numVXRs % CDF . NUM_VXRlvl_ENTRIES ) vxroff = vxrhead prevxroff = - 1 if ( remaining != 0 ) : newNumVXRs += 1 CDF . level += 1 for x in range ( 0 , newNumVXRs ) : newvxroff = self . _write_...
Build a new level of VXRs ... make VXRs more tree - like
19,714
def _update_vdr_vxrheadtail ( self , f , vdr_offset , VXRoffset ) : self . _update_offset_value ( f , vdr_offset + 28 , 8 , VXRoffset ) self . _update_offset_value ( f , vdr_offset + 36 , 8 , VXRoffset )
This sets a VXR to be the first and last VXR in the VDR
19,715
def _get_recrange ( self , f , VXRoffset ) : f . seek ( VXRoffset + 20 ) numEntries = int . from_bytes ( f . read ( 4 ) , 'big' , signed = True ) usedEntries = int . from_bytes ( f . read ( 4 ) , 'big' , signed = True ) firstRec = int . from_bytes ( f . read ( 4 ) , 'big' , signed = True ) f . seek ( VXRoffset + 28 + (...
Finds the first and last record numbers pointed by the VXR Assumes the VXRs are in order
19,716
def _datatype_size ( datatype , numElms ) : sizes = { 1 : 1 , 2 : 2 , 4 : 4 , 8 : 8 , 11 : 1 , 12 : 2 , 14 : 4 , 21 : 4 , 22 : 8 , 31 : 8 , 32 : 16 , 33 : 8 , 41 : 1 , 44 : 4 , 45 : 8 , 51 : 1 , 52 : 1 } try : if ( isinstance ( datatype , int ) ) : if ( datatype == 51 or datatype == 52 ) : return numElms else : return ...
Gets datatype size
19,717
def _write_adr ( self , f , gORv , name ) : f . seek ( 0 , 2 ) byte_loc = f . tell ( ) block_size = CDF . ADR_BASE_SIZE64 section_type = CDF . ADR_ nextADR = 0 headAgrEDR = 0 if ( gORv == True ) : scope = 1 else : scope = 2 num = len ( self . attrs ) ngrEntries = 0 maxgrEntry = - 1 rfuA = 0 headAzEDR = 0 nzEntries = 0 ...
Writes and ADR to the end of the file .
19,718
def _write_aedr ( self , f , gORz , attrNum , entryNum , value , pdataType , pnumElems , zVar ) : f . seek ( 0 , 2 ) byte_loc = f . tell ( ) if ( gORz == True or zVar != True ) : section_type = CDF . AgrEDR_ else : section_type = CDF . AzEDR_ nextAEDR = 0 if pdataType is None : if isinstance ( value , ( list , tuple ) ...
Writes an aedr into the end of the file .
19,719
def _write_vxr ( self , f , numEntries = None ) : f . seek ( 0 , 2 ) byte_loc = f . tell ( ) section_type = CDF . VXR_ nextVXR = 0 if ( numEntries == None ) : nEntries = CDF . NUM_VXR_ENTRIES else : nEntries = int ( numEntries ) block_size = CDF . VXR_BASE_SIZE64 + ( 4 + 4 + 8 ) * nEntries nUsedEntries = 0 firsts = [ -...
Creates a VXR at the end of the file . Returns byte location of the VXR The First Last and Offset fields will need to be filled in later
19,720
def _write_vvr ( self , f , data ) : f . seek ( 0 , 2 ) byte_loc = f . tell ( ) block_size = CDF . VVR_BASE_SIZE64 + len ( data ) section_type = CDF . VVR_ vvr1 = bytearray ( 12 ) vvr1 [ 0 : 8 ] = struct . pack ( '>q' , block_size ) vvr1 [ 8 : 12 ] = struct . pack ( '>i' , section_type ) f . write ( vvr1 ) f . write ( ...
Writes a vvr to the end of file f with the byte stream data .
19,721
def _write_cpr ( self , f , cType , parameter ) -> int : f . seek ( 0 , 2 ) byte_loc = f . tell ( ) block_size = CDF . CPR_BASE_SIZE64 + 4 section_type = CDF . CPR_ rfuA = 0 pCount = 1 cpr = bytearray ( block_size ) cpr [ 0 : 8 ] = struct . pack ( '>q' , block_size ) cpr [ 8 : 12 ] = struct . pack ( '>i' , section_type...
Write compression info to the end of the file in a CPR .
19,722
def _write_cvvr ( self , f , data ) : f . seek ( 0 , 2 ) byte_loc = f . tell ( ) cSize = len ( data ) block_size = CDF . CVVR_BASE_SIZE64 + cSize section_type = CDF . CVVR_ rfuA = 0 cvvr1 = bytearray ( 24 ) cvvr1 [ 0 : 8 ] = struct . pack ( '>q' , block_size ) cvvr1 [ 8 : 12 ] = struct . pack ( '>i' , section_type ) cv...
Write compressed data variable to the end of the file in a CVVR
19,723
def _write_ccr ( self , f , g , level : int ) : f . seek ( 8 ) data = f . read ( ) uSize = len ( data ) section_type = CDF . CCR_ rfuA = 0 cData = gzip . compress ( data , level ) block_size = CDF . CCR_BASE_SIZE64 + len ( cData ) cprOffset = 0 ccr1 = bytearray ( 32 ) ccr1 [ 0 : 8 ] = struct . pack ( '>q' , block_size ...
Write a CCR to file g from file f with level level . Currently only handles gzip compression .
19,724
def _convert_type ( data_type ) : if data_type in ( 1 , 41 ) : dt_string = 'b' elif data_type == 2 : dt_string = 'h' elif data_type == 4 : dt_string = 'i' elif data_type in ( 8 , 33 ) : dt_string = 'q' elif data_type == 11 : dt_string = 'B' elif data_type == 12 : dt_string = 'H' elif data_type == 14 : dt_string = 'I' e...
Converts CDF data types into python types
19,725
def _convert_nptype ( data_type , data ) : if data_type in ( 1 , 41 ) : return np . int8 ( data ) . tobytes ( ) elif data_type == 2 : return np . int16 ( data ) . tobytes ( ) elif data_type == 4 : return np . int32 ( data ) . tobytes ( ) elif ( data_type == 8 ) or ( data_type == 33 ) : return np . int64 ( data ) . toby...
Converts data of CDF type data_type into a numpy array
19,726
def _default_pad ( self , data_type , numElems ) : order = self . _convert_option ( ) if ( data_type == 1 ) or ( data_type == 41 ) : pad_value = struct . pack ( order + 'b' , - 127 ) elif data_type == 2 : pad_value = struct . pack ( order + 'h' , - 32767 ) elif data_type == 4 : pad_value = struct . pack ( order + 'i' ,...
Determines the default pad data for a data_type
19,727
def _num_values ( self , zVar , varNum ) : values = 1 if ( zVar == True ) : numDims = self . zvarsinfo [ varNum ] [ 2 ] dimSizes = self . zvarsinfo [ varNum ] [ 3 ] dimVary = self . zvarsinfo [ varNum ] [ 4 ] else : numDims = self . rvarsinfo [ varNum ] [ 2 ] dimSizes = self . rvarsinfo [ varNum ] [ 3 ] dimVary = self ...
Determines the number of values in a record . Set zVar = True if this is a zvariable .
19,728
def _read_offset_value ( self , f , offset , size ) : f . seek ( offset , 0 ) if ( size == 8 ) : return int . from_bytes ( f . read ( 8 ) , 'big' , signed = True ) else : return int . from_bytes ( f . read ( 4 ) , 'big' , signed = True )
Reads an integer value from file f at location offset .
19,729
def _update_offset_value ( self , f , offset , size , value ) : f . seek ( offset , 0 ) if ( size == 8 ) : f . write ( struct . pack ( '>q' , value ) ) else : f . write ( struct . pack ( '>i' , value ) )
Writes value into location offset in file f .
19,730
def _update_aedr_link ( self , f , attrNum , zVar , varNum , offset ) : adr_offset = self . attrsinfo [ attrNum ] [ 2 ] if zVar : f . seek ( adr_offset + 56 , 0 ) entries = int . from_bytes ( f . read ( 4 ) , 'big' , signed = True ) maxEntry = int . from_bytes ( f . read ( 4 ) , 'big' , signed = True ) else : f . seek ...
Updates variable aedr links
19,731
def _md5_compute ( self , f ) : md5 = hashlib . md5 ( ) block_size = 16384 f . seek ( 0 , 2 ) remaining = f . tell ( ) f . seek ( 0 ) while ( remaining > block_size ) : data = f . read ( block_size ) remaining = remaining - block_size md5 . update ( data ) if remaining > 0 : data = f . read ( remaining ) md5 . update (...
Computes the checksum of the file
19,732
def cdf_info ( self ) : mycdf_info = { } mycdf_info [ 'CDF' ] = self . file mycdf_info [ 'Version' ] = self . _version mycdf_info [ 'Encoding' ] = self . _encoding mycdf_info [ 'Majority' ] = self . _majority mycdf_info [ 'rVariables' ] , mycdf_info [ 'zVariables' ] = self . _get_varnames ( ) mycdf_info [ 'Attributes' ...
Returns a dictionary that shows the basic CDF information .
19,733
def varinq ( self , variable ) : vdr_info = self . varget ( variable = variable , inq = True ) if vdr_info is None : raise KeyError ( "Variable {} not found." . format ( variable ) ) var = { } var [ 'Variable' ] = vdr_info [ 'name' ] var [ 'Num' ] = vdr_info [ 'variable_number' ] var [ 'Var_Type' ] = CDF . _variable_to...
Returns a dictionary that shows the basic variable information .
19,734
def attinq ( self , attribute = None ) : position = self . _first_adr if isinstance ( attribute , str ) : for _ in range ( 0 , self . _num_att ) : name , next_adr = self . _read_adr_fast ( position ) if name . strip ( ) . lower ( ) == attribute . strip ( ) . lower ( ) : return self . _read_adr ( position ) position = n...
Get attribute information .
19,735
def epochrange ( self , epoch = None , starttime = None , endtime = None ) : return self . varget ( variable = epoch , starttime = starttime , endtime = endtime , record_range_only = True )
Get epoch range .
19,736
def globalattsget ( self , expand = False , to_np = True ) : byte_loc = self . _first_adr return_dict = { } for _ in range ( 0 , self . _num_att ) : adr_info = self . _read_adr ( byte_loc ) if ( adr_info [ 'scope' ] != 1 ) : byte_loc = adr_info [ 'next_adr_location' ] continue if ( adr_info [ 'num_gr_entry' ] == 0 ) : ...
Gets all global attributes .
19,737
def varattsget ( self , variable = None , expand = False , to_np = True ) : if ( isinstance ( variable , int ) and self . _num_zvariable > 0 and self . _num_rvariable > 0 ) : print ( 'This CDF has both r and z variables. Use variable name' ) return None if isinstance ( variable , str ) : position = self . _first_zvaria...
Gets all variable attributes .
19,738
def _uncompress_file ( self , path ) : with self . file . open ( 'rb' ) as f : if ( self . cdfversion == 3 ) : data_start , data_size , cType , _ = self . _read_ccr ( 8 ) else : data_start , data_size , cType , _ = self . _read_ccr2 ( 8 ) if cType != 5 : return f . seek ( data_start ) decompressed_data = gzip . decompr...
Writes the current file into a file in the temporary directory .
19,739
def _convert_option ( self ) : if sys . byteorder == 'little' and self . _endian ( ) == 'big-endian' : order = '>' elif sys . byteorder == 'big' and self . _endian ( ) == 'little-endian' : order = '<' else : order = '=' return order
Determines how to convert CDF byte ordering to the system byte ordering .
19,740
def _num_values ( self , vdr_dict ) : values = 1 for x in range ( 0 , vdr_dict [ 'num_dims' ] ) : if ( vdr_dict [ 'dim_vary' ] [ x ] != 0 ) : values = values * vdr_dict [ 'dim_sizes' ] [ x ] return values
Returns the number of values in a record using a given VDR dictionary . Multiplies the dimension sizes of each dimension if it is varying .
19,741
def _convert_type ( self , data_type ) : if ( data_type == 1 ) or ( data_type == 41 ) : dt_string = 'b' elif data_type == 2 : dt_string = 'h' elif data_type == 4 : dt_string = 'i' elif ( data_type == 8 ) or ( data_type == 33 ) : dt_string = 'q' elif data_type == 11 : dt_string = 'B' elif data_type == 12 : dt_string = '...
CDF data types to python struct data types
19,742
def _default_pad ( self , data_type , num_elms ) : order = self . _convert_option ( ) if ( data_type == 51 or data_type == 52 ) : return str ( ' ' * num_elms ) if ( data_type == 1 ) or ( data_type == 41 ) : pad_value = struct . pack ( order + 'b' , - 127 ) dt_string = 'i1' elif data_type == 2 : pad_value = struct . pac...
The default pad values by CDF data type
19,743
def _convert_np_data ( data , data_type , num_elems ) : if ( data_type == 51 or data_type == 52 ) : if ( data == '' ) : return ( '\x00' * num_elems ) . encode ( ) else : return data . ljust ( num_elems , '\x00' ) . encode ( 'utf-8' ) elif ( data_type == 32 ) : data_stream = data . real . tobytes ( ) data_stream += data...
Converts a single np data into byte stream .
19,744
def _read_vvr_block ( self , offset ) : with self . file . open ( 'rb' ) as f : f . seek ( offset , 0 ) block_size = int . from_bytes ( f . read ( 8 ) , 'big' ) block = f . read ( block_size - 8 ) section_type = int . from_bytes ( block [ 0 : 4 ] , 'big' ) if section_type == 13 : compressed_size = int . from_bytes ( bl...
Returns a VVR or decompressed CVVR block
19,745
def _find_block ( starts , ends , cur_block , rec_num ) : total = len ( starts ) if ( cur_block == - 1 ) : cur_block = 0 for x in range ( cur_block , total ) : if ( starts [ x ] <= rec_num and ends [ x ] >= rec_num ) : return x , x if ( starts [ x ] > rec_num ) : break return - 1 , x - 1
Finds the block that rec_num is in if it is found . Otherwise it returns - 1 . It also returns the block that has the physical data either at or preceeding the rec_num . It could be - 1 if the preceeding block does not exists .
19,746
def _convert_data ( self , data , data_type , num_recs , num_values , num_elems ) : if ( data_type == 51 or data_type == 52 ) : return [ data [ i : i + num_elems ] . decode ( 'utf-8' ) for i in range ( 0 , num_recs * num_values * num_elems , num_elems ) ] else : tofrom = self . _convert_option ( ) dt_string = self . _c...
Converts data to the appropriate type using the struct . unpack method rather than using numpy .
19,747
def getVersion ( ) : print ( 'CDFread version:' , str ( CDF . version ) + '.' + str ( CDF . release ) + '.' + str ( CDF . increment ) ) print ( 'Date: 2018/01/11' )
Shows the code version and last modified date .
19,748
def get_access_token ( self ) : if ( self . token is None ) or ( datetime . utcnow ( ) > self . reuse_token_until ) : headers = { 'Ocp-Apim-Subscription-Key' : self . client_secret } response = requests . post ( self . base_url , headers = headers ) response . raise_for_status ( ) self . token = response . content self...
Returns an access token for the specified subscription .
19,749
def main ( from_lang , to_lang , provider , secret_access_key , output_only , text ) : text = ' ' . join ( text ) kwargs = dict ( from_lang = from_lang , to_lang = to_lang , provider = provider ) if provider != DEFAULT_PROVIDER : kwargs [ 'secret_access_key' ] = secret_access_key translator = Translator ( ** kwargs ) t...
Python command line tool to make on line translations
19,750
def get_organization_id ( server_config , label ) : response = requests . get ( server_config [ 'url' ] + '/katello/api/v2/organizations' , data = json . dumps ( { 'search' : 'label={}' . format ( label ) } ) , auth = server_config [ 'auth' ] , headers = { 'content-type' : 'application/json' } , verify = server_config ...
Return the ID of the organization with label label .
19,751
def _make_entity_from_id ( entity_cls , entity_obj_or_id , server_config ) : if isinstance ( entity_obj_or_id , entity_cls ) : return entity_obj_or_id return entity_cls ( server_config , id = entity_obj_or_id )
Given an entity object or an ID return an entity object .
19,752
def _get_entity_id ( field_name , attrs ) : field_name_id = field_name + '_id' if field_name in attrs : if attrs [ field_name ] is None : return None elif 'id' in attrs [ field_name ] : return attrs [ field_name ] [ 'id' ] if field_name_id in attrs : return attrs [ field_name_id ] else : raise MissingValueError ( 'Cann...
Find the ID for a one to one relationship .
19,753
def _get_entity_ids ( field_name , attrs ) : field_name_ids = field_name + '_ids' plural_field_name = pluralize ( field_name ) if field_name_ids in attrs : return attrs [ field_name_ids ] elif field_name in attrs : return [ entity [ 'id' ] for entity in attrs [ field_name ] ] elif plural_field_name in attrs : return [ ...
Find the IDs for a one to many relationship .
19,754
def to_json_serializable ( obj ) : if isinstance ( obj , Entity ) : return obj . to_json_dict ( ) if isinstance ( obj , dict ) : return { k : to_json_serializable ( v ) for k , v in obj . items ( ) } elif isinstance ( obj , ( list , tuple ) ) : return [ to_json_serializable ( v ) for v in obj ] elif isinstance ( obj , ...
Transforms obj into a json serializable object .
19,755
def path ( self , which = None ) : base = urljoin ( self . _server_config . url + '/' , self . _meta [ 'api_path' ] ) if which == 'base' or ( which is None and not hasattr ( self , 'id' ) ) : return base elif ( which == 'self' or which is None ) and hasattr ( self , 'id' ) : return urljoin ( base + '/' , str ( self . i...
Return the path to the current entity .
19,756
def get_values ( self ) : attrs = vars ( self ) . copy ( ) attrs . pop ( '_server_config' ) attrs . pop ( '_fields' ) attrs . pop ( '_meta' ) if '_path_fields' in attrs : attrs . pop ( '_path_fields' ) return attrs
Return a copy of field values on the current object .
19,757
def to_json_dict ( self , filter_fcn = None ) : fields , values = self . get_fields ( ) , self . get_values ( ) filtered_fields = fields . items ( ) if filter_fcn is not None : filtered_fields = ( tpl for tpl in filtered_fields if filter_fcn ( tpl [ 0 ] , tpl [ 1 ] ) ) json_dct = { } for field_name , field in filtered_...
Create a dict with Entity properties for json encoding . It can be overridden by subclasses for each standard serialization doesn t work . By default it call _to_json_dict on OneToOne fields and build a list calling the same method on each OneToMany object s fields .
19,758
def compare ( self , other , filter_fcn = None ) : if not isinstance ( other , type ( self ) ) : return False if filter_fcn is None : def filter_unique ( _ , field ) : return not field . unique filter_fcn = filter_unique return self . to_json_dict ( filter_fcn ) == other . to_json_dict ( filter_fcn )
Returns True if properties can be compared in terms of eq . Entity s Fields can be filtered accordingly to filter_fcn . This callable receives field s name as first parameter and field itself as second parameter . It must return True if field s value should be included on comparison and False otherwise . If not provide...
19,759
def create_missing ( self ) : for field_name , field in self . get_fields ( ) . items ( ) : if field . required and not hasattr ( self , field_name ) : if hasattr ( field , 'default' ) : value = field . default elif hasattr ( field , 'choices' ) : value = gen_choice ( field . choices ) elif isinstance ( field , OneToOn...
Automagically populate all required instance attributes .
19,760
def update_payload ( self , fields = None ) : values = self . get_values ( ) if fields is not None : values = { field : values [ field ] for field in fields } return _payload ( self . get_fields ( ) , values )
Create a payload of values that can be sent to the server .
19,761
def search_payload ( self , fields = None , query = None ) : if fields is None : fields = set ( self . get_values ( ) . keys ( ) ) if query is None : query = { } payload = { } fields_dict = self . get_fields ( ) for field in fields : value = getattr ( self , field ) if isinstance ( fields_dict [ field ] , OneToOneField...
Create a search query .
19,762
def search_normalize ( self , results ) : fields = self . get_fields ( ) normalized = [ ] for result in results : attrs = { } for field_name , field in fields . items ( ) : if isinstance ( field , OneToOneField ) : try : attrs [ field_name ] = _get_entity_id ( field_name , result ) except MissingValueError : pass elif ...
Normalize search results so they can be used to create new entities .
19,763
def search_filter ( entities , filters ) : if len ( entities ) == 0 : return entities fields = entities [ 0 ] . get_fields ( ) if not set ( filters ) . issubset ( fields ) : raise NoSuchFieldError ( 'Valid filters are {0}, but received {1} instead.' . format ( fields . keys ( ) , filters . keys ( ) ) ) for field_name i...
Read all entities and locally filter them .
19,764
def _get_config_file_path ( xdg_config_dir , xdg_config_file ) : for config_dir in BaseDirectory . load_config_paths ( xdg_config_dir ) : path = join ( config_dir , xdg_config_file ) if isfile ( path ) : return path raise ConfigFileError ( 'No configuration files could be located after searching for a file ' 'named "{0...
Search XDG_CONFIG_DIRS for a config file and return the first found .
19,765
def delete ( cls , label = 'default' , path = None ) : if path is None : path = _get_config_file_path ( cls . _xdg_config_dir , cls . _xdg_config_file ) cls . _file_lock . acquire ( ) try : with open ( path ) as config_file : config = json . load ( config_file ) del config [ label ] with open ( path , 'w' ) as config_f...
Delete a server configuration .
19,766
def get_labels ( cls , path = None ) : if path is None : path = _get_config_file_path ( cls . _xdg_config_dir , cls . _xdg_config_file ) with open ( path ) as config_file : return tuple ( json . load ( config_file ) . keys ( ) )
Get all server configuration labels .
19,767
def save ( self , label = 'default' , path = None ) : cfg = vars ( self ) if 'version' in cfg : cfg [ 'version' ] = str ( cfg [ 'version' ] ) if path is None : path = join ( BaseDirectory . save_config_path ( self . _xdg_config_dir ) , self . _xdg_config_file ) self . _file_lock . acquire ( ) try : try : with open ( pa...
Save the current connection configuration to a file .
19,768
def _log_request ( method , url , kwargs , data = None , params = None ) : logger . debug ( 'Making HTTP %s request to %s with %s, %s and %s.' , method , url , 'options {0}' . format ( kwargs ) if len ( kwargs ) > 0 else 'no options' , 'params {0}' . format ( params ) if params else 'no params' , 'data {0}' . format ( ...
Log out information about the arguments given .
19,769
def _log_response ( response ) : message = u'Received HTTP {0} response: {1}' . format ( response . status_code , response . text ) if response . status_code >= 400 : logger . warning ( message ) else : logger . debug ( message )
Log out information about a Request object .
19,770
def request ( method , url , ** kwargs ) : _set_content_type ( kwargs ) if _content_type_is_json ( kwargs ) and kwargs . get ( 'data' ) is not None : kwargs [ 'data' ] = dumps ( kwargs [ 'data' ] ) _log_request ( method , url , kwargs ) response = requests . request ( method , url , ** kwargs ) _log_response ( response...
A wrapper for requests . request .
19,771
def head ( url , ** kwargs ) : _set_content_type ( kwargs ) if _content_type_is_json ( kwargs ) and kwargs . get ( 'data' ) is not None : kwargs [ 'data' ] = dumps ( kwargs [ 'data' ] ) _log_request ( 'HEAD' , url , kwargs ) response = requests . head ( url , ** kwargs ) _log_response ( response ) return response
A wrapper for requests . head .
19,772
def post ( url , data = None , json = None , ** kwargs ) : _set_content_type ( kwargs ) if _content_type_is_json ( kwargs ) and data is not None : data = dumps ( data ) _log_request ( 'POST' , url , kwargs , data ) response = requests . post ( url , data , json , ** kwargs ) _log_response ( response ) return response
A wrapper for requests . post .
19,773
def put ( url , data = None , ** kwargs ) : _set_content_type ( kwargs ) if _content_type_is_json ( kwargs ) and data is not None : data = dumps ( data ) _log_request ( 'PUT' , url , kwargs , data ) response = requests . put ( url , data , ** kwargs ) _log_response ( response ) return response
A wrapper for requests . put . Sends a PUT request .
19,774
def _handle_response ( response , server_config , synchronous = False , timeout = None ) : response . raise_for_status ( ) if synchronous is True and response . status_code == ACCEPTED : return ForemanTask ( server_config , id = response . json ( ) [ 'id' ] ) . poll ( timeout = timeout ) if response . status_code == NO...
Handle a server s response in a typical fashion .
19,775
def create_missing ( self ) : super ( AuthSourceLDAP , self ) . create_missing ( ) if getattr ( self , 'onthefly_register' , False ) is True : for field in ( 'account_password' , 'attr_firstname' , 'attr_lastname' , 'attr_login' , 'attr_mail' ) : if not hasattr ( self , field ) : setattr ( self , field , self . _fields...
Possibly set several extra instance attributes .
19,776
def read ( self , entity = None , attrs = None , ignore = None , params = None ) : if attrs is None : attrs = self . update_json ( [ ] ) if ignore is None : ignore = set ( ) ignore . add ( 'account_password' ) return super ( AuthSourceLDAP , self ) . read ( entity , attrs , ignore , params )
Do not read the account_password attribute . Work around a bug .
19,777
def read ( self , entity = None , attrs = None , ignore = None , params = None ) : if attrs is None : attrs = self . read_json ( ) attrs [ 'search_' ] = attrs . pop ( 'search' ) attr = 'max_count' if ignore is None : ignore = set ( ) if attr not in ignore : attrs [ attr ] = DiscoveryRule ( self . _server_config , id = ...
Work around a bug . Rename search to search_ .
19,778
def read ( self , entity = None , attrs = None , ignore = None , params = None ) : if entity is None : entity = type ( self ) ( self . _server_config , usergroup = self . usergroup , ) if ignore is None : ignore = set ( ) ignore . add ( 'usergroup' ) if attrs is None : attrs = self . read_json ( ) attrs [ 'auth_source'...
Ignore usergroup from read and alter auth_source_ldap with auth_source
19,779
def run ( self , synchronous = True , ** kwargs ) : kwargs = kwargs . copy ( ) kwargs . update ( self . _server_config . get_client_kwargs ( ) ) if 'data' in kwargs : if 'job_template_id' not in kwargs [ 'data' ] and 'feature' not in kwargs [ 'data' ] : raise KeyError ( 'Provide either job_template_id or feature value'...
Helper to run existing job template
19,780
def read ( self , entity = None , attrs = None , ignore = None , params = None ) : if attrs is None : attrs = self . read_json ( params = params ) if ignore is None : ignore = set ( ) ignore . add ( 'template_inputs' ) entity = super ( JobTemplate , self ) . read ( entity = entity , attrs = attrs , ignore = ignore , pa...
Ignore the template inputs when initially reading the job template . Look up each TemplateInput entity separately and afterwords add them to the JobTemplate entity .
19,781
def upload ( self , filepath , filename = None ) : if not filename : filename = os . path . basename ( filepath ) content_upload = self . create ( ) try : offset = 0 content_chunk_size = 2 * 1024 * 1024 with open ( filepath , 'rb' ) as contentfile : chunk = contentfile . read ( content_chunk_size ) while len ( chunk ) ...
Upload content .
19,782
def read ( self , entity = None , attrs = None , ignore = None , params = None ) : if entity is None : entity = type ( self ) ( self . _server_config , content_view_filter = self . content_view_filter , ) if attrs is None : attrs = self . read_json ( ) if ignore is None : ignore = set ( ) ignore . add ( 'content_view_f...
Do not read certain fields .
19,783
def publish ( self , synchronous = True , ** kwargs ) : kwargs = kwargs . copy ( ) if 'data' in kwargs and 'id' not in kwargs [ 'data' ] : kwargs [ 'data' ] [ 'id' ] = self . id kwargs . update ( self . _server_config . get_client_kwargs ( ) ) response = client . post ( self . path ( 'publish' ) , ** kwargs ) return _h...
Helper for publishing an existing content view .
19,784
def delete_from_environment ( self , environment , synchronous = True ) : if isinstance ( environment , Environment ) : environment_id = environment . id else : environment_id = environment response = client . delete ( '{0}/environments/{1}' . format ( self . path ( ) , environment_id ) , ** self . _server_config . get...
Delete this content view version from an environment .
19,785
def add ( self , synchronous = True , ** kwargs ) : kwargs = kwargs . copy ( ) if 'data' not in kwargs : kwargs [ 'data' ] = dict ( ) if 'component_ids' not in kwargs [ 'data' ] : kwargs [ 'data' ] [ 'components' ] = [ _payload ( self . get_fields ( ) , self . get_values ( ) ) ] kwargs . update ( self . _server_config ...
Add provided Content View Component .
19,786
def read ( self , entity = None , attrs = None , ignore = None , params = None ) : if attrs is None : attrs = self . read_json ( ) attrs [ 'override' ] = attrs . pop ( 'override?' ) attrs [ 'unlimited' ] = attrs . pop ( 'unlimited?' ) return super ( Filter , self ) . read ( entity , attrs , ignore , params )
Deal with different named data returned from the server
19,787
def poll ( self , poll_rate = None , timeout = None ) : return _poll_task ( self . id , self . _server_config , poll_rate , timeout )
Return the status of a task or timeout .
19,788
def read ( self , entity = None , attrs = None , ignore = None , params = None ) : if ignore is None : ignore = set ( ) ignore . add ( 'root_pass' ) ignore . add ( 'kickstart_repository' ) if attrs is None : attrs = self . read_json ( ) attrs [ 'parent_id' ] = attrs . pop ( 'ancestry' ) version = _get_version ( self . ...
Deal with several bugs .
19,789
def delete_puppetclass ( self , synchronous = True , ** kwargs ) : kwargs = kwargs . copy ( ) kwargs . update ( self . _server_config . get_client_kwargs ( ) ) path = "{0}/{1}" . format ( self . path ( 'puppetclass_ids' ) , kwargs [ 'data' ] . pop ( 'puppetclass_id' ) ) return _handle_response ( client . delete ( path ...
Remove a Puppet class from host group
19,790
def owner_type ( self , value ) : self . _owner_type = value if value == 'User' : self . _fields [ 'owner' ] = entity_fields . OneToOneField ( User ) if hasattr ( self , 'owner' ) : self . owner = User ( self . _server_config , id = self . owner . id if isinstance ( self . owner , Entity ) else self . owner ) elif valu...
Set owner_type to the given value .
19,791
def get_values ( self ) : attrs = super ( Host , self ) . get_values ( ) if '_owner_type' in attrs and attrs [ '_owner_type' ] is not None : attrs [ 'owner_type' ] = attrs . pop ( '_owner_type' ) else : attrs . pop ( '_owner_type' ) return attrs
Correctly set the owner_type attribute .
19,792
def errata_applicability ( self , synchronous = True , ** kwargs ) : kwargs = kwargs . copy ( ) kwargs . update ( self . _server_config . get_client_kwargs ( ) ) response = client . put ( self . path ( 'errata/applicability' ) , ** kwargs ) return _handle_response ( response , self . _server_config , synchronous )
Force regenerate errata applicability
19,793
def read ( self , entity = None , attrs = None , ignore = None , params = None ) : if attrs is None : attrs = self . read_json ( ) if ignore is None : ignore = set ( ) if 'parameters' in attrs : attrs [ 'host_parameters_attributes' ] = attrs . pop ( 'parameters' ) else : ignore . add ( 'host_parameters_attributes' ) if...
Deal with oddly named and structured data returned by the server .
19,794
def create_payload ( self ) : payload = super ( LifecycleEnvironment , self ) . create_payload ( ) if ( _get_version ( self . _server_config ) < Version ( '6.1' ) and 'prior_id' in payload ) : payload [ 'prior' ] = payload . pop ( 'prior_id' ) return payload
Rename the payload key prior_id to prior .
19,795
def create_missing ( self ) : super ( LifecycleEnvironment , self ) . create_missing ( ) if ( self . name != 'Library' and not hasattr ( self , 'prior' ) ) : results = self . search ( { 'organization' } , { u'name' : u'Library' } ) if len ( results ) != 1 : raise APIResponseError ( u'Could not find the "Library" lifecy...
Automatically populate additional instance attributes .
19,796
def create_payload ( self ) : payload = super ( Media , self ) . create_payload ( ) if 'path_' in payload : payload [ 'path' ] = payload . pop ( 'path_' ) return { u'medium' : payload }
Wrap submitted data within an extra dict and rename path_ .
19,797
def create_payload ( self ) : payload = super ( OverrideValue , self ) . create_payload ( ) if hasattr ( self , 'smart_class_parameter' ) : del payload [ 'smart_class_parameter_id' ] if hasattr ( self , 'smart_variable' ) : del payload [ 'smart_variable_id' ] return payload
Remove smart_class_parameter_id or smart_variable_id
19,798
def read ( self , entity = None , attrs = None , ignore = None , params = None ) : if entity is None : entity = type ( self ) ( self . _server_config , ** { self . _parent_type : self . _parent_id } ) if ignore is None : ignore = set ( ) for field_name in self . _path_fields : ignore . add ( field_name ) return super (...
Ignore path related fields as they re never returned by the server and are only added to entity to be able to use proper path .
19,799
def search ( self , fields = None , query = None , filters = None ) : results = self . search_json ( fields , query ) [ 'results' ] results = self . search_normalize ( results ) entities = [ ] for result in results : sync_plan = result . get ( 'sync_plan' ) if sync_plan is not None : del result [ 'sync_plan' ] entity =...
Search for entities with missing attribute