idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
14,300 | def find_and_parse_config ( config , default_config = 'default.yaml' ) : def load_config ( path ) : if os . path . isfile ( path ) : with open ( path , 'r' ) as f : config_dict_ = yaml . load ( f ) return config_dict_ config_path = find_file ( config ) default_path = find_file ( default_config ) config = load_config ( config_path ) default_config = load_config ( default_path ) if config is None and default_config is None : raise ValueError ( 'Both config and default_config return None' ) if config is None : config_dict = default_config elif default_config is None : config_dict = config else : config_dict = merge ( default_config , config ) return config_dict | Finds the service configuration file and parses it . Checks also a directory called default to check for default configuration values that will be overwritten by the actual configuration found on given path . | 184 | 37 |
14,301 | def parse ( s , subs ) : if len ( subs ) == 0 : return [ ] points = [ ] requests = _tokenize_request ( s ) if len ( requests ) == 1 and requests [ 0 ] . type_ == _Request . Type . OFFSET : return _offset_subtitles ( requests [ 0 ] , subs ) return _sync_subtitles ( requests , subs ) | Parses a given string and creates a list of SyncPoints . | 85 | 14 |
14,302 | def full_name_natural_split ( full_name ) : parts = full_name . strip ( ) . split ( ' ' ) first_name = "" if parts : first_name = parts . pop ( 0 ) if first_name . lower ( ) == "el" and parts : first_name += " " + parts . pop ( 0 ) last_name = "" if parts : last_name = parts . pop ( ) if ( last_name . lower ( ) == 'i' or last_name . lower ( ) == 'ii' or last_name . lower ( ) == 'iii' and parts ) : last_name = parts . pop ( ) + " " + last_name middle_initials = "" for middle_name in parts : if middle_name : middle_initials += middle_name [ 0 ] return first_name , middle_initials , last_name | This function splits a full name into a natural first name last name and middle initials . | 191 | 17 |
14,303 | def _get_xml_value ( value ) : retval = [ ] if isinstance ( value , dict ) : for key , value in value . iteritems ( ) : retval . append ( '<' + xml_escape ( str ( key ) ) + '>' ) retval . append ( _get_xml_value ( value ) ) retval . append ( '</' + xml_escape ( str ( key ) ) + '>' ) elif isinstance ( value , list ) : for key , value in enumerate ( value ) : retval . append ( '<child order="' + xml_escape ( str ( key ) ) + '">' ) retval . append ( _get_xml_value ( value ) ) retval . append ( '</child>' ) elif isinstance ( value , bool ) : retval . append ( xml_escape ( str ( value ) . lower ( ) ) ) elif isinstance ( value , unicode ) : retval . append ( xml_escape ( value . encode ( 'utf-8' ) ) ) else : retval . append ( xml_escape ( str ( value ) ) ) return "" . join ( retval ) | Convert an individual value to an XML string . Calls itself recursively for dictionaries and lists . | 257 | 21 |
14,304 | def fetch_changes ( repo_path , up_commit = 'master' ) : last_up_commit = None prevcwd = os . getcwd ( ) try : gitexe = 'git' os . chdir ( repo_path ) old_sources_timestamp = sources_latest_timestamp ( '.' ) shell_command ( [ gitexe , 'pull' ] ) last_up_commit = subprocess . check_output ( [ 'git' , 'rev-parse' , 'HEAD' ] ) shell_command ( [ gitexe , 'checkout' , up_commit ] ) up_commit = subprocess . check_output ( [ 'git' , 'rev-parse' , 'HEAD' ] ) new_sources_timestamp = sources_latest_timestamp ( '.' ) if old_sources_timestamp < new_sources_timestamp : with open ( '.timestamp' , 'w' ) as up_commit_file : up_commit_file . write ( up_commit ) finally : os . chdir ( prevcwd ) return last_up_commit , up_commit | Fetch latest changes from stage and touch . timestamp if any python sources have been modified . | 248 | 18 |
14,305 | def migrate_all ( ) : if 'south' in settings . INSTALLED_APPS : return _south_migrate_all ( ) from django . core . management . commands import makemigrations , migrate schema_args = [ sys . executable , 'makemigrations' ] for app in settings . INSTALLED_APPS : if not app . startswith ( 'django' ) : schema_args += [ app ] schema_cmd = makemigrations . Command ( ) schema_cmd . run_from_argv ( schema_args ) migrate_cmd = migrate . Command ( ) sys . stderr . write ( "MIGRATE ALL!\n" ) return migrate_cmd . run_from_argv ( [ sys . executable , 'migrate' ] ) | Create schema migrations for all apps specified in INSTALLED_APPS then run a migrate command . | 174 | 21 |
14,306 | def add ( self , username , user_api , filename = None ) : keys = API . __get_keys ( filename ) user = user_api . find ( username ) [ 0 ] distinguished_name = user . entry_dn if 'ldapPublicKey' not in user . objectClass : raise ldap3 . core . exceptions . LDAPNoSuchAttributeResult ( 'LDAP Public Key Object Class not found. ' + 'Please ensure user was created correctly.' ) else : for key in list ( set ( keys ) ) : # prevents duplicate insertion print ( key ) try : SSHKey ( key ) . parse ( ) except Exception as err : raise err from None else : operation = { 'sshPublicKey' : [ ( ldap3 . MODIFY_ADD , [ key ] ) ] } self . client . modify ( distinguished_name , operation ) | Add SSH public key to a user s profile . | 184 | 10 |
14,307 | def remove ( self , username , user_api , filename = None , force = False ) : self . keys = API . __get_keys ( filename ) self . username = username user = user_api . find ( username ) [ 0 ] if not force : # pragma: no cover self . __confirm ( ) for key in self . __delete_keys ( ) : operation = { 'sshPublicKey' : [ ( ldap3 . MODIFY_DELETE , [ key ] ) ] } self . client . modify ( user . entry_dn , operation ) | Remove specified SSH public key from specified user . | 124 | 9 |
14,308 | def get_keys_from_ldap ( self , username = None ) : result_dict = { } filter = [ '(sshPublicKey=*)' ] if username is not None : filter . append ( '(uid={})' . format ( username ) ) attributes = [ 'uid' , 'sshPublicKey' ] results = self . client . search ( filter , attributes ) for result in results : result_dict [ result . uid . value ] = result . sshPublicKey . values return result_dict | Fetch keys from ldap . | 108 | 8 |
14,309 | def add ( config , username , filename ) : try : client = Client ( ) client . prepare_connection ( ) user_api = UserApi ( client ) key_api = API ( client ) key_api . add ( username , user_api , filename ) except ( ldap3 . core . exceptions . LDAPNoSuchAttributeResult , ldap_tools . exceptions . InvalidResult , ldap3 . core . exceptions . LDAPAttributeOrValueExistsResult ) as err : # pragma: no cover print ( '{}: {}' . format ( type ( err ) , err . args [ 0 ] ) ) except Exception as err : # pragma: no cover raise err from None | Add user s SSH public key to their LDAP entry . | 150 | 12 |
14,310 | def remove ( config , username , filename , force ) : client = Client ( ) client . prepare_connection ( ) user_api = UserApi ( client ) key_api = API ( client ) key_api . remove ( username , user_api , filename , force ) | Remove user s SSH public key from their LDAP entry . | 58 | 12 |
14,311 | def install ( config ) : # pragma: no cover client = Client ( ) client . prepare_connection ( ) key_api = API ( client ) key_api . install ( ) | Install user s SSH public key to the local system . | 39 | 11 |
14,312 | def show ( config , username ) : # pragma: no cover client = Client ( ) client . prepare_connection ( ) key_api = API ( client ) for key , value in key_api . get_keys_from_ldap ( username ) . items ( ) : print ( value ) | Show a user s SSH public key from their LDAP entry . | 63 | 13 |
14,313 | def main ( ) : logging . basicConfig ( ) logger . info ( "mmi-runner" ) warnings . warn ( "You are using the mmi-runner script, please switch to `mmi runner`" , DeprecationWarning ) arguments = docopt . docopt ( __doc__ ) kwargs = parse_args ( arguments ) runner = mmi . runner . Runner ( * * kwargs ) runner . run ( ) | run mmi runner | 94 | 4 |
14,314 | def load_requires_from_file ( filepath ) : with open ( filepath ) as fp : return [ pkg_name . strip ( ) for pkg_name in fp . readlines ( ) ] | Read a package list from a given file path . | 47 | 10 |
14,315 | def get_tour_list ( self ) : resp = json . loads ( urlopen ( self . tour_list_url . format ( 1 ) ) . read ( ) . decode ( 'utf-8' ) ) total_count = resp [ 'response' ] [ 'body' ] [ 'totalCount' ] # Get total count resp = json . loads ( urlopen ( self . tour_list_url . format ( total_count ) ) . read ( ) . decode ( 'utf-8' ) ) data = resp [ 'response' ] [ 'body' ] [ 'items' ] [ 'item' ] # Extract data list keychain = { 'contentid' : ( 'content_id' , None ) , 'contenttypeid' : ( 'content_type_id' , None ) , 'title' : ( 'title' , None ) , 'addr1' : ( 'address' , None ) , 'zipcode' : ( 'zipcode' , None ) , 'sigungucode' : ( 'municipality' , None ) , 'mapx' : ( 'x' , None ) , 'mapy' : ( 'y' , None ) , 'cat1' : ( 'main_category' , None ) , 'cat2' : ( 'middle_category' , None ) , 'cat3' : ( 'small_category' , None ) , 'readcount' : ( 'views' , 0 ) , 'tel' : ( 'tel' , None ) , 'firstimage' : ( 'image' , None ) , } for tour in data : _dict_key_changer ( tour , keychain ) tour [ 'creation_date' ] = str ( tour . pop ( 'createdtime' ) ) [ : 8 ] if 'createdtime' in tour else None tour [ 'modified_date' ] = str ( tour . pop ( 'modifiedtime' ) ) [ : 8 ] if 'modifiedtime' in tour else None tour . pop ( 'areacode' , None ) tour . pop ( 'addr2' , None ) tour . pop ( 'mlevel' , None ) # Manufacture return data | Inquire all tour list | 466 | 5 |
14,316 | def get_detail_common ( self , content_id ) : resp = json . loads ( urlopen ( self . detail_common_url . format ( str ( content_id ) ) ) . read ( ) . decode ( 'utf-8' ) ) data = resp [ 'response' ] [ 'body' ] [ 'items' ] [ 'item' ] # Extract data keychain = { 'contenttypeid' : ( 'content_type_id' , None ) , 'overview' : ( 'overview' , None ) , 'tel' : ( 'tel' , None ) , 'telname' : ( 'tel_owner' , None ) , 'booktour' : ( 'in_book' , 0 ) } _dict_key_changer ( data , keychain ) try : data [ 'homepage' ] = re . findall ( 'http\w?://[\w|.]+' , data . pop ( 'homepage' ) ) [ 0 ] if 'homepage' in data else None except IndexError : data [ 'homepage' ] = None data . pop ( 'contentid' , None ) data . pop ( 'title' , None ) data . pop ( 'createdtime' , None ) data . pop ( 'modifiedtime' , None ) # Manufacture return data | Inquire common detail data | 285 | 5 |
14,317 | def get_detail_images ( self , content_id ) : resp = json . loads ( urlopen ( self . additional_images_url . format ( content_id , 1 ) ) . read ( ) . decode ( 'utf-8' ) ) total_count = resp [ 'response' ] [ 'body' ] [ 'totalCount' ] # Get total count resp = json . loads ( urlopen ( self . additional_images_url . format ( content_id , total_count ) ) . read ( ) . decode ( 'utf-8' ) ) try : data = resp [ 'response' ] [ 'body' ] [ 'items' ] [ 'item' ] # Extract data list if type ( data ) is dict : data . pop ( 'contentid' , None ) data . pop ( 'serialnum' , None ) data [ 'origin' ] = data . pop ( 'originimgurl' , None ) data [ 'small' ] = data . pop ( 'smallimageurl' , None ) # Manufacture else : for img in data : if type ( img ) is dict : img . pop ( 'contentid' , None ) img . pop ( 'serialnum' , None ) img [ 'origin' ] = img . pop ( 'originimgurl' , None ) img [ 'small' ] = img . pop ( 'smallimageurl' , None ) # Manufacture else : del img return data if type ( data ) is list else [ data ] except TypeError : return None | Inquire detail images | 322 | 4 |
14,318 | def _writeFile ( cls , filePath , content , encoding = None ) : filePath = os . path . realpath ( filePath ) log . debug ( _ ( "Real file path to write: %s" % filePath ) ) if encoding is None : encoding = File . DEFAULT_ENCODING try : encodedContent = '' . join ( content ) . encode ( encoding ) except LookupError as msg : raise SubFileError ( _ ( "Unknown encoding name: '%s'." ) % encoding ) except UnicodeEncodeError : raise SubFileError ( _ ( "There are some characters in '%(file)s' that cannot be encoded to '%(enc)s'." ) % { "file" : filePath , "enc" : encoding } ) tmpFilePath = "%s.tmp" % filePath bakFilePath = "%s.bak" % filePath with open ( tmpFilePath , 'wb' ) as f : f . write ( encodedContent ) # ensure that all data is on disk. # for performance reasons, we skip os.fsync(f.fileno()) f . flush ( ) try : os . rename ( filePath , bakFilePath ) except FileNotFoundError : # there's nothing to move when filePath doesn't exist # note the Python bug: http://bugs.python.org/issue16074 pass os . rename ( tmpFilePath , filePath ) try : os . unlink ( bakFilePath ) except FileNotFoundError : pass | Safe file writing . Most common mistakes are checked against and reported before write operation . After that if anything unexpected happens user won t be left without data or with corrupted one as this method writes to a temporary file and then simply renames it ( which should be atomic operation according to POSIX but who knows how Ext4 really works . | 324 | 66 |
14,319 | def pay_with_account_credit_cards ( invoice_id ) -> Optional [ Transaction ] : logger . debug ( 'invoice-payment-started' , invoice_id = invoice_id ) with transaction . atomic ( ) : invoice = Invoice . objects . select_for_update ( ) . get ( pk = invoice_id ) # # Precondition: Invoice should be in a state that allows payment # if not invoice . in_payable_state : raise PreconditionError ( 'Cannot pay invoice with status {}.' . format ( invoice . status ) ) # # Precondition: The due amount must be positive, in a single currency # due = invoice . due ( ) . monies ( ) if len ( due ) == 0 : raise PreconditionError ( 'Cannot pay empty invoice.' ) if len ( due ) > 1 : raise PreconditionError ( 'Cannot pay invoice with more than one currency.' ) amount = due [ 0 ] if amount . amount <= 0 : raise PreconditionError ( 'Cannot pay invoice with non-positive amount.' ) # # Try valid credit cards until one works. Start with the active ones # valid_credit_cards = CreditCard . objects . valid ( ) . filter ( account = invoice . account ) . order_by ( 'status' ) if not valid_credit_cards : raise PreconditionError ( 'No valid credit card on account.' ) for credit_card in valid_credit_cards : try : success , payment_psp_object = psp . charge_credit_card ( credit_card_psp_object = credit_card . psp_object , amount = amount , client_ref = str ( invoice_id ) ) payment = Transaction . objects . create ( account = invoice . account , invoice = invoice , amount = amount , success = success , payment_method = credit_card . type , credit_card_number = credit_card . number , psp_object = payment_psp_object ) if success : invoice . pay ( ) invoice . save ( ) logger . info ( 'invoice-payment-success' , invoice = invoice_id , payment = payment ) return payment else : logger . info ( 'invoice-payment-failure' , invoice = invoice_id , payment = payment ) except Exception as e : logger . error ( 'invoice-payment-error' , invoice_id = invoice_id , credit_card = credit_card , exc_info = e ) return None | Get paid for the invoice trying the valid credit cards on record for the account . | 527 | 16 |
14,320 | def setContentFor ( self , widget ) : for i in range ( self . count ( ) ) : item = self . widget ( i ) if widget . isStatic : item . setStaticContent ( widget ) else : item . setContent ( widget ) | Updates toolbox contents with a data corresponding to a given tab . | 53 | 14 |
14,321 | def clear ( self ) : layout = self . layout ( ) for index in reversed ( range ( layout . count ( ) ) ) : item = layout . takeAt ( index ) try : item . widget ( ) . deleteLater ( ) except AttributeError : item = None | Removes all child widgets . | 57 | 6 |
14,322 | def _request ( self , service , * * kw ) : fb_request = { 'service' : service , } for key in [ 'limit' , 'offset' , 'filter' , 'data' ] : fb_request [ key ] = kw . pop ( key , None ) if kw : raise _exc . FastbillRequestError ( "Unknown arguments: %s" % ", " . join ( kw . keys ( ) ) ) data = _jsonencoder . dumps ( fb_request ) _logger . debug ( "Sending data: %r" , data ) self . _pre_request_callback ( service , fb_request ) # TODO: Retry when we hit a 404 (api not found). Probably a deploy. http_resp = self . session . post ( self . SERVICE_URL , auth = self . auth , headers = self . headers , timeout = self . timeout , data = data ) self . _post_request_callback ( service , fb_request , http_resp ) try : json_resp = http_resp . json ( ) except ValueError : _logger . debug ( "Got data: %r" , http_resp . content ) _abort_http ( service , http_resp ) return # to make PyCharm happy else : _logger . debug ( "Got data: %r" , json_resp ) errors = json_resp [ 'RESPONSE' ] . get ( 'ERRORS' ) if errors : _abort_api ( service , json_resp , errors ) # If Fastbill should ever remove the REQUEST or SERVICE section # from their responses, just remove the checks. if json_resp [ 'REQUEST' ] [ 'SERVICE' ] != service : raise _exc . FastbillError ( "API Error: Got response from wrong service." ) return _response . FastbillResponse ( json_resp [ 'RESPONSE' ] , self ) | Do the actual request to Fastbill s API server . | 422 | 11 |
14,323 | def set_parent ( self , node ) : self . _parent = node if node is None : # detach from parent self . _depth = 0 else : self . _depth = node . get_depth ( ) + 1 | Attach node to its parent . | 47 | 6 |
14,324 | def generate_child_leaf_nodes ( self ) : def _yield_child_leaf_nodes ( node ) : """ Args: node: Yields: """ if not node . has_children ( ) : yield node else : for child_node in node . generate_child_nodes ( ) : # recursivity is not compatible with yield in Python2.x: you have to re-yield results for child in _yield_child_leaf_nodes ( child_node ) : yield child return _yield_child_leaf_nodes ( self ) | Generate leaf nodes of this node . | 127 | 8 |
14,325 | def detach_children ( self ) : for node in self . get_child_nodes ( ) : node . set_parent ( None ) self . _nodes = dict ( ) | Erase references to children without deleting them . | 39 | 9 |
14,326 | def process_expt ( h5_path , inmemory = True , ignorenan = False ) : logging . info ( "Reading file at {}" . format ( h5_path ) ) h5_file = tables . open_file ( h5_path , mode = 'r' ) F = h5_file . root . F_measure n_expt , n_labels , n_class = F . shape mean_n_iterations = np . sum ( h5_file . root . n_iterations ) / n_expt if hasattr ( h5_file . root , 'CPU_time' ) : CPU_time = h5_file . root . CPU_time mean_CPU_time = np . mean ( CPU_time ) var_CPU_time = np . var ( CPU_time ) else : mean_CPU_time = None var_CPU_time = None mean_CPU_time_per_iteration = None F_mean = np . empty ( [ n_labels , n_class ] , dtype = 'float' ) F_var = np . empty ( [ n_labels , n_class ] , dtype = 'float' ) F_stderr = np . empty ( [ n_labels , n_class ] , dtype = 'float' ) n_sample = np . empty ( n_labels , dtype = 'int' ) if inmemory : F_mem = F [ : , : , : ] logging . info ( "Beginning processing" . format ( ) ) for t in range ( n_labels ) : if t % np . ceil ( n_labels / 10 ) . astype ( int ) == 0 : logging . info ( "Processed {} of {} experiments" . format ( t , n_labels ) ) if inmemory : temp = F_mem [ : , t , : ] else : temp = F [ : , t , : ] if ignorenan : n_sample [ t ] = np . sum ( ~ np . isnan ( temp ) ) # Expect to see RuntimeWarnings if array contains all NaNs with warnings . catch_warnings ( ) : warnings . simplefilter ( "ignore" , category = RuntimeWarning ) F_mean [ t ] = np . nanmean ( temp , axis = 0 ) F_var [ t ] = np . nanvar ( temp , axis = 0 ) F_stderr [ t ] = np . sqrt ( F_var [ t ] / n_sample [ t ] ) else : n_sample [ t ] = len ( temp ) F_mean [ t ] = np . mean ( temp , axis = 0 ) F_var [ t ] = np . var ( temp , axis = 0 ) F_stderr [ t ] = np . sqrt ( F_var [ t ] / n_sample [ t ] ) logging . info ( "Processing complete" . format ( ) ) h5_file . close ( ) return { 'mean' : F_mean , 'variance' : F_var , 'std_error' : F_stderr , 'n_samples' : n_sample , 'n_expts' : n_expt , 'n_labels' : n_labels , 'mean_CPU_time' : mean_CPU_time , 'var_CPU_time' : var_CPU_time , 'mean_n_iterations' : mean_n_iterations , 'h5_path' : h5_path } | Assumes h5 file has table called F_measure | 770 | 12 |
14,327 | def calc_confusion_matrix ( self , printout = False ) : if self . labels is None : raise DataError ( "Cannot calculate confusion matrix before data " "has been read." ) if self . preds is None : raise DataError ( "Predictions not available. Please run " "`scores_to_preds` before calculating confusion " "matrix" ) self . TP = np . sum ( np . logical_and ( self . preds == 1 , self . labels == 1 ) ) self . TN = np . sum ( np . logical_and ( self . preds == 0 , self . labels == 0 ) ) self . FP = np . sum ( np . logical_and ( self . preds == 1 , self . labels == 0 ) ) self . FN = np . sum ( np . logical_and ( self . preds == 0 , self . labels == 1 ) ) if printout : print ( "Contingency matrix is:" ) print ( "----------------------" ) print ( "TP: {} \t FN: {}" . format ( self . TP , self . FN ) ) print ( "FP: {} \t TN: {}" . format ( self . FP , self . TN ) ) print ( "\n" ) | Calculates number of TP FP TN FN | 270 | 9 |
14,328 | def calc_true_performance ( self , printout = False ) : try : self . calc_confusion_matrix ( printout = False ) except DataError as e : print ( e . msg ) raise if self . TP + self . FP == 0 : self . precision = np . nan else : self . precision = self . TP / ( self . TP + self . FP ) if self . TP + self . FN == 0 : self . recall = np . nan else : self . recall = self . TP / ( self . TP + self . FN ) if self . precision + self . recall == 0 : self . F1_measure = np . nan else : self . F1_measure = ( 2 * self . precision * self . recall / ( self . precision + self . recall ) ) if printout : print ( "True performance is:" ) print ( "--------------------" ) print ( "Precision: {} \t Recall: {} \t F1 measure: {}" . format ( self . precision , self . recall , self . F1_measure ) ) | Evaluate precision recall and balanced F - measure | 230 | 10 |
14,329 | def modify_fk_constraint ( apps , schema_editor ) : model = apps . get_model ( "message_sender" , "OutboundSendFailure" ) table = model . _meta . db_table with schema_editor . connection . cursor ( ) as cursor : constraints = schema_editor . connection . introspection . get_constraints ( cursor , table ) [ constraint ] = filter ( lambda c : c [ 1 ] [ "foreign_key" ] , constraints . items ( ) ) [ name , _ ] = constraint sql_delete_fk = ( "SET CONSTRAINTS {name} IMMEDIATE; " "ALTER TABLE {table} DROP CONSTRAINT {name}" ) . format ( table = schema_editor . quote_name ( table ) , name = schema_editor . quote_name ( name ) ) schema_editor . execute ( sql_delete_fk ) field = model . outbound . field to_table = field . remote_field . model . _meta . db_table to_column = field . remote_field . model . _meta . get_field ( field . remote_field . field_name ) . column sql_create_fk = ( "ALTER TABLE {table} ADD CONSTRAINT {name} FOREIGN KEY " "({column}) REFERENCES {to_table} ({to_column}) " "ON DELETE CASCADE {deferrable};" ) . format ( table = schema_editor . quote_name ( table ) , name = schema_editor . quote_name ( name ) , column = schema_editor . quote_name ( field . column ) , to_table = schema_editor . quote_name ( to_table ) , to_column = schema_editor . quote_name ( to_column ) , deferrable = schema_editor . connection . ops . deferrable_sql ( ) , ) schema_editor . execute ( sql_create_fk ) | Delete s the current foreign key contraint on the outbound field and adds it again but this time with an ON DELETE clause | 431 | 27 |
14,330 | def log_warning ( self , msg ) : if self . __logger : self . __logger . warning ( msg ) if self . __raise_exception_on_warning : raise RuntimeError ( msg ) | Log a warning if logger exists . | 46 | 7 |
14,331 | def log_error ( self , msg ) : if self . __logger : self . __logger . error ( msg ) raise RuntimeError ( msg ) | Log an error and raise an exception . | 33 | 8 |
14,332 | def __add_action ( self , relative_directory , action ) : generator_action_container = self . __actions . retrieve_element_or_default ( relative_directory , None ) if generator_action_container is None : generator_action_container = GeneratorActionContainer ( ) generator_action_container . add_generator_action ( action ) self . __actions . add_element ( location = relative_directory , element = generator_action_container ) else : generator_action_container . add_generator_action ( action ) | Add action into the dictionary of actions . | 115 | 8 |
14,333 | def __is_function_action ( self , action_function ) : # test if function returns a couple of values is_function_action = True if not hasattr ( action_function , '__call__' ) : return False # OK, callable. Do we receive the right arguments? try : for end_string , context in action_function ( ) : if not isinstance ( end_string , basestring ) : self . log_error ( "Action function must return end of filename as a string as first argument" ) if not isinstance ( context , dict ) : self . log_error ( "Action function must return context as a dict as second argument" ) break except Exception : is_function_action = False return is_function_action | Detect if given function is really an action function . | 160 | 10 |
14,334 | def register_default_action ( self , file_pattern , action_function ) : if self . __default_action is not None : self . log_error ( 'Default action function already exist.' ) if not self . __is_function_action ( action_function ) : self . log_error ( 'Attached default function is not an action function.' ) self . __default_action = GeneratorAction ( file_pattern = file_pattern , action_function = action_function ) | Default action used if no compatible action is found . | 103 | 10 |
14,335 | def prepare_page ( self , * args , * * kwargs ) : super ( BaseBackend , self ) . prepare_page ( * args , * * kwargs ) | This is called after the page has been loaded good time to do extra polishing | 39 | 16 |
14,336 | def set_wrapped ( self , wrapped ) : self . wrapped = wrapped functools . update_wrapper ( self , self . wrapped , updated = ( ) ) self . wrapped_func = False self . wrapped_class = False if inspect . isroutine ( wrapped ) : self . wrapped_func = True elif isinstance ( wrapped , type ) : self . wrapped_class = True | This will decide what wrapped is and set . wrapped_func or . wrapped_class accordingly | 83 | 18 |
14,337 | def decorate_class ( self , klass , * decorator_args , * * decorator_kwargs ) : raise RuntimeError ( "decorator {} does not support class decoration" . format ( self . __class__ . __name__ ) ) return klass | override this in a child class with your own logic it must return a function that returns klass or the like | 58 | 23 |
14,338 | def decorate_class ( self , klass , * decorator_args , * * decorator_kwargs ) : class ChildClass ( klass ) : def __init__ ( slf , * args , * * kwargs ) : super ( ChildClass , slf ) . __init__ ( * args , * * kwargs ) self . decorate ( slf , * decorator_args , * * decorator_kwargs ) decorate_klass = ChildClass decorate_klass . __name__ = klass . __name__ decorate_klass . __module__ = klass . __module__ # for some reason you can't update a __doc__ on a class # http://bugs.python.org/issue12773 return decorate_klass | where the magic happens this wraps a class to call our decorate method in the init of the class | 169 | 20 |
14,339 | def generate_entry_tags ( sender , instance , created , raw , using , * * kwargs ) : Tag . objects . create_tags ( instance ) | Generate the M2M Tag s for an Entry right after it has been saved . | 34 | 18 |
14,340 | def entry_stats ( entries , top_n = 10 ) : wc = Counter ( ) # A Word counter for content in entries . values_list ( "rendered_content" , flat = True ) : # Do a little cleanup content = strip_tags ( content ) # remove all html tags content = re . sub ( '\s+' , ' ' , content ) # condense all whitespace content = re . sub ( '[^A-Za-z ]+' , '' , content ) # remove non-alpha chars words = [ w . lower ( ) for w in content . split ( ) ] wc . update ( [ w for w in words if w not in IGNORE_WORDS ] ) return { "total_words" : len ( wc . values ( ) ) , "most_common" : wc . most_common ( top_n ) , } | Calculates stats for the given QuerySet of Entry s . | 189 | 13 |
14,341 | def create_tags ( self , entry ) : tag_list = [ t . lower ( ) . strip ( ) for t in entry . tag_string . split ( ',' ) ] for t in tag_list : tag , created = self . get_or_create ( name = t ) entry . tags . add ( tag ) | Inspects an Entry instance and builds associates Tag objects based on the values in the Entry s tag_string . | 70 | 23 |
14,342 | def _create_date_slug ( self ) : if not self . pk : # haven't saved this yet, so use today's date d = utc_now ( ) elif self . published and self . published_on : # use the actual published on date d = self . published_on elif self . updated_on : # default to the last-updated date d = self . updated_on self . date_slug = u"{0}/{1}" . format ( d . strftime ( "%Y/%m/%d" ) , self . slug ) | Prefixes the slug with the published_on date . | 127 | 12 |
14,343 | def _render_content ( self ) : if self . content_format == "rst" and docutils_publish is not None : doc_parts = docutils_publish ( source = self . raw_content , writer_name = "html4css1" ) self . rendered_content = doc_parts [ 'fragment' ] elif self . content_format == "rs" and docutils_publish is None : raise RuntimeError ( "Install docutils to pubilsh reStructuredText" ) elif self . content_format == "md" and markdown is not None : self . rendered_content = markdown ( self . raw_content ) elif self . content_format == "md" and markdown is None : raise RuntimeError ( "Install Markdown to pubilsh markdown" ) else : # Assume we've got html self . rendered_content = self . raw_content | Renders the content according to the content_format . | 199 | 11 |
14,344 | def save ( self , * args , * * kwargs ) : self . _create_slug ( ) self . _create_date_slug ( ) self . _render_content ( ) # Call ``_set_published`` the *first* time this Entry is published. # NOTE: if this is unpublished, and then republished, this method won't # get called; e.g. the date won't get changed and the # ``entry_published`` signal won't get re-sent. send_published_signal = False if self . published and self . published_on is None : send_published_signal = self . _set_published ( ) super ( Entry , self ) . save ( * args , * * kwargs ) # We need an ID before we can send this signal. if send_published_signal : entry_published . send ( sender = self , entry = self ) | Auto - generate a slug from the name . | 196 | 9 |
14,345 | def get_absolute_url_with_date ( self ) : pub_date = self . published_on if pub_date and settings . USE_TZ : # If TZ is enabled, convert all of these dates from UTC to whatever # the project's timezone is set as. Ideally, we'd pull this form # some user settings, but the *canonical* publish time is that of # the author (asssuming author == owner of this project). pub_date = make_naive ( pub_date , pytz . utc ) # Make naive pub_date = pytz . timezone ( settings . TIME_ZONE ) . localize ( pub_date ) if pub_date : args = [ pub_date . strftime ( "%Y" ) , pub_date . strftime ( "%m" ) , pub_date . strftime ( "%d" ) , self . slug ] else : args = [ self . slug ] return reverse ( 'blargg:entry_detail' , args = args ) | URL based on the entry s date & slug . | 219 | 10 |
14,346 | def tag_list ( self ) : tags = [ tag . strip ( ) for tag in self . tag_string . split ( "," ) ] return sorted ( filter ( None , tags ) ) | Return a plain python list containing all of this Entry s tags . | 41 | 13 |
14,347 | def heartbeat ( self ) : url = urljoin ( self . base_url , 'heartbeat' ) return self . session . get ( url ) . json ( ) [ 'ok' ] | Check The API Is Up . | 40 | 6 |
14,348 | def venue_healthcheck ( self ) : url = urljoin ( self . base_url , 'venues/TESTEX/heartbeat' ) return self . session . get ( url ) . json ( ) [ 'ok' ] | Check A Venue Is Up . | 50 | 7 |
14,349 | def venue_stocks ( self ) : url = urljoin ( self . base_url , 'venues/{0}/stocks' . format ( self . venue ) ) return self . session . get ( url ) . json ( ) | List the stocks available for trading on the venue . | 50 | 10 |
14,350 | def orderbook_for_stock ( self , stock ) : url_fragment = 'venues/{venue}/stocks/{stock}' . format ( venue = self . venue , stock = stock , ) url = urljoin ( self . base_url , url_fragment ) return self . session . get ( url ) . json ( ) | Get the orderbook for a particular stock . | 77 | 9 |
14,351 | def place_new_order ( self , stock , price , qty , direction , order_type ) : url_fragment = 'venues/{venue}/stocks/{stock}/orders' . format ( venue = self . venue , stock = stock , ) data = { "stock" : stock , "price" : price , "venue" : self . venue , "account" : self . account , "qty" : qty , "direction" : direction , "orderType" : order_type , } url = urljoin ( self . base_url , url_fragment ) resp = self . session . post ( url , json = data ) return resp . json ( ) | Place an order for a stock . | 151 | 7 |
14,352 | def status_for_order ( self , order_id , stock ) : url_fragment = 'venues/{venue}/stocks/{stock}/orders/{order_id}' . format ( venue = self . venue , stock = stock , order_id = order_id , ) url = urljoin ( self . base_url , url_fragment ) return self . session . get ( url ) . json ( ) | Status For An Existing Order | 96 | 6 |
14,353 | def cancel_order ( self , order_id , stock ) : url_fragment = 'venues/{venue}/stocks/{stock}/orders/{order_id}' . format ( venue = self . venue , stock = stock , order_id = order_id , ) url = urljoin ( self . base_url , url_fragment ) return self . session . delete ( url ) . json ( ) | Cancel An Order | 94 | 4 |
14,354 | def status_for_all_orders ( self ) : url_fragment = 'venues/{venue}/accounts/{account}/orders' . format ( venue = self . venue , account = self . account , ) url = urljoin ( self . base_url , url_fragment ) return self . session . get ( url ) . json ( ) | Status for all orders | 81 | 4 |
14,355 | def status_for_all_orders_in_a_stock ( self , stock ) : url_fragment = 'venues/{venue}/accounts/{account}/stocks/{stock}/orders' . format ( stock = stock , venue = self . venue , account = self . account , ) url = urljoin ( self . base_url , url_fragment ) return self . session . get ( url ) . json ( ) | Status for all orders in a stock | 99 | 7 |
14,356 | def scan_django_settings ( values , imports ) : if isinstance ( values , ( str , bytes ) ) : if utils . is_import_str ( values ) : imports . add ( values ) elif isinstance ( values , dict ) : for k , v in values . items ( ) : scan_django_settings ( k , imports ) scan_django_settings ( v , imports ) elif hasattr ( values , '__file__' ) and getattr ( values , '__file__' ) : imp , _ = utils . import_path_from_file ( getattr ( values , '__file__' ) ) imports . add ( imp ) elif hasattr ( values , '__iter__' ) : for item in values : scan_django_settings ( item , imports ) | Recursively scans Django settings for values that appear to be imported modules . | 177 | 15 |
14,357 | def handle_django_settings ( filename ) : old_sys_path = sys . path [ : ] dirpath = os . path . dirname ( filename ) project = os . path . basename ( dirpath ) cwd = os . getcwd ( ) project_path = os . path . normpath ( os . path . join ( dirpath , '..' ) ) if project_path not in sys . path : sys . path . insert ( 0 , project_path ) os . chdir ( project_path ) project_settings = '{}.settings' . format ( project ) os . environ [ 'DJANGO_SETTINGS_MODULE' ] = project_settings try : import django # Sanity django . setup = lambda : False except ImportError : log . error ( 'Found Django settings, but Django is not installed.' ) return log . warn ( 'Loading Django Settings (Using {}): {}' . format ( django . get_version ( ) , filename ) ) from django . conf import LazySettings installed_apps = set ( ) settings_imports = set ( ) try : settings = LazySettings ( ) settings . _setup ( ) for k , v in vars ( settings . _wrapped ) . items ( ) : if k not in _excluded_settings and re . match ( r'^[A-Z_]+$' , k ) : # log.debug('Scanning Django setting: %s', k) scan_django_settings ( v , settings_imports ) # Manually scan INSTALLED_APPS since the broad scan won't include # strings without a period in it . for app in getattr ( settings , 'INSTALLED_APPS' , [ ] ) : if hasattr ( app , '__file__' ) and getattr ( app , '__file__' ) : imp , _ = utils . import_path_from_file ( getattr ( app , '__file__' ) ) installed_apps . add ( imp ) else : installed_apps . add ( app ) except Exception as e : log . error ( 'Could not load Django settings: %s' , e ) log . debug ( '' , exc_info = True ) return if not installed_apps or not settings_imports : log . error ( 'Got empty settings values from Django settings.' ) try : from django . apps . registry import apps , Apps , AppRegistryNotReady # Django doesn't like it when the initial instance of `apps` is reused, # but it has to be populated before other instances can be created. if not apps . apps_ready : apps . populate ( installed_apps ) else : apps = Apps ( installed_apps ) start = time . time ( ) while True : try : for app in apps . get_app_configs ( ) : installed_apps . add ( app . name ) except AppRegistryNotReady : if time . time ( ) - start > 10 : raise Exception ( 'Bail out of waiting for Django' ) log . debug ( 'Waiting for apps to load...' ) continue break except Exception as e : log . debug ( 'Could not use AppConfig: {}' . format ( e ) ) # Restore before sub scans can occur sys . path [ : ] = old_sys_path os . chdir ( cwd ) for item in settings_imports : need_scan = item . startswith ( _filescan_modules ) yield ( 'django' , item , project_path if need_scan else None ) for app in installed_apps : need_scan = app . startswith ( project ) yield ( 'django' , app , project_path if need_scan else None ) | Attempts to load a Django project and get package dependencies from settings . | 799 | 13 |
14,358 | def _url ( endpoint : str , sandbox : bool = False ) -> str : if sandbox is True : url = BASE_URL_SANDBOX else : url = BASE_URL return "{0}{1}" . format ( url , endpoint ) | Build a URL from the API s base URLs . | 51 | 10 |
14,359 | def update ( self , goal : Dict = None ) -> None : if goal is None : endpoint = "/account/{0}/savings-goals/{1}" . format ( self . _account_uid , self . uid ) response = get ( _url ( endpoint , self . _sandbox ) , headers = self . _auth_headers ) response . raise_for_status ( ) goal = response . json ( ) self . uid = goal . get ( 'savingsGoalUid' ) self . name = goal . get ( 'name' ) target = goal . get ( 'target' , { } ) self . target_currency = target . get ( 'currency' ) self . target_minor_units = target . get ( 'minorUnits' ) total_saved = goal . get ( 'totalSaved' , { } ) self . total_saved_currency = total_saved . get ( 'currency' ) self . total_saved_minor_units = total_saved . get ( 'minorUnits' ) | Update a single savings goals data . | 234 | 7 |
14,360 | def deposit ( self , deposit_minor_units : int ) -> None : endpoint = "/account/{0}/savings-goals/{1}/add-money/{2}" . format ( self . _account_uid , self . uid , uuid4 ( ) ) body = { "amount" : { "currency" : self . total_saved_currency , "minorUnits" : deposit_minor_units } } response = put ( _url ( endpoint , self . _sandbox ) , headers = self . _auth_headers , data = json_dumps ( body ) ) response . raise_for_status ( ) self . update ( ) | Add funds to a savings goal . | 149 | 7 |
14,361 | def get_image ( self , filename : str = None ) -> None : if filename is None : filename = "{0}.png" . format ( self . name ) endpoint = "/account/{0}/savings-goals/{1}/photo" . format ( self . _account_uid , self . uid ) response = get ( _url ( endpoint , self . _sandbox ) , headers = self . _auth_headers ) response . raise_for_status ( ) base64_image = response . json ( ) [ 'base64EncodedPhoto' ] with open ( filename , 'wb' ) as file : file . write ( b64decode ( base64_image ) ) | Download the photo associated with a Savings Goal . | 151 | 9 |
14,362 | def update_account_data ( self ) -> None : response = get ( _url ( "/accounts/{0}/identifiers" . format ( self . _account_uid ) , self . _sandbox ) , headers = self . _auth_headers ) response . raise_for_status ( ) response = response . json ( ) self . account_identifier = response . get ( 'accountIdentifier' ) self . bank_identifier = response . get ( 'bankIdentifier' ) self . iban = response . get ( 'iban' ) self . bic = response . get ( 'bic' ) | Get basic information for the account . | 134 | 7 |
14,363 | def update_balance_data ( self ) -> None : response = get ( _url ( "/accounts/{0}/balance" . format ( self . _account_uid ) , self . _sandbox ) , headers = self . _auth_headers ) response . raise_for_status ( ) response = response . json ( ) self . cleared_balance = response [ 'clearedBalance' ] [ 'minorUnits' ] self . effective_balance = response [ 'effectiveBalance' ] [ 'minorUnits' ] self . pending_transactions = response [ 'pendingTransactions' ] [ 'minorUnits' ] self . available_to_spend = response [ 'availableToSpend' ] [ 'minorUnits' ] self . accepted_overdraft = response [ 'acceptedOverdraft' ] [ 'minorUnits' ] | Get the latest balance information for the account . | 189 | 9 |
14,364 | def update_savings_goal_data ( self ) -> None : response = get ( _url ( "/account/{0}/savings-goals" . format ( self . _account_uid ) , self . _sandbox ) , headers = self . _auth_headers ) response . raise_for_status ( ) response = response . json ( ) response_savings_goals = response . get ( 'savingsGoalList' , { } ) returned_uids = [ ] # New / Update for goal in response_savings_goals : uid = goal . get ( 'savingsGoalUid' ) returned_uids . append ( uid ) # Intiialise new _SavingsGoal object if new if uid not in self . savings_goals : self . savings_goals [ uid ] = SavingsGoal ( self . _auth_headers , self . _sandbox , self . _account_uid ) self . savings_goals [ uid ] . update ( goal ) # Forget about savings goals if the UID isn't returned by Starling for uid in list ( self . savings_goals ) : if uid not in returned_uids : self . savings_goals . pop ( uid ) | Get the latest savings goal information for the account . | 271 | 10 |
14,365 | def process_inlines ( parser , token ) : args = token . split_contents ( ) if not len ( args ) in ( 2 , 4 , 6 ) : raise template . TemplateSyntaxError ( "%r tag requires either 1, 3 or 5 arguments." % args [ 0 ] ) var_name = args [ 1 ] ALLOWED_ARGS = [ 'as' , 'in' ] kwargs = { 'template_directory' : None } if len ( args ) > 2 : tuples = zip ( * [ args [ 2 : ] [ i : : 2 ] for i in range ( 2 ) ] ) for k , v in tuples : if not k in ALLOWED_ARGS : raise template . TemplateSyntaxError ( "%r tag options arguments must be one of %s." % ( args [ 0 ] , ', ' . join ( ALLOWED_ARGS ) ) ) if k == 'in' : kwargs [ 'template_directory' ] = v if k == 'as' : kwargs [ 'asvar' ] = v return InlinesNode ( var_name , * * kwargs ) | Searches through the provided content and applies inlines where ever they are found . | 246 | 17 |
14,366 | def build_current_graph ( ) : graph = SQLStateGraph ( ) for app_name , config in apps . app_configs . items ( ) : try : module = import_module ( '.' . join ( ( config . module . __name__ , SQL_CONFIG_MODULE ) ) ) sql_items = module . sql_items except ( ImportError , AttributeError ) : continue for sql_item in sql_items : graph . add_node ( ( app_name , sql_item . name ) , sql_item ) for dep in sql_item . dependencies : graph . add_lazy_dependency ( ( app_name , sql_item . name ) , dep ) graph . build_graph ( ) return graph | Read current state of SQL items from the current project state . | 159 | 12 |
14,367 | def build_graph ( self ) : for child , parents in self . dependencies . items ( ) : if child not in self . nodes : raise NodeNotFoundError ( "App %s SQL item dependencies reference nonexistent child node %r" % ( child [ 0 ] , child ) , child ) for parent in parents : if parent not in self . nodes : raise NodeNotFoundError ( "App %s SQL item dependencies reference nonexistent parent node %r" % ( child [ 0 ] , parent ) , parent ) self . node_map [ child ] . add_parent ( self . node_map [ parent ] ) self . node_map [ parent ] . add_child ( self . node_map [ child ] ) for node in self . nodes : self . ensure_not_cyclic ( node , lambda x : ( parent . key for parent in self . node_map [ x ] . parents ) ) | Read lazy dependency list and build graph . | 190 | 8 |
14,368 | def sample ( self , n_to_sample , * * kwargs ) : n_to_sample = verify_positive ( int ( n_to_sample ) ) n_remaining = self . _max_iter - self . t_ if n_remaining == 0 : if ( not self . replace ) and ( self . _n_items == self . _max_iter ) : raise Exception ( "All items have already been sampled" ) else : raise Exception ( "No more space available to continue sampling. " "Consider re-initialising with a larger value " "of max_iter." ) if n_to_sample > n_remaining : warnings . warn ( "Space only remains for {} more iteration(s). " "Setting n_to_sample = {}." . format ( n_remaining , n_remaining ) ) n_to_sample = n_remaining for _ in range ( n_to_sample ) : self . _iterate ( * * kwargs ) | Sample a sequence of items from the pool | 216 | 8 |
14,369 | def sample_distinct ( self , n_to_sample , * * kwargs ) : # Record how many distinct items have not yet been sampled n_notsampled = np . sum ( np . isnan ( self . cached_labels_ ) ) if n_notsampled == 0 : raise Exception ( "All distinct items have already been sampled." ) if n_to_sample > n_notsampled : warnings . warn ( "Only {} distinct item(s) have not yet been sampled." " Setting n_to_sample = {}." . format ( n_notsampled , n_notsampled ) ) n_to_sample = n_notsampled n_sampled = 0 # number of distinct items sampled this round while n_sampled < n_to_sample : self . sample ( 1 , * * kwargs ) n_sampled += self . _queried_oracle [ self . t_ - 1 ] * 1 | Sample a sequence of items from the pool until a minimum number of distinct items are queried | 207 | 18 |
14,370 | def _sample_item ( self , * * kwargs ) : if self . replace : # Can sample from any of the items loc = np . random . choice ( self . _n_items ) else : # Can only sample from items that have not been seen # Find ids that haven't been seen yet not_seen_ids = np . where ( np . isnan ( self . cached_labels_ ) ) [ 0 ] loc = np . random . choice ( not_seen_ids ) return loc , 1 , { } | Sample an item from the pool | 114 | 6 |
14,371 | def _query_label ( self , loc ) : # Try to get label from cache ell = self . cached_labels_ [ loc ] if np . isnan ( ell ) : # Label has not been cached. Need to query oracle oracle_arg = self . identifiers [ loc ] ell = self . oracle ( oracle_arg ) if ell not in [ 0 , 1 ] : raise Exception ( "Oracle provided an invalid label." ) #TODO Gracefully handle errors from oracle? self . _queried_oracle [ self . t_ ] = True self . cached_labels_ [ loc ] = ell return ell | Query the label for the item with index loc . Preferentially queries the label from the cache but if not yet cached queries the oracle . | 137 | 29 |
14,372 | def _F_measure ( self , alpha , TP , FP , FN , return_num_den = False ) : num = np . float64 ( TP ) den = np . float64 ( alpha * ( TP + FP ) + ( 1 - alpha ) * ( TP + FN ) ) with np . errstate ( divide = 'ignore' , invalid = 'ignore' ) : F_measure = num / den #F_measure = num/den if return_num_den : return F_measure , num , den else : return F_measure | Calculate the weighted F - measure | 121 | 8 |
14,373 | def key_occurrence ( self , key , update = True ) : if update : self . update ( ) result = { } for k , v in self . database . items ( ) : if key in v : result [ str ( v [ key ] ) ] = k return result | Return a dict containing the value of the provided key and its uuid as value . | 59 | 17 |
14,374 | def zmq_address ( self , key ) : zmq_address = "tcp://" + self . database [ key ] [ 'node' ] + ":" + str ( self . database [ key ] [ 'ports' ] [ 'REQ' ] ) return zmq_address | Return a ZeroMQ address to the module with the provided key . | 65 | 13 |
14,375 | def _get_json ( location ) : location = os . path . expanduser ( location ) try : if os . path . isfile ( location ) : with io . open ( location , encoding = "utf-8" ) as json_data : return json . load ( json_data , object_pairs_hook = OrderedDict ) . get ( "tests" ) elif "http" in location : json_data = requests . get ( location ) if not json_data : raise Dump2PolarionException ( "Failed to download" ) return json . loads ( json_data . text , object_pairs_hook = OrderedDict ) . get ( "tests" ) else : raise Dump2PolarionException ( "Invalid location" ) except Exception as err : raise Dump2PolarionException ( "Failed to parse JSON from {}: {}" . format ( location , err ) ) | Reads JSON data from file or URL . | 200 | 9 |
14,376 | def _calculate_duration ( start_time , finish_time ) : if not ( start_time and finish_time ) : return 0 start = datetime . datetime . fromtimestamp ( start_time ) finish = datetime . datetime . fromtimestamp ( finish_time ) duration = finish - start decimals = float ( ( "0." + str ( duration . microseconds ) ) ) return duration . seconds + decimals | Calculates how long it took to execute the testcase . | 96 | 13 |
14,377 | def _filter_parameters ( parameters ) : if not parameters : return None return OrderedDict ( ( param , value ) for param , value in six . iteritems ( parameters ) if param not in IGNORED_PARAMS ) | Filters the ignored parameters out . | 49 | 7 |
14,378 | def _append_record ( test_data , results , test_path ) : statuses = test_data . get ( "statuses" ) jenkins_data = test_data . get ( "jenkins" ) or { } data = [ ( "title" , test_data . get ( "test_name" ) or _get_testname ( test_path ) ) , ( "verdict" , statuses . get ( "overall" ) ) , ( "source" , test_data . get ( "source" ) ) , ( "job_name" , jenkins_data . get ( "job_name" ) ) , ( "run" , jenkins_data . get ( "build_number" ) ) , ( "params" , _filter_parameters ( test_data . get ( "params" ) ) ) , ( "time" , _calculate_duration ( test_data . get ( "start_time" ) , test_data . get ( "finish_time" ) ) or 0 , ) , ] test_id = test_data . get ( "polarion" ) if test_id : if isinstance ( test_id , list ) : test_id = test_id [ 0 ] data . append ( ( "test_id" , test_id ) ) results . append ( OrderedDict ( data ) ) | Adds data of single testcase results to results database . | 302 | 11 |
14,379 | def _parse_ostriz ( ostriz_data ) : if not ostriz_data : raise NothingToDoException ( "No data to import" ) results = [ ] found_build = None last_finish_time = [ 0 ] for test_path , test_data in six . iteritems ( ostriz_data ) : curr_build = test_data . get ( "build" ) if not curr_build : continue # set `found_build` from first record where it's present if not found_build : found_build = curr_build # make sure we are collecting data for the same build if found_build != curr_build : continue if not test_data . get ( "statuses" ) : continue _append_record ( test_data , results , test_path ) _comp_finish_time ( test_data , last_finish_time ) if last_finish_time [ 0 ] : logger . info ( "Last result finished at %s" , last_finish_time [ 0 ] ) testrun_id = _get_testrun_id ( found_build ) return xunit_exporter . ImportedData ( results = results , testrun = testrun_id ) | Reads the content of the input JSON and returns testcases results . | 268 | 14 |
14,380 | def send_array ( socket , A = None , metadata = None , flags = 0 , copy = False , track = False , compress = None , chunksize = 50 * 1000 * 1000 ) : # create a metadata dictionary for the message md = { } # always add a timestamp md [ 'timestamp' ] = datetime . datetime . now ( ) . isoformat ( ) # copy extra metadata if metadata : md . update ( metadata ) # if we don't have an array if A is None : # send only json md [ 'parts' ] = 0 socket . send_json ( md , flags ) # and we're done return # support single values (empty shape) if isinstance ( A , float ) or isinstance ( A , int ) : A = np . asarray ( A ) # add array metadata md [ 'dtype' ] = str ( A . dtype ) md [ 'shape' ] = A . shape # determine number of parts md [ 'parts' ] = int ( np . prod ( A . shape ) // chunksize + 1 ) try : # If an array has a fill value assume it's an array with missings # store the fill_Value in the metadata and fill the array before sending. # asscalar should work for scalar, 0d array or nd array of size 1 md [ 'fill_value' ] = np . asscalar ( A . fill_value ) A = A . filled ( ) except AttributeError : # no masked array, nothing to do pass # send json, followed by array (in x parts) socket . send_json ( md , flags | zmq . SNDMORE ) # although the check is not strictly necessary, we try to maintain fast # pointer transfer when there is only 1 part if md [ 'parts' ] == 1 : msg = memoryview ( np . ascontiguousarray ( A ) ) socket . send ( msg , flags , copy = copy , track = track ) else : # split array at first dimension and send parts for i , a in enumerate ( np . array_split ( A , md [ 'parts' ] ) ) : # Make a copy if required and pass along the memoryview msg = memoryview ( np . ascontiguousarray ( a ) ) flags_ = flags if i != md [ 'parts' ] - 1 : flags_ |= zmq . SNDMORE socket . send ( msg , flags_ , copy = copy , track = track ) return | send a numpy array with metadata over zmq | 523 | 11 |
14,381 | def recv_array ( socket , flags = 0 , copy = False , track = False , poll = None , poll_timeout = 10000 ) : if poll is None : md = socket . recv_json ( flags = flags ) else : # one-try "Lazy Pirate" method: http://zguide.zeromq.org/php:chapter4 socks = dict ( poll . poll ( poll_timeout ) ) if socks . get ( socket ) == zmq . POLLIN : reply = socket . recv_json ( flags = flags ) # note that reply can be an empty array md = reply else : raise NoResponseException ( "Recv_array got no response within timeout (1)" ) if md [ 'parts' ] == 0 : # No array expected A = None elif md [ 'parts' ] == 1 : # although the check is not strictly necessary, we try to maintain fast # pointer transfer when there is only 1 part if poll is None : msg = socket . recv ( flags = flags , copy = copy , track = track ) else : # one-try "Lazy Pirate" method: http://zguide.zeromq.org/php:chapter4 socks = dict ( poll . poll ( poll_timeout ) ) if socks . get ( socket ) == zmq . POLLIN : reply = socket . recv ( flags = flags , copy = copy , track = track ) # note that reply can be an empty array msg = reply else : raise NoResponseException ( "Recv_array got no response within timeout (2)" ) buf = buffer ( msg ) A = np . frombuffer ( buf , dtype = md [ 'dtype' ] ) A = A . reshape ( md [ 'shape' ] ) if 'fill_value' in md : A = np . ma . masked_equal ( A , md [ 'fill_value' ] ) else : # multi part array A = np . zeros ( np . prod ( md [ 'shape' ] ) , dtype = md [ 'dtype' ] ) arr_position = 0 for i in range ( md [ 'parts' ] ) : if poll is None : msg = socket . recv ( flags = flags , copy = copy , track = track ) else : # one-try "Lazy Pirate" method: http://zguide.zeromq.org/php:chapter4 socks = dict ( poll . poll ( poll_timeout ) ) if socks . get ( socket ) == zmq . POLLIN : reply = socket . recv ( flags = flags , copy = copy , track = track ) if not reply : raise EmptyResponseException ( "Recv_array got an empty response (2)" ) msg = reply else : raise NoResponseException ( "Recv_array got no response within timeout (2)" ) buf = buffer ( msg ) a = np . frombuffer ( buf , dtype = md [ 'dtype' ] ) A [ arr_position : arr_position + a . shape [ 0 ] ] = a [ : ] arr_position += a . shape [ 0 ] A = A . reshape ( md [ 'shape' ] ) if 'fill_value' in md : A = np . ma . masked_equal ( A , md [ 'fill_value' ] ) return A , md | recv a metadata and an optional numpy array from a zmq socket | 712 | 16 |
14,382 | def is_sql_equal ( sqls1 , sqls2 ) : is_seq1 = isinstance ( sqls1 , ( list , tuple ) ) is_seq2 = isinstance ( sqls2 , ( list , tuple ) ) if not is_seq1 : sqls1 = ( sqls1 , ) if not is_seq2 : sqls2 = ( sqls2 , ) if len ( sqls1 ) != len ( sqls2 ) : return False for sql1 , sql2 in zip ( sqls1 , sqls2 ) : sql1 , params1 = _sql_params ( sql1 ) sql2 , params2 = _sql_params ( sql2 ) if sql1 != sql2 or params1 != params2 : return False return True | Find out equality of two SQL items . | 166 | 8 |
14,383 | def add_sql_operation ( self , app_label , sql_name , operation , dependencies ) : deps = [ ( dp [ 0 ] , SQL_BLOB , dp [ 1 ] , self . _sql_operations . get ( dp ) ) for dp in dependencies ] self . add_operation ( app_label , operation , dependencies = deps ) self . _sql_operations [ ( app_label , sql_name ) ] = operation | Add SQL operation and register it to be used as dependency for further sequential operations . | 101 | 16 |
14,384 | def _generate_reversed_sql ( self , keys , changed_keys ) : for key in keys : if key not in changed_keys : continue app_label , sql_name = key old_item = self . from_sql_graph . nodes [ key ] new_item = self . to_sql_graph . nodes [ key ] if not old_item . reverse_sql or old_item . reverse_sql == RunSQL . noop or new_item . replace : continue # migrate backwards operation = ReverseAlterSQL ( sql_name , old_item . reverse_sql , reverse_sql = old_item . sql ) sql_deps = [ n . key for n in self . from_sql_graph . node_map [ key ] . children ] sql_deps . append ( key ) self . add_sql_operation ( app_label , sql_name , operation , sql_deps ) | Generate reversed operations for changes that require full rollback and creation . | 199 | 14 |
14,385 | def _generate_delete_sql ( self , delete_keys ) : for key in delete_keys : app_label , sql_name = key old_node = self . from_sql_graph . nodes [ key ] operation = DeleteSQL ( sql_name , old_node . reverse_sql , reverse_sql = old_node . sql ) sql_deps = [ n . key for n in self . from_sql_graph . node_map [ key ] . children ] sql_deps . append ( key ) self . add_sql_operation ( app_label , sql_name , operation , sql_deps ) | Generate forward delete operations for SQL items . | 136 | 9 |
14,386 | def generate_sql_changes ( self ) : from_keys = set ( self . from_sql_graph . nodes . keys ( ) ) to_keys = set ( self . to_sql_graph . nodes . keys ( ) ) new_keys = to_keys - from_keys delete_keys = from_keys - to_keys changed_keys = set ( ) dep_changed_keys = [ ] for key in from_keys & to_keys : old_node = self . from_sql_graph . nodes [ key ] new_node = self . to_sql_graph . nodes [ key ] # identify SQL changes -- these will alter database. if not is_sql_equal ( old_node . sql , new_node . sql ) : changed_keys . add ( key ) # identify dependencies change old_deps = self . from_sql_graph . dependencies [ key ] new_deps = self . to_sql_graph . dependencies [ key ] removed_deps = old_deps - new_deps added_deps = new_deps - old_deps if removed_deps or added_deps : dep_changed_keys . append ( ( key , removed_deps , added_deps ) ) # we do basic sort here and inject dependency keys here. # operations built using these keys will properly set operation dependencies which will # enforce django to build/keep a correct order of operations (stable_topological_sort). keys = self . assemble_changes ( new_keys , changed_keys , self . to_sql_graph ) delete_keys = self . assemble_changes ( delete_keys , set ( ) , self . from_sql_graph ) self . _sql_operations = { } self . _generate_reversed_sql ( keys , changed_keys ) self . _generate_sql ( keys , changed_keys ) self . _generate_delete_sql ( delete_keys ) self . _generate_altered_sql_dependencies ( dep_changed_keys ) | Starting point of this tool which identifies changes and generates respective operations . | 440 | 13 |
14,387 | def check_dependency ( self , operation , dependency ) : if isinstance ( dependency [ 1 ] , SQLBlob ) : # NOTE: we follow the sort order created by `assemble_changes` so we build a fixed chain # of operations. thus we should match exact operation here. return dependency [ 3 ] == operation return super ( MigrationAutodetector , self ) . check_dependency ( operation , dependency ) | Enhances default behavior of method by checking dependency for matching operation . | 89 | 13 |
14,388 | def reactivate ( credit_card_id : str ) -> None : logger . info ( 'reactivating-credit-card' , credit_card_id = credit_card_id ) with transaction . atomic ( ) : cc = CreditCard . objects . get ( pk = credit_card_id ) cc . reactivate ( ) cc . save ( ) | Reactivates a credit card . | 79 | 7 |
14,389 | def sync ( self , syncPointList ) : if len ( syncPointList ) == 0 : return subsCopy = self . _subs . clone ( ) syncPointList . sort ( ) SubAssert ( syncPointList [ 0 ] . subNo >= 0 ) SubAssert ( syncPointList [ 0 ] . subNo < subsCopy . size ( ) ) SubAssert ( syncPointList [ - 1 ] . subNo < subsCopy . size ( ) ) # Always start from the first subtitle. firstSyncPoint = self . _getLowestSyncPoint ( syncPointList , subsCopy ) if firstSyncPoint != syncPointList [ 0 ] : syncPointList . insert ( 0 , firstSyncPoint ) for i , syncPoint in enumerate ( syncPointList ) : # Algorithm: # 1. Calculate time deltas between sync points and between subs: # DE_OLD = subTime[secondSyncSubNo] - subTime[firstSyncSubNo] # DE_NEW = secondSyncTime - firstSyncTime # 2. Calculate proportional sub position within DE_OLD: # d = (subTime - subTime[firstSubNo]) / DE_OLD # 3. "d" is constant within deltas, so we can now calculate newSubTime: # newSubTime = DE_NEW * d + firstSyncTime firstSyncPoint = syncPointList [ i ] secondSyncPoint = self . _getSyncPointOrEnd ( i + 1 , syncPointList , subsCopy ) log . debug ( _ ( "Syncing times for sync points:" ) ) log . debug ( " %s" % firstSyncPoint ) log . debug ( " %s" % secondSyncPoint ) # A case for the last one syncPoint if firstSyncPoint == secondSyncPoint : continue secondSubNo = secondSyncPoint . subNo firstSubNo = firstSyncPoint . subNo firstOldSub = subsCopy [ firstSubNo ] secondOldSub = subsCopy [ secondSubNo ] oldStartDelta , oldEndDelta = self . _getDeltas ( firstOldSub , secondOldSub ) newStartDelta , newEndDelta = self . _getDeltas ( firstSyncPoint , secondSyncPoint ) for subNo in range ( firstSubNo , secondSubNo + 1 ) : sub = subsCopy [ subNo ] newStartTime = self . _calculateTime ( sub . start , firstOldSub . start , firstSyncPoint . start , oldStartDelta , newStartDelta ) newEndTime = self . _calculateTime ( sub . end , firstOldSub . end , firstSyncPoint . end , oldEndDelta , newEndDelta ) self . _subs . changeSubStart ( subNo , newStartTime ) self . _subs . changeSubEnd ( subNo , newEndTime ) | Synchronise subtitles using a given list of SyncPoints . | 602 | 12 |
14,390 | def _getDeltas ( self , firstSub , secondSub ) : startDelta = max ( firstSub . start , secondSub . start ) - min ( firstSub . start , secondSub . start ) endDelta = max ( firstSub . end , secondSub . end ) - min ( firstSub . end , secondSub . end ) return ( startDelta , endDelta ) | Arguments must have start and end properties which are FrameTimes . | 80 | 13 |
14,391 | async def scan_for_units ( self , iprange ) : units = [ ] for ip_address in ipaddress . IPv4Network ( iprange ) : sock = socket . socket ( ) sock . settimeout ( 0.02 ) host = str ( ip_address ) try : scan_result = sock . connect ( ( host , PORT ) ) except socket . error : scan_result = 1 _LOGGER . debug ( 'Checking port connectivity on %s:%s' , host , ( str ( PORT ) ) ) if scan_result is None : ghlocalapi = DeviceInfo ( self . _loop , self . _session , host ) await ghlocalapi . get_device_info ( ) data = ghlocalapi . device_info if data is not None : cap = data [ 'device_info' ] [ 'capabilities' ] units . append ( { 'host' : host , 'name' : data [ 'name' ] , 'model' : data [ 'device_info' ] [ 'model_name' ] , 'assistant_supported' : cap . get ( 'assistant_supported' , False ) } ) sock . close ( ) return units | Scan local network for GH units . | 255 | 7 |
14,392 | async def bluetooth_scan ( ) : async with aiohttp . ClientSession ( ) as session : ghlocalapi = Bluetooth ( LOOP , session , IPADDRESS ) await ghlocalapi . scan_for_devices ( ) # Start device scan await ghlocalapi . get_scan_result ( ) # Returns the result print ( "Device info:" , ghlocalapi . devices ) | Get nearby bluetooth devices . | 84 | 6 |
14,393 | def map_predict ( interface , state , label , inp ) : import numpy as np out = interface . output ( 0 ) continuous = [ j for i , j in enumerate ( state [ "X_indices" ] ) if state [ "X_meta" ] [ i ] == "c" ] # indices of continuous features discrete = [ j for i , j in enumerate ( state [ "X_indices" ] ) if state [ "X_meta" ] [ i ] == "d" ] # indices of discrete features cont = True if len ( continuous ) > 0 else False # enables calculation of Gaussian probabilities disc = True if len ( discrete ) > 0 else False # enables calculation of multinomial probabilities. for row in inp : row = row . strip ( ) . split ( state [ "delimiter" ] ) if len ( row ) > 1 : # if row is empty # set id of a sample x_id = "" if state [ "id_index" ] == - 1 else row [ state [ "id_index" ] ] # initialize prior probability for all labels probs = state [ "fit_model" ] [ "prior_log" ] if cont : # continuous features x = np . array ( [ ( 0 if row [ j ] in state [ "missing_vals" ] else float ( row [ j ] ) ) for j in continuous ] ) # sets selected features of the sample # Gaussian distribution probs = probs - 0.5 * np . sum ( np . true_divide ( ( x - state [ "fit_model" ] [ "mean" ] ) ** 2 , state [ "fit_model" ] [ "var" ] ) + state [ "fit_model" ] [ "var_log" ] , axis = 1 ) if disc : # discrete features # multinomial distribution probs = probs + np . sum ( [ ( 0 if row [ i ] in state [ "missing_vals" ] else state [ "fit_model" ] . get ( ( str ( i ) , row [ i ] ) , np . zeros ( 1 ) ) ) for i in discrete ] , axis = 0 ) # normalize by P(x) = P(f_1, ..., f_n) log_prob_x = np . log ( np . sum ( np . exp ( probs ) ) ) probs = np . exp ( np . array ( probs ) - log_prob_x ) # Predicted label is the one with highest probability y_predicted = max ( zip ( probs , state [ "fit_model" ] [ "y_labels" ] ) ) [ 1 ] out . add ( x_id , ( y_predicted , probs . tolist ( ) ) ) | Function makes a predictions of samples with given model . It calculates probabilities with multinomial and Gaussian distribution . | 601 | 22 |
14,394 | def predict ( dataset , fitmodel_url , m = 1 , save_results = True , show = False ) : from disco . worker . pipeline . worker import Worker , Stage from disco . core import Job , result_iterator import numpy as np try : m = float ( m ) except ValueError : raise Exception ( "Parameter m should be numerical." ) if "naivebayes_fitmodel" in fitmodel_url : # fit model is loaded from ddfs fit_model = dict ( ( k , v ) for k , v in result_iterator ( fitmodel_url [ "naivebayes_fitmodel" ] ) ) if len ( fit_model [ "y_labels" ] ) < 2 : print "There is only one class in training data." return [ ] else : raise Exception ( "Incorrect fit model." ) if dataset . params [ "X_meta" ] . count ( "d" ) > 0 : # if there are discrete features in the model # code calculates logarithms to optimize predict phase as opposed to calculation by every mapped. np . seterr ( divide = 'ignore' ) for iv in fit_model [ "iv" ] : dist = [ fit_model . pop ( ( y , ) + iv , 0 ) for y in fit_model [ "y_labels" ] ] fit_model [ iv ] = np . nan_to_num ( np . log ( np . true_divide ( np . array ( dist ) + m * fit_model [ "prior" ] , np . sum ( dist ) + m ) ) ) - fit_model [ "prior_log" ] del ( fit_model [ "iv" ] ) # define a job and set save of results to ddfs job = Job ( worker = Worker ( save_results = save_results ) ) # job parallelizes execution of mappers job . pipeline = [ ( "split" , Stage ( "map" , input_chain = dataset . params [ "input_chain" ] , init = simple_init , process = map_predict ) ) ] job . params = dataset . params # job parameters (dataset object) job . params [ "fit_model" ] = fit_model # define name of a job and input data urls job . run ( name = "naivebayes_predict" , input = dataset . params [ "data_tag" ] ) results = job . wait ( show = show ) return results | Function starts a job that makes predictions to input data with a given model | 531 | 14 |
14,395 | def data ( self ) : if self . _data : return self . _data retval = { } data = self . get_request_data ( ) for subdata in data : for key , value in subdata . iteritems ( ) : if not key in retval : retval [ key ] = value self . _data = retval return retval | Returns the request data as a dictionary . | 76 | 8 |
14,396 | def get_resource ( self , resource , * * kwargs ) : return resource ( request = self . request , response = self . response , path_params = self . path_params , application = self . application , * * kwargs ) | Returns a new instance of the resource class passed in as resource . This is a helper to make future - compatibility easier when new arguments get added to the constructor . | 53 | 32 |
14,397 | def assert_conditions ( self ) : self . assert_condition_md5 ( ) etag = self . clean_etag ( self . call_method ( 'get_etag' ) ) self . response . last_modified = self . call_method ( 'get_last_modified' ) self . assert_condition_etag ( ) self . assert_condition_last_modified ( ) | Handles various HTTP conditions and raises HTTP exceptions to abort the request . | 86 | 14 |
14,398 | def assert_condition_md5 ( self ) : if 'Content-MD5' in self . request . headers : body_md5 = hashlib . md5 ( self . request . body ) . hexdigest ( ) if body_md5 != self . request . headers [ 'Content-MD5' ] : raise_400 ( self , msg = 'Invalid Content-MD5 request header.' ) | If the Content - MD5 request header is present in the request it s verified against the MD5 hash of the request body . If they don t match a 400 HTTP response is returned . | 86 | 38 |
14,399 | def get_allowed_methods ( self ) : return ", " . join ( [ method for method in dir ( self ) if method . upper ( ) == method and callable ( getattr ( self , method ) ) ] ) | Returns a coma - separated list of method names that are allowed on this instance . Useful to set the Allowed response header . | 48 | 25 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.