idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
8,100 | def logout ( client ) : if not client . session_id : client . request_session ( ) concierge_request_header = client . construct_concierge_header ( url = ( "http://membersuite.com/contracts/IConciergeAPIService/" "Logout" ) ) logout_result = client . client . service . Logout ( _soapheaders = [ concierge_request_header ... | Log out the currently logged - in user . | 156 | 9 |
8,101 | def get_user_for_membersuite_entity ( membersuite_entity ) : user = None user_created = False # First, try to match on username. user_username = generate_username ( membersuite_entity ) try : user = User . objects . get ( username = user_username ) except User . DoesNotExist : pass # Next, try to match on email address... | Returns a User for membersuite_entity . | 196 | 10 |
8,102 | def add_validator ( self , validator ) : if not isinstance ( validator , AbstractValidator ) : err = 'Validator must be of type {}' . format ( AbstractValidator ) raise InvalidValidator ( err ) self . validators . append ( validator ) return self | Add validator to property | 62 | 5 |
8,103 | def filter ( self , value = None , model = None , context = None ) : if value is None : return value for filter_obj in self . filters : value = filter_obj . filter ( value = value , model = model , context = context if self . use_context else None ) return value | Sequentially applies all the filters to provided value | 64 | 9 |
8,104 | def validate ( self , value = None , model = None , context = None ) : errors = [ ] for validator in self . validators : if value is None and not isinstance ( validator , Required ) : continue error = validator . run ( value = value , model = model , context = context if self . use_context else None ) if error : errors... | Sequentially apply each validator to value and collect errors . | 85 | 12 |
8,105 | def filter_with_schema ( self , model = None , context = None ) : if model is None or self . schema is None : return self . _schema . filter ( model = model , context = context if self . use_context else None ) | Perform model filtering with schema | 55 | 6 |
8,106 | def validate_with_schema ( self , model = None , context = None ) : if self . _schema is None or model is None : return result = self . _schema . validate ( model = model , context = context if self . use_context else None ) return result | Perform model validation with schema | 61 | 6 |
8,107 | def filter_with_schema ( self , collection = None , context = None ) : if collection is None or self . schema is None : return try : for item in collection : self . _schema . filter ( model = item , context = context if self . use_context else None ) except TypeError : pass | Perform collection items filtering with schema | 67 | 7 |
8,108 | def validate_with_schema ( self , collection = None , context = None ) : if self . _schema is None or not collection : return result = [ ] try : for index , item in enumerate ( collection ) : item_result = self . _schema . validate ( model = item , context = context if self . use_context else None ) result . append ( i... | Validate each item in collection with our schema | 92 | 9 |
8,109 | def json_based_stable_hash ( obj ) : encoded_str = json . dumps ( obj = obj , skipkeys = False , ensure_ascii = False , check_circular = True , allow_nan = True , cls = None , indent = 0 , separators = ( ',' , ':' ) , default = None , sort_keys = True , ) . encode ( 'utf-8' ) return hashlib . sha256 ( encoded_str ) . h... | Computes a cross - kernel stable hash value for the given object . | 108 | 14 |
8,110 | def read_request_line ( self , request_line ) : request = self . __request_cls . parse_request_line ( self , request_line ) protocol_version = self . protocol_version ( ) if protocol_version == '0.9' : if request . method ( ) != 'GET' : raise Exception ( 'HTTP/0.9 standard violation' ) elif protocol_version == '1.0' or... | Read HTTP - request line | 131 | 5 |
8,111 | def metaclass ( * metaclasses ) : # type: (*type) -> Callable[[type], type] def _inner ( cls ) : # pragma pylint: disable=unused-variable metabases = tuple ( collections . OrderedDict ( # noqa: F841 ( c , None ) for c in ( metaclasses + ( type ( cls ) , ) ) ) . keys ( ) ) # pragma pylint: enable=unused-variable _Meta =... | Create the class using all metaclasses . | 165 | 9 |
8,112 | def get_attrition_in_years ( self ) : attrition_of_nets = self . itn . find ( "attritionOfNets" ) function = attrition_of_nets . attrib [ "function" ] if function != "step" : return None L = attrition_of_nets . attrib [ "L" ] return L | Function for the Basic UI | 75 | 5 |
8,113 | def add ( self , intervention , name = None ) : if self . et is None : return assert isinstance ( intervention , six . string_types ) et = ElementTree . fromstring ( intervention ) vector_pop = VectorPopIntervention ( et ) assert isinstance ( vector_pop . name , six . string_types ) if name is not None : assert isinsta... | Add an intervention to vectorPop section . intervention is either ElementTree or xml snippet | 125 | 16 |
8,114 | def add ( self , value ) : index = len ( self . __history ) self . __history . append ( value ) return index | Add new record to history . Record will be added to the end | 28 | 13 |
8,115 | def start_session ( self ) : self . __current_row = '' self . __history_mode = False self . __editable_history = deepcopy ( self . __history ) self . __prompt_show = True self . refresh_window ( ) | Start new session and prepare environment for new row editing process | 56 | 11 |
8,116 | def fin_session ( self ) : self . __prompt_show = False self . __history . add ( self . row ( ) ) self . exec ( self . row ( ) ) | Finalize current session | 40 | 4 |
8,117 | def data ( self , previous_data = False , prompt = False , console_row = False , console_row_to_cursor = False , console_row_from_cursor = False ) : result = '' if previous_data : result += self . __previous_data if prompt or console_row or console_row_to_cursor : result += self . console ( ) . prompt ( ) if console_ro... | Return output data . Flags specifies what data to append . If no flags was specified nul - length string returned | 186 | 22 |
8,118 | def write_data ( self , data , start_position = 0 ) : if len ( data ) > self . height ( ) : raise ValueError ( 'Data too long (too many strings)' ) for i in range ( len ( data ) ) : self . write_line ( start_position + i , data [ i ] ) | Write data from the specified line | 70 | 6 |
8,119 | def write_feedback ( self , feedback , cr = True ) : self . __previous_data += feedback if cr is True : self . __previous_data += '\n' | Store feedback . Keep specified feedback as previous output | 41 | 9 |
8,120 | def refresh ( self , prompt_show = True ) : self . clear ( ) for drawer in self . __drawers : if drawer . suitable ( self , prompt_show = prompt_show ) : drawer . draw ( self , prompt_show = prompt_show ) return raise RuntimeError ( 'No suitable drawer was found' ) | Refresh current window . Clear current window and redraw it with one of drawers | 69 | 17 |
8,121 | def is_dir ( path ) : try : return path . expanduser ( ) . absolute ( ) . is_dir ( ) except AttributeError : return os . path . isdir ( os . path . abspath ( os . path . expanduser ( str ( path ) ) ) ) | Determine if a Path or string is a directory on the file system . | 61 | 16 |
8,122 | def is_file ( path ) : try : return path . expanduser ( ) . absolute ( ) . is_file ( ) except AttributeError : return os . path . isfile ( os . path . abspath ( os . path . expanduser ( str ( path ) ) ) ) | Determine if a Path or string is a file on the file system . | 61 | 16 |
8,123 | def exists ( path ) : try : return path . expanduser ( ) . absolute ( ) . exists ( ) except AttributeError : return os . path . exists ( os . path . abspath ( os . path . expanduser ( str ( path ) ) ) ) | Determine if a Path or string is an existing path on the file system . | 56 | 17 |
8,124 | def enableHook ( self , msgObj ) : self . killListIdx = len ( qte_global . kill_list ) - 2 self . qteMain . qtesigKeyseqComplete . connect ( self . disableHook ) | Enable yank - pop . | 52 | 6 |
8,125 | def cursorPositionChangedEvent ( self ) : # Determine the sender and cursor position. qteWidget = self . sender ( ) tc = qteWidget . textCursor ( ) origin = tc . position ( ) # Remove all the highlighting. Since this will move the # cursor, first disconnect this very routine to avoid an # infinite recursion. qteWidget ... | Update the highlighting . | 605 | 4 |
8,126 | def qteRemoveHighlighting ( self , widgetObj ) : # Retrieve the widget specific macro data. data = self . qteMacroData ( widgetObj ) if not data : return # If the data structure is empty then no previously # highlighted characters exist in this particular widget, so # do nothing. if not data . matchingPositions : retur... | Remove the highlighting from previously highlighted characters . | 166 | 8 |
8,127 | def highlightCharacters ( self , widgetObj , setPos , colorCode , fontWeight , charFormat = None ) : # Get the text cursor and character format. textCursor = widgetObj . textCursor ( ) oldPos = textCursor . position ( ) retVal = [ ] # Change the character formats of all the characters placed at # the positions ``setPos... | Change the character format of one or more characters . | 497 | 10 |
8,128 | def scenarios ( self , generate_seed = False ) : seed = prime_numbers ( 1000 ) sweeps_all = self . experiment [ "sweeps" ] . keys ( ) if "combinations" in self . experiment : if isinstance ( self . experiment [ "combinations" ] , list ) : # For backward compatibility with experiments1-4s combinations_in_experiment = { ... | Generator function . Spits out scenarios for this experiment | 867 | 11 |
8,129 | def lvm_info ( self , name = None ) : cmd = [ ] if self . sudo ( ) is False else [ 'sudo' ] cmd . extend ( [ self . command ( ) , '-c' ] ) if name is not None : cmd . append ( name ) output = subprocess . check_output ( cmd , timeout = self . cmd_timeout ( ) ) output = output . decode ( ) result = [ ] fields_count = se... | Call a program | 179 | 3 |
8,130 | def uuid ( self ) : uuid_file = '/sys/block/%s/dm/uuid' % os . path . basename ( os . path . realpath ( self . volume_path ( ) ) ) lv_uuid = open ( uuid_file ) . read ( ) . strip ( ) if lv_uuid . startswith ( 'LVM-' ) is True : return lv_uuid [ 4 : ] return lv_uuid | Return UUID of logical volume | 105 | 6 |
8,131 | def create_snapshot ( self , snapshot_size , snapshot_suffix ) : size_extent = math . ceil ( self . extents_count ( ) * snapshot_size ) size_kb = self . volume_group ( ) . extent_size ( ) * size_extent snapshot_name = self . volume_name ( ) + snapshot_suffix lvcreate_cmd = [ 'sudo' ] if self . lvm_command ( ) . sudo ( ... | Create snapshot for this logical volume . | 238 | 7 |
8,132 | def remove_volume ( self ) : lvremove_cmd = [ 'sudo' ] if self . lvm_command ( ) . sudo ( ) is True else [ ] lvremove_cmd . extend ( [ 'lvremove' , '-f' , self . volume_path ( ) ] ) subprocess . check_output ( lvremove_cmd , timeout = self . __class__ . __lvm_snapshot_remove_cmd_timeout__ ) | Remove this volume | 100 | 3 |
8,133 | def logical_volume ( cls , file_path , sudo = False ) : mp = WMountPoint . mount_point ( file_path ) if mp is not None : name_file = '/sys/block/%s/dm/name' % mp . device_name ( ) if os . path . exists ( name_file ) : lv_path = '/dev/mapper/%s' % open ( name_file ) . read ( ) . strip ( ) return WLogicalVolume ( lv_path... | Return logical volume that stores the given path | 117 | 8 |
8,134 | def write ( self , b ) : self . __buffer += bytes ( b ) bytes_written = 0 while len ( self . __buffer ) >= self . __cipher_block_size : io . BufferedWriter . write ( self , self . __cipher . encrypt_block ( self . __buffer [ : self . __cipher_block_size ] ) ) self . __buffer = self . __buffer [ self . __cipher_block_si... | Encrypt and write data | 118 | 5 |
8,135 | def reset_component ( self , component ) : if isinstance ( component , str ) is True : component = WURI . Component ( component ) self . __components [ component ] = None | Unset component in this URI | 40 | 6 |
8,136 | def parse ( cls , uri ) : uri_components = urlsplit ( uri ) adapter_fn = lambda x : x if x is not None and ( isinstance ( x , str ) is False or len ( x ) ) > 0 else None return cls ( scheme = adapter_fn ( uri_components . scheme ) , username = adapter_fn ( uri_components . username ) , password = adapter_fn ( uri_compo... | Parse URI - string and return WURI object | 185 | 10 |
8,137 | def add_parameter ( self , name , value = None ) : if name not in self . __query : self . __query [ name ] = [ value ] else : self . __query [ name ] . append ( value ) | Add new parameter value to this query . New value will be appended to previously added values . | 49 | 19 |
8,138 | def remove_parameter ( self , name ) : if name in self . __query : self . __query . pop ( name ) | Remove the specified parameter from this query | 28 | 7 |
8,139 | def parse ( cls , query_str ) : parsed_query = parse_qs ( query_str , keep_blank_values = True , strict_parsing = True ) result = cls ( ) for parameter_name in parsed_query . keys ( ) : for parameter_value in parsed_query [ parameter_name ] : result . add_parameter ( parameter_name , parameter_value if len ( parameter_... | Parse string that represent query component from URI | 100 | 9 |
8,140 | def add_specification ( self , specification ) : name = specification . name ( ) if name in self . __specs : raise ValueError ( 'WStrictURIQuery object already has specification for parameter "%s" ' % name ) self . __specs [ name ] = specification | Add a new query parameter specification . If this object already has a specification for the specified parameter - exception is raised . No checks for the specified or any parameter are made regarding specification appending | 60 | 37 |
8,141 | def remove_specification ( self , name ) : if name in self . __specs : self . __specs . pop ( name ) | Remove a specification that matches a query parameter . No checks for the specified or any parameter are made regarding specification removing | 30 | 22 |
8,142 | def replace_parameter ( self , name , value = None ) : spec = self . __specs [ name ] if name in self . __specs else None if self . extra_parameters ( ) is False and spec is None : raise ValueError ( 'Extra parameters are forbidden for this WStrictURIQuery object' ) if spec is not None and spec . nullable ( ) is False ... | Replace a query parameter values with a new value . If a new value does not match current specifications then exception is raised | 178 | 24 |
8,143 | def remove_parameter ( self , name ) : spec = self . __specs [ name ] if name in self . __specs else None if spec is not None and spec . optional ( ) is False : raise ValueError ( 'Unable to remove a required parameter "%s"' % name ) WURIQuery . remove_parameter ( self , name ) | Remove parameter from this query . If a parameter is mandatory then exception is raised | 76 | 15 |
8,144 | def validate ( self , uri ) : requirement = self . requirement ( ) uri_component = uri . component ( self . component ( ) ) if uri_component is None : return requirement != WURIComponentVerifier . Requirement . required if requirement == WURIComponentVerifier . Requirement . unsupported : return False re_obj = self . r... | Check an URI for compatibility with this specification . Return True if the URI is compatible . | 109 | 17 |
8,145 | def validate ( self , uri ) : if WURIComponentVerifier . validate ( self , uri ) is False : return False try : WStrictURIQuery ( WURIQuery . parse ( uri . component ( self . component ( ) ) ) , * self . __specs , extra_parameters = self . __extra_parameters ) except ValueError : return False return True | Check that an query part of an URI is compatible with this descriptor . Return True if the URI is compatible . | 85 | 22 |
8,146 | def is_compatible ( self , uri ) : for component , component_value in uri : if self . verifier ( component ) . validate ( uri ) is False : return False return True | Check if URI is compatible with this specification . Compatible URI has scheme name that matches specification scheme name has all of the required components does not have unsupported components and may have optional components | 42 | 36 |
8,147 | def handler ( self , scheme_name = None ) : if scheme_name is None : return self . __default_handler_cls for handler in self . __handlers_cls : if handler . scheme_specification ( ) . scheme_name ( ) == scheme_name : return handler | Return handler which scheme name matches the specified one | 63 | 9 |
8,148 | def open ( self , uri , * * kwargs ) : handler = self . handler ( uri . scheme ( ) ) if handler is None : raise WSchemeCollection . NoHandlerFound ( uri ) if uri . scheme ( ) is None : uri . component ( 'scheme' , handler . scheme_specification ( ) . scheme_name ( ) ) if handler . scheme_specification ( ) . is_compatib... | Return handler instance that matches the specified URI . WSchemeCollection . NoHandlerFound and WSchemeCollection . SchemeIncompatible may be raised . | 130 | 30 |
8,149 | def loadFile ( self , fileName ) : self . fileName = fileName self . qteWeb . load ( QtCore . QUrl ( fileName ) ) | Load the URL fileName . | 35 | 6 |
8,150 | def render_to_response ( self , context , * * response_kwargs ) : context [ "ajax_form_id" ] = self . ajax_form_id # context["base_template"] = "towel_bootstrap/modal.html" return self . response_class ( request = self . request , template = self . get_template_names ( ) , context = context , * * response_kwargs ) | Returns a response with a template rendered with the given context . | 97 | 12 |
8,151 | def to_python ( self , value , resource ) : if value is None : return self . _transform ( value ) if isinstance ( value , six . text_type ) : return self . _transform ( value ) if self . encoding is None and isinstance ( value , ( six . text_type , six . binary_type ) ) : return self . _transform ( value ) if self . en... | Converts to unicode if self . encoding ! = None otherwise returns input without attempting to decode | 131 | 19 |
8,152 | def to_python ( self , value , resource ) : if isinstance ( value , dict ) : d = { self . aliases . get ( k , k ) : self . to_python ( v , resource ) if isinstance ( v , ( dict , list ) ) else v for k , v in six . iteritems ( value ) } return type ( self . class_name , ( ) , d ) elif isinstance ( value , list ) : retur... | Dictionary to Python object | 131 | 5 |
8,153 | def to_value ( self , obj , resource , visited = set ( ) ) : if id ( obj ) in visited : raise ValueError ( 'Circular reference detected when attempting to serialize object' ) if isinstance ( obj , ( list , tuple , set ) ) : return [ self . to_value ( x , resource ) if hasattr ( x , '__dict__' ) else x for x in obj ] el... | Python object to dictionary | 220 | 4 |
8,154 | def hello_message ( self , invert_hello = False ) : if invert_hello is False : return self . __gouverneur_message hello_message = [ ] for i in range ( len ( self . __gouverneur_message ) - 1 , - 1 , - 1 ) : hello_message . append ( self . __gouverneur_message [ i ] ) return bytes ( hello_message ) | Return message header . | 92 | 4 |
8,155 | def _message_address_parse ( self , message , invert_hello = False ) : message_header = self . hello_message ( invert_hello = invert_hello ) if message [ : len ( message_header ) ] != message_header : raise ValueError ( 'Invalid message header' ) message = message [ len ( message_header ) : ] message_parts = message . ... | Read address from beacon message . If no address is specified then nullable WIPV4SocketInfo returns | 253 | 21 |
8,156 | def cipher ( self ) : #cipher = pyAES.new(*self.mode().aes_args(), **self.mode().aes_kwargs()) cipher = Cipher ( * self . mode ( ) . aes_args ( ) , * * self . mode ( ) . aes_kwargs ( ) ) return WAES . WAESCipher ( cipher ) | Generate AES - cipher | 81 | 5 |
8,157 | def encrypt ( self , data ) : padding = self . mode ( ) . padding ( ) if padding is not None : data = padding . pad ( data , WAESMode . __data_padding_length__ ) return self . cipher ( ) . encrypt_block ( data ) | Encrypt the given data with cipher that is got from AES . cipher call . | 58 | 16 |
8,158 | def decrypt ( self , data , decode = False ) : #result = self.cipher().decrypt(data) result = self . cipher ( ) . decrypt_block ( data ) padding = self . mode ( ) . padding ( ) if padding is not None : result = padding . reverse_pad ( result , WAESMode . __data_padding_length__ ) return result . decode ( ) if decode el... | Decrypt the given data with cipher that is got from AES . cipher call . | 88 | 16 |
8,159 | def thread_tracker_exception ( self , raised_exception ) : print ( 'Thread tracker execution was stopped by the exception. Exception: %s' % str ( raised_exception ) ) print ( 'Traceback:' ) print ( traceback . format_exc ( ) ) | Method is called whenever an exception is raised during registering a event | 62 | 12 |
8,160 | def __store_record ( self , record ) : if isinstance ( record , WSimpleTrackerStorage . Record ) is False : raise TypeError ( 'Invalid record type was' ) limit = self . record_limit ( ) if limit is not None and len ( self . __registry ) >= limit : self . __registry . pop ( 0 ) self . __registry . append ( record ) | Save record in a internal storage | 84 | 6 |
8,161 | def put_nested_val ( dict_obj , key_tuple , value ) : current_dict = dict_obj for key in key_tuple [ : - 1 ] : try : current_dict = current_dict [ key ] except KeyError : current_dict [ key ] = { } current_dict = current_dict [ key ] current_dict [ key_tuple [ - 1 ] ] = value | Put a value into nested dicts by the order of the given keys tuple . | 90 | 16 |
8,162 | def get_alternative_nested_val ( key_tuple , dict_obj ) : # print('key_tuple: {}'.format(key_tuple)) # print('dict_obj: {}'.format(dict_obj)) top_keys = key_tuple [ 0 ] if isinstance ( key_tuple [ 0 ] , ( list , tuple ) ) else [ key_tuple [ 0 ] ] for key in top_keys : try : if len ( key_tuple ) < 2 : return dict_obj [ ... | Return a value from nested dicts by any path in the given keys tuple . | 162 | 16 |
8,163 | def subdict_by_keys ( dict_obj , keys ) : return { k : dict_obj [ k ] for k in set ( keys ) . intersection ( dict_obj . keys ( ) ) } | Returns a sub - dict composed solely of the given keys . | 44 | 12 |
8,164 | def add_to_dict_val_set ( dict_obj , key , val ) : try : dict_obj [ key ] . add ( val ) except KeyError : dict_obj [ key ] = set ( [ val ] ) | Adds the given val to the set mapped by the given key . If the key is missing from the dict the given mapping is added . | 50 | 27 |
8,165 | def add_many_to_dict_val_set ( dict_obj , key , val_list ) : try : dict_obj [ key ] . update ( val_list ) except KeyError : dict_obj [ key ] = set ( val_list ) | Adds the given value list to the set mapped by the given key . If the key is missing from the dict the given mapping is added . | 56 | 28 |
8,166 | def add_many_to_dict_val_list ( dict_obj , key , val_list ) : try : dict_obj [ key ] . extend ( val_list ) except KeyError : dict_obj [ key ] = list ( val_list ) | Adds the given value list to the list mapped by the given key . If the key is missing from the dict the given mapping is added . | 56 | 28 |
8,167 | def get_keys_of_max_n ( dict_obj , n ) : return sorted ( [ item [ 0 ] for item in sorted ( dict_obj . items ( ) , key = lambda item : item [ 1 ] , reverse = True ) [ : n ] ] ) | Returns the keys that maps to the top n max values in the given dict . | 59 | 16 |
8,168 | def deep_merge_dict ( base , priority ) : if not isinstance ( base , dict ) or not isinstance ( priority , dict ) : return priority result = copy . deepcopy ( base ) for key in priority . keys ( ) : if key in base : result [ key ] = deep_merge_dict ( base [ key ] , priority [ key ] ) else : result [ key ] = priority [ ... | Recursively merges the two given dicts into a single dict . | 92 | 15 |
8,169 | def norm_int_dict ( int_dict ) : norm_dict = int_dict . copy ( ) val_sum = sum ( norm_dict . values ( ) ) for key in norm_dict : norm_dict [ key ] = norm_dict [ key ] / val_sum return norm_dict | Normalizes values in the given dict with int values . | 65 | 11 |
8,170 | def sum_num_dicts ( dicts , normalize = False ) : sum_dict = { } for dicti in dicts : for key in dicti : sum_dict [ key ] = sum_dict . get ( key , 0 ) + dicti [ key ] if normalize : return norm_int_dict ( sum_dict ) return sum_dict | Sums the given dicts into a single dict mapping each key to the sum of its mappings in all given dicts . | 78 | 26 |
8,171 | def reverse_dict ( dict_obj ) : new_dict = { } for key in dict_obj : add_to_dict_val_set ( dict_obj = new_dict , key = dict_obj [ key ] , val = key ) for key in new_dict : new_dict [ key ] = sorted ( new_dict [ key ] , reverse = False ) return new_dict | Reverse a dict so each value in it maps to a sorted list of its keys . | 85 | 19 |
8,172 | def reverse_dict_partial ( dict_obj ) : new_dict = { } for key in dict_obj : new_dict [ dict_obj [ key ] ] = key return new_dict | Reverse a dict so each value in it maps to one of its keys . | 42 | 17 |
8,173 | def reverse_list_valued_dict ( dict_obj ) : new_dict = { } for key in dict_obj : for element in dict_obj [ key ] : new_dict [ element ] = key return new_dict | Reverse a list - valued dict so each element in a list maps to its key . | 49 | 19 |
8,174 | def flatten_dict ( dict_obj , separator = '.' , flatten_lists = False ) : reducer = _get_key_reducer ( separator ) flat = { } def _flatten_key_val ( key , val , parent ) : flat_key = reducer ( parent , key ) try : _flatten ( val , flat_key ) except TypeError : flat [ flat_key ] = val def _flatten ( d , parent = None ) ... | Flattens the given dict into a single - level dict with flattend keys . | 191 | 17 |
8,175 | def pprint_int_dict ( int_dict , indent = 4 , descending = False ) : sorted_tup = sorted ( int_dict . items ( ) , key = lambda x : x [ 1 ] ) if descending : sorted_tup . reverse ( ) print ( '{' ) for tup in sorted_tup : print ( '{}{}: {}' . format ( ' ' * indent , tup [ 0 ] , tup [ 1 ] ) ) print ( '}' ) | Prints the given dict with int values in a nice way . | 107 | 13 |
8,176 | def key_value_nested_generator ( dict_obj ) : for key , value in dict_obj . items ( ) : if isinstance ( value , dict ) : for key , value in key_value_nested_generator ( value ) : yield key , value else : yield key , value | Recursively iterate over key - value pairs of nested dictionaries . | 66 | 15 |
8,177 | def key_tuple_value_nested_generator ( dict_obj ) : for key , value in dict_obj . items ( ) : if isinstance ( value , dict ) : for nested_key , value in key_tuple_value_nested_generator ( value ) : yield tuple ( [ key ] ) + nested_key , value else : yield tuple ( [ key ] ) , value | Recursively iterate over key - tuple - value pairs of nested dictionaries . | 88 | 17 |
8,178 | def register ( self ) : group = cfg . OptGroup ( self . group_name , title = "HNV (Hyper-V Network Virtualization) Options" ) self . _config . register_group ( group ) self . _config . register_opts ( self . _options , group = group ) | Register the current options to the global ConfigOpts object . | 66 | 12 |
8,179 | def _language_exclusions ( stem : LanguageStemRange , exclusions : List [ ShExDocParser . LanguageExclusionContext ] ) -> None : for excl in exclusions : excl_langtag = LANGTAG ( excl . LANGTAG ( ) . getText ( ) [ 1 : ] ) stem . exclusions . append ( LanguageStem ( excl_langtag ) if excl . STEM_MARK ( ) else excl_langt... | languageExclusion = - LANGTAG STEM_MARK? | 102 | 13 |
8,180 | def create_thumbnail ( self , image , geometry , upscale = True , crop = None , colorspace = 'RGB' ) : image = self . colorspace ( image , colorspace ) image = self . scale ( image , geometry , upscale , crop ) image = self . crop ( image , geometry , crop ) return image | This serves as a really basic example of a thumbnailing method . You may want to implement your own logic but this will work for simple cases . | 68 | 30 |
8,181 | def get_tokens ( self , * , payer_id , credit_card_token_id , start_date , end_date ) : payload = { "language" : self . client . language . value , "command" : PaymentCommand . GET_TOKENS . value , "merchant" : { "apiLogin" : self . client . api_login , "apiKey" : self . client . api_key } , "creditCardTokenInformation... | With this functionality you can query previously the Credit Cards Token . | 224 | 12 |
8,182 | def remove_token ( self , * , payer_id , credit_card_token_id ) : payload = { "language" : self . client . language . value , "command" : PaymentCommand . REMOVE_TOKEN . value , "merchant" : { "apiLogin" : self . client . api_login , "apiKey" : self . client . api_key } , "removeCreditCardToken" : { "payerId" : payer_i... | This feature allows you to delete a tokenized credit card register . | 149 | 13 |
8,183 | def set_file_path ( self , filePath ) : if filePath is not None : assert isinstance ( filePath , basestring ) , "filePath must be None or string" filePath = str ( filePath ) self . __filePath = filePath | Set the file path that needs to be locked . | 57 | 10 |
8,184 | def set_lock_pass ( self , lockPass ) : assert isinstance ( lockPass , basestring ) , "lockPass must be string" lockPass = str ( lockPass ) assert '\n' not in lockPass , "lockPass must be not contain a new line" self . __lockPass = lockPass | Set the locking pass | 69 | 4 |
8,185 | def set_lock_path ( self , lockPath ) : if lockPath is not None : assert isinstance ( lockPath , basestring ) , "lockPath must be None or string" lockPath = str ( lockPath ) self . __lockPath = lockPath if self . __lockPath is None : if self . __filePath is None : self . __lockPath = os . path . join ( os . getcwd ( ) ... | Set the managing lock file path . | 131 | 7 |
8,186 | def set_timeout ( self , timeout ) : try : timeout = float ( timeout ) assert timeout >= 0 assert timeout >= self . __wait except : raise Exception ( 'timeout must be a positive number bigger than wait' ) self . __timeout = timeout | set the timeout limit . | 52 | 5 |
8,187 | def set_wait ( self , wait ) : try : wait = float ( wait ) assert wait >= 0 except : raise Exception ( 'wait must be a positive number' ) self . __wait = wait | set the waiting time . | 42 | 5 |
8,188 | def set_dead_lock ( self , deadLock ) : try : deadLock = float ( deadLock ) assert deadLock >= 0 except : raise Exception ( 'deadLock must be a positive number' ) self . __deadLock = deadLock | Set the dead lock time . | 51 | 6 |
8,189 | def release_lock ( self , verbose = VERBOSE , raiseError = RAISE_ERROR ) : if not os . path . isfile ( self . __lockPath ) : released = True code = 0 else : try : with open ( self . __lockPath , 'rb' ) as fd : lock = fd . readlines ( ) except Exception as err : code = Exception ( "Unable to read release lock file '%s' ... | Release the lock when set and close file descriptor if opened . | 438 | 12 |
8,190 | def import_bert ( self , filename , * * kwargs ) : timestep = kwargs . get ( 'timestep' , None ) if 'timestep' in kwargs : del ( kwargs [ 'timestep' ] ) self . logger . info ( 'Unified data format (BERT/pyGIMLi) file import' ) with LogDataChanges ( self , filter_action = 'import' , filter_query = os . path . basename (... | BERT . ohm file import | 213 | 7 |
8,191 | def to_ip ( self ) : if 'chargeability' in self . data . columns : tdip = reda . TDIP ( data = self . data ) else : raise Exception ( 'Missing column "chargeability"' ) return tdip | Return of copy of the data inside a TDIP container | 51 | 11 |
8,192 | def sub_filter ( self , subset , filter , inplace = True ) : # build the full query full_query = '' . join ( ( 'not (' , subset , ') or not (' , filter , ')' ) ) with LogDataChanges ( self , filter_action = 'filter' , filter_query = filter ) : result = self . data . query ( full_query , inplace = inplace ) return resul... | Apply a filter to subset of the data | 91 | 8 |
8,193 | def filter ( self , query , inplace = True ) : with LogDataChanges ( self , filter_action = 'filter' , filter_query = query ) : result = self . data . query ( 'not ({0})' . format ( query ) , inplace = inplace , ) return result | Use a query statement to filter data . Note that you specify the data to be removed! | 64 | 18 |
8,194 | def compute_K_analytical ( self , spacing ) : K = redaK . compute_K_analytical ( self . data , spacing = spacing ) self . data = redaK . apply_K ( self . data , K ) redafixK . fix_sign_with_K ( self . data ) | Compute geometrical factors over the homogeneous half - space with a constant electrode spacing | 69 | 18 |
8,195 | def pseudosection ( self , column = 'r' , filename = None , log10 = False , * * kwargs ) : fig , ax , cb = PS . plot_pseudosection_type2 ( self . data , column = column , log10 = log10 , * * kwargs ) if filename is not None : fig . savefig ( filename , dpi = 300 ) return fig , ax , cb | Plot a pseudosection of the given column . Note that this function only works with dipole - dipole data at the moment . | 93 | 27 |
8,196 | def histogram ( self , column = 'r' , filename = None , log10 = False , * * kwargs ) : return_dict = HS . plot_histograms ( self . data , column ) if filename is not None : return_dict [ 'all' ] . savefig ( filename , dpi = 300 ) return return_dict | Plot a histogram of one data column | 74 | 8 |
8,197 | def delete_measurements ( self , row_or_rows ) : self . data . drop ( self . data . index [ row_or_rows ] , inplace = True ) self . data = self . data . reset_index ( ) | Delete one or more measurements by index of the DataFrame . | 53 | 12 |
8,198 | def get_image ( self , source ) : buf = StringIO ( source . read ( ) ) return Image . open ( buf ) | Given a file - like object loads it up into a PIL . Image object and returns it . | 28 | 20 |
8,199 | def is_valid_image ( self , raw_data ) : buf = StringIO ( raw_data ) try : trial_image = Image . open ( buf ) trial_image . verify ( ) except Exception : # TODO: Get more specific with this exception handling. return False return True | Checks if the supplied raw data is valid image data . | 61 | 12 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.