idx
int64
0
251k
question
stringlengths
53
3.53k
target
stringlengths
5
1.23k
len_question
int64
20
893
len_target
int64
3
238
25,400
def get_info ( node_cfg ) : node_cfg = node_cfg if isinstance ( node_cfg , dict ) else { "name" : node_cfg } return node_cfg . get ( "name" ) , node_cfg . get ( "fields" , { } )
Return a tuple with the verbal name of a node and a dict of field names .
62
17
25,401
def isinstance ( self , instance , class_name ) : if isinstance ( instance , BaseNode ) : klass = self . dynamic_node_classes . get ( class_name , None ) if klass : return isinstance ( instance , klass ) # Not an instance of a class in the registry return False else : raise TypeError ( "This function can only be used for BaseNode objects" )
Check if a BaseNode is an instance of a registered dynamic class
86
13
25,402
def get_transformer ( cls , method_name ) : transform_function = getattr ( cls , method_name ) assert callable ( transform_function ) def transformer_method ( self , node ) : kwargs = { } if inspect . signature ( transform_function ) . parameters . get ( "helper" ) : kwargs [ "helper" ] = self . helper return transform_function ( node , * * kwargs ) return transformer_method
Get method to bind to visitor
102
6
25,403
def visitTerminal ( self , ctx ) : text = ctx . getText ( ) return Terminal . from_text ( text , ctx )
Converts case insensitive keywords and identifiers to lowercase
32
10
25,404
def run ( self , * args ) : params = self . parser . parse_args ( args ) entry = params . entry if params . add : code = self . add ( entry ) elif params . delete : code = self . delete ( entry ) else : term = entry code = self . blacklist ( term ) return code
List add or delete entries from the blacklist .
68
9
25,405
def add ( self , entry ) : # Empty or None values for organizations are not allowed if not entry : return CMD_SUCCESS try : api . add_to_matching_blacklist ( self . db , entry ) except InvalidValueError as e : # If the code reaches here, something really wrong has happened # because entry cannot be None or empty raise RuntimeError ( str ( e ) ) except AlreadyExistsError as e : msg = "%s already exists in the registry" % entry self . error ( msg ) return e . code return CMD_SUCCESS
Add entries to the blacklist .
122
6
25,406
def delete ( self , entry ) : if not entry : return CMD_SUCCESS try : api . delete_from_matching_blacklist ( self . db , entry ) except NotFoundError as e : self . error ( str ( e ) ) return e . code return CMD_SUCCESS
Remove entries from the blacklist .
66
6
25,407
def blacklist ( self , term = None ) : try : bl = api . blacklist ( self . db , term ) self . display ( 'blacklist.tmpl' , blacklist = bl ) except NotFoundError as e : self . error ( str ( e ) ) return e . code return CMD_SUCCESS
List blacklisted entries .
67
5
25,408
def run ( self , * args ) : params = self . parser . parse_args ( args ) config_file = os . path . expanduser ( '~/.sortinghat' ) if params . action == 'get' : code = self . get ( params . parameter , config_file ) elif params . action == 'set' : code = self . set ( params . parameter , params . value , config_file ) else : raise RuntimeError ( "Not get or set action given" ) return code
Get and set configuration parameters .
108
6
25,409
def get ( self , key , filepath ) : if not filepath : raise RuntimeError ( "Configuration file not given" ) if not self . __check_config_key ( key ) : raise RuntimeError ( "%s parameter does not exists" % key ) if not os . path . isfile ( filepath ) : raise RuntimeError ( "%s config file does not exist" % filepath ) section , option = key . split ( '.' ) config = configparser . SafeConfigParser ( ) config . read ( filepath ) try : option = config . get ( section , option ) self . display ( 'config.tmpl' , key = key , option = option ) except ( configparser . NoSectionError , configparser . NoOptionError ) : pass return CMD_SUCCESS
Get configuration parameter .
168
4
25,410
def set ( self , key , value , filepath ) : if not filepath : raise RuntimeError ( "Configuration file not given" ) if not self . __check_config_key ( key ) : raise RuntimeError ( "%s parameter does not exists or cannot be set" % key ) config = configparser . SafeConfigParser ( ) if os . path . isfile ( filepath ) : config . read ( filepath ) section , option = key . split ( '.' ) if section not in config . sections ( ) : config . add_section ( section ) try : config . set ( section , option , value ) except TypeError as e : raise RuntimeError ( str ( e ) ) try : with open ( filepath , 'w' ) as f : config . write ( f ) except IOError as e : raise RuntimeError ( str ( e ) ) return CMD_SUCCESS
Set configuration parameter .
189
4
25,411
def __check_config_key ( self , key ) : try : section , option = key . split ( '.' ) except ( AttributeError , ValueError ) : return False if not section or not option : return False return section in Config . CONFIG_OPTIONS and option in Config . CONFIG_OPTIONS [ section ]
Check whether the key is valid .
70
7
25,412
def run ( self , * args ) : params = self . parser . parse_args ( args ) with params . outfile as outfile : if params . identities : code = self . export_identities ( outfile , params . source ) elif params . orgs : code = self . export_organizations ( outfile ) else : # The running proccess never should reach this section raise RuntimeError ( "Unexpected export option" ) return code
Export data from the registry .
95
6
25,413
def export_identities ( self , outfile , source = None ) : exporter = SortingHatIdentitiesExporter ( self . db ) dump = exporter . export ( source ) try : outfile . write ( dump ) outfile . write ( '\n' ) except IOError as e : raise RuntimeError ( str ( e ) ) return CMD_SUCCESS
Export identities information to a file .
81
7
25,414
def export_organizations ( self , outfile ) : exporter = SortingHatOrganizationsExporter ( self . db ) dump = exporter . export ( ) try : outfile . write ( dump ) outfile . write ( '\n' ) except IOError as e : raise RuntimeError ( str ( e ) ) return CMD_SUCCESS
Export organizations information to a file .
76
7
25,415
def export ( self , source = None ) : uidentities = { } uids = api . unique_identities ( self . db , source = source ) for uid in uids : enrollments = [ rol . to_dict ( ) for rol in api . enrollments ( self . db , uuid = uid . uuid ) ] u = uid . to_dict ( ) u [ 'identities' ] . sort ( key = lambda x : x [ 'id' ] ) uidentities [ uid . uuid ] = u uidentities [ uid . uuid ] [ 'enrollments' ] = enrollments blacklist = [ mb . excluded for mb in api . blacklist ( self . db ) ] obj = { 'time' : str ( datetime . datetime . now ( ) ) , 'source' : source , 'blacklist' : blacklist , 'organizations' : { } , 'uidentities' : uidentities } return json . dumps ( obj , default = self . _json_encoder , indent = 4 , separators = ( ',' , ': ' ) , sort_keys = True )
Export a set of unique identities .
250
7
25,416
def export ( self ) : organizations = { } orgs = api . registry ( self . db ) for org in orgs : domains = [ { 'domain' : dom . domain , 'is_top' : dom . is_top_domain } for dom in org . domains ] domains . sort ( key = lambda x : x [ 'domain' ] ) organizations [ org . name ] = domains obj = { 'time' : str ( datetime . datetime . now ( ) ) , 'blacklist' : [ ] , 'organizations' : organizations , 'uidentities' : { } } return json . dumps ( obj , default = self . _json_encoder , indent = 4 , separators = ( ',' , ': ' ) , sort_keys = True )
Export a set of organizations .
167
6
25,417
def run ( self , * args ) : params = self . parser . parse_args ( args ) sources = params . source code = self . autocomplete ( sources ) return code
Autocomplete profile information .
38
6
25,418
def autocomplete ( self , sources ) : email_pattern = re . compile ( EMAIL_ADDRESS_REGEX ) identities = self . __select_autocomplete_identities ( sources ) for uuid , ids in identities . items ( ) : # Among the identities (with the same priority) selected # to complete the profile, it will choose the longest 'name'. # If no name is available, it will use the field 'username'. name = None email = None for identity in ids : oldname = name if not name : name = identity . name or identity . username elif identity . name and len ( identity . name ) > len ( name ) : name = identity . name # Do not set email addresses on the name field if name and email_pattern . match ( name ) : name = oldname if not email and identity . email : email = identity . email kw = { 'name' : name , 'email' : email } try : api . edit_profile ( self . db , uuid , * * kw ) self . display ( 'autoprofile.tmpl' , identity = identity ) except ( NotFoundError , InvalidValueError ) as e : self . error ( str ( e ) ) return e . code return CMD_SUCCESS
Autocomplete unique identities profiles .
276
7
25,419
def __select_autocomplete_identities ( self , sources ) : MIN_PRIORITY = 99999999 checked = { } for source in sources : uids = api . unique_identities ( self . db , source = source ) for uid in uids : if uid . uuid in checked : continue max_priority = MIN_PRIORITY selected = [ ] for identity in sorted ( uid . identities , key = lambda x : x . id ) : try : priority = sources . index ( identity . source ) if priority < max_priority : selected = [ identity ] max_priority = priority elif priority == max_priority : selected . append ( identity ) except ValueError : continue checked [ uid . uuid ] = selected identities = collections . OrderedDict ( sorted ( checked . items ( ) , key = lambda t : t [ 0 ] ) ) return identities
Select the identities used for autocompleting
190
8
25,420
def run ( self , * args ) : params = self . parser . parse_args ( args ) code = self . show ( params . uuid , params . term ) return code
Show information about unique identities .
38
6
25,421
def show ( self , uuid = None , term = None ) : try : if uuid : uidentities = api . unique_identities ( self . db , uuid ) elif term : uidentities = api . search_unique_identities ( self . db , term ) else : uidentities = api . unique_identities ( self . db ) for uid in uidentities : # Add enrollments to a new property 'roles' enrollments = api . enrollments ( self . db , uid . uuid ) uid . roles = enrollments self . display ( 'show.tmpl' , uidentities = uidentities ) except NotFoundError as e : self . error ( str ( e ) ) return e . code return CMD_SUCCESS
Show the information related to unique identities .
170
8
25,422
def __parse_organizations ( self , json ) : try : for company in json [ 'companies' ] : name = self . __encode ( company [ 'company_name' ] ) org = self . _organizations . get ( name , None ) if not org : org = Organization ( name = name ) self . _organizations [ name ] = org for domain in company [ 'domains' ] : if not domain : continue dom = Domain ( domain = domain ) org . domains . append ( dom ) except KeyError as e : msg = "invalid json format. Attribute %s not found" % e . args raise InvalidFormatError ( cause = msg )
Parse Stackalytics organizations .
144
7
25,423
def __parse_identities ( self , json ) : try : for user in json [ 'users' ] : name = self . __encode ( user [ 'user_name' ] ) uuid = name uid = UniqueIdentity ( uuid = uuid ) identity = Identity ( name = name , email = None , username = None , source = self . source , uuid = uuid ) uid . identities . append ( identity ) for email_addr in user [ 'emails' ] : email = self . __encode ( email_addr ) identity = Identity ( name = name , email = email , username = None , source = self . source , uuid = uuid ) uid . identities . append ( identity ) for site_id in [ 'gerrit_id' , 'launchpad_id' ] : username = user . get ( site_id , None ) if not username : continue username = self . __encode ( username ) source = self . source + ':' + site_id . replace ( '_id' , '' ) identity = Identity ( name = name , email = None , username = username , source = source , uuid = uuid ) uid . identities . append ( identity ) for rol in self . __parse_enrollments ( user ) : uid . enrollments . append ( rol ) self . _identities [ uuid ] = uid except KeyError as e : msg = "invalid json format. Attribute %s not found" % e . args raise InvalidFormatError ( cause = msg )
Parse identities using Stackalytics format .
335
9
25,424
def __parse_enrollments ( self , user ) : enrollments = [ ] for company in user [ 'companies' ] : name = company [ 'company_name' ] org = self . _organizations . get ( name , None ) if not org : org = Organization ( name = name ) self . _organizations [ name ] = org start_date = MIN_PERIOD_DATE end_date = MAX_PERIOD_DATE if company [ 'end_date' ] : end_date = str_to_datetime ( company [ 'end_date' ] ) rol = Enrollment ( start = start_date , end = end_date , organization = org ) enrollments . append ( rol ) return enrollments
Parse user enrollments
162
5
25,425
def __load_json ( self , stream ) : import json try : return json . loads ( stream ) except ValueError as e : cause = "invalid json format. %s" % str ( e ) raise InvalidFormatError ( cause = cause )
Load json stream into a dict object
53
7
25,426
def __parse ( self , stream , has_orgs ) : if has_orgs : self . __parse_organizations ( stream ) else : self . __parse_identities ( stream )
Parse identities and organizations using mailmap format .
42
10
25,427
def __parse_organizations ( self , stream ) : for aliases in self . __parse_stream ( stream ) : # Parse identity identity = self . __parse_alias ( aliases [ 1 ] ) uuid = identity . email uid = self . _identities . get ( uuid , None ) if not uid : uid = UniqueIdentity ( uuid = uuid ) identity . uuid = uuid uid . identities . append ( identity ) self . _identities [ uuid ] = uid # Parse organization mailmap_id = aliases [ 0 ] name = self . __encode ( mailmap_id [ 0 ] ) if name in MAILMAP_NO_ORGS : continue org = Organization ( name = name ) self . _organizations [ name ] = org enrollment = Enrollment ( start = MIN_PERIOD_DATE , end = MAX_PERIOD_DATE , organization = org ) uid . enrollments . append ( enrollment )
Parse organizations stream
212
4
25,428
def __parse_identities ( self , stream ) : for aliases in self . __parse_stream ( stream ) : identity = self . __parse_alias ( aliases [ 0 ] ) uuid = identity . email uid = self . _identities . get ( uuid , None ) if not uid : uid = UniqueIdentity ( uuid = uuid ) identity . uuid = uuid uid . identities . append ( identity ) self . _identities [ uuid ] = uid profile = Profile ( uuid = uuid , name = identity . name , email = identity . email , is_bot = False ) uid . profile = profile # Aliases for alias in aliases [ 1 : ] : identity = self . __parse_alias ( alias , uuid ) uid . identities . append ( identity ) self . _identities [ uuid ] = uid
Parse identities stream
188
4
25,429
def __parse_stream ( self , stream ) : nline = 0 lines = stream . split ( '\n' ) for line in lines : nline += 1 # Ignore blank lines and comments m = re . match ( self . LINES_TO_IGNORE_REGEX , line , re . UNICODE ) if m : continue line = line . strip ( '\n' ) . strip ( ' ' ) parts = line . split ( '>' ) if len ( parts ) == 0 : cause = "line %s: invalid format" % str ( nline ) raise InvalidFormatError ( cause = cause ) aliases = [ ] for part in parts : part = part . replace ( ',' , ' ' ) part = part . strip ( '\n' ) . strip ( ' ' ) if len ( part ) == 0 : continue if part . find ( '<' ) < 0 : cause = "line %s: invalid format" % str ( nline ) raise InvalidFormatError ( cause = cause ) alias = email . utils . parseaddr ( part + '>' ) aliases . append ( alias ) yield aliases
Generic method to parse mailmap streams
240
7
25,430
def run ( self , * args ) : params = self . parser . parse_args ( args ) from_uuid = params . from_uuid to_uuid = params . to_uuid code = self . merge ( from_uuid , to_uuid ) return code
Merge two identities .
61
5
25,431
def create_identity_matcher ( matcher = 'default' , blacklist = None , sources = None , strict = True ) : import sortinghat . matching as matching if matcher not in matching . SORTINGHAT_IDENTITIES_MATCHERS : raise MatcherNotSupportedError ( matcher = str ( matcher ) ) klass = matching . SORTINGHAT_IDENTITIES_MATCHERS [ matcher ] return klass ( blacklist = blacklist , sources = sources , strict = strict )
Create an identity matcher of the given type .
109
10
25,432
def match ( uidentities , matcher , fastmode = False ) : if not isinstance ( matcher , IdentityMatcher ) : raise TypeError ( "matcher is not an instance of IdentityMatcher" ) if fastmode : try : matcher . matching_criteria ( ) except NotImplementedError : name = "'%s (fast mode)'" % matcher . __class__ . __name__ . lower ( ) raise MatcherNotSupportedError ( matcher = name ) filtered , no_filtered , uuids = _filter_unique_identities ( uidentities , matcher ) if not fastmode : matched = _match ( filtered , matcher ) else : matched = _match_with_pandas ( filtered , matcher ) matched = _build_matches ( matched , uuids , no_filtered , fastmode ) return matched
Find matches in a set of unique identities .
188
9
25,433
def _match ( filtered , matcher ) : def match_filtered_identities ( x , ids , matcher ) : """Check if an identity matches a set of identities""" for y in ids : if x . uuid == y . uuid : return True if matcher . match_filtered_identities ( x , y ) : return True return False # Find subsets of matches matched = [ ] while filtered : candidates = [ ] no_match = [ ] x = filtered . pop ( 0 ) while matched : ids = matched . pop ( 0 ) if match_filtered_identities ( x , ids , matcher ) : candidates += ids else : no_match . append ( ids ) candidates . append ( x ) # Generate the new list of matched subsets matched = [ candidates ] + no_match return matched
Old method to find matches in a set of filtered identities .
182
12
25,434
def _match_with_pandas ( filtered , matcher ) : import pandas data = [ fl . to_dict ( ) for fl in filtered ] if not data : return [ ] df = pandas . DataFrame ( data ) df = df . sort_values ( [ 'uuid' ] ) cdfs = [ ] criteria = matcher . matching_criteria ( ) for c in criteria : cdf = df [ [ 'id' , 'uuid' , c ] ] cdf = cdf . dropna ( subset = [ c ] ) cdf = pandas . merge ( cdf , cdf , on = c , how = 'left' ) cdf = cdf [ [ 'uuid_x' , 'uuid_y' ] ] cdfs . append ( cdf ) result = pandas . concat ( cdfs ) result = result . drop_duplicates ( ) groups = result . groupby ( by = [ 'uuid_x' ] , as_index = True , sort = True ) matched = _calculate_matches_closures ( groups ) return matched
Find matches in a set using Pandas library .
244
10
25,435
def _filter_unique_identities ( uidentities , matcher ) : filtered = [ ] no_filtered = [ ] uuids = { } for uidentity in uidentities : n = len ( filtered ) filtered += matcher . filter ( uidentity ) if len ( filtered ) > n : uuids [ uidentity . uuid ] = uidentity else : no_filtered . append ( [ uidentity ] ) return filtered , no_filtered , uuids
Filter a set of unique identities .
109
7
25,436
def _build_matches ( matches , uuids , no_filtered , fastmode = False ) : result = [ ] for m in matches : mk = m [ 0 ] . uuid if not fastmode else m [ 0 ] subset = [ uuids [ mk ] ] for id_ in m [ 1 : ] : uk = id_ . uuid if not fastmode else id_ u = uuids [ uk ] if u not in subset : subset . append ( u ) result . append ( subset ) result += no_filtered result . sort ( key = len , reverse = True ) sresult = [ ] for r in result : r . sort ( key = lambda id_ : id_ . uuid ) sresult . append ( r ) return sresult
Build a list with matching subsets
167
7
25,437
def _calculate_matches_closures ( groups ) : matches = [ ] ns = sorted ( groups . groups . keys ( ) ) while ns : n = ns . pop ( 0 ) visited = [ n ] vs = [ v for v in groups . get_group ( n ) [ 'uuid_y' ] ] while vs : v = vs . pop ( 0 ) if v in visited : continue nvs = [ nv for nv in groups . get_group ( v ) [ 'uuid_y' ] ] vs += nvs visited . append ( v ) try : ns . remove ( v ) except : pass matches . append ( visited ) return matches
Find the transitive closure of each unique identity .
144
10
25,438
def match ( self , a , b ) : if not isinstance ( a , UniqueIdentity ) : raise ValueError ( "<a> is not an instance of UniqueIdentity" ) if not isinstance ( b , UniqueIdentity ) : raise ValueError ( "<b> is not an instance of UniqueIdentity" ) if a . uuid and b . uuid and a . uuid == b . uuid : return True filtered_a = self . filter ( a ) filtered_b = self . filter ( b ) for fa in filtered_a : for fb in filtered_b : if self . match_filtered_identities ( fa , fb ) : return True return False
Determine if two unique identities are the same .
147
11
25,439
def find_unique_identity ( session , uuid ) : uidentity = session . query ( UniqueIdentity ) . filter ( UniqueIdentity . uuid == uuid ) . first ( ) return uidentity
Find a unique identity .
47
5
25,440
def find_identity ( session , id_ ) : identity = session . query ( Identity ) . filter ( Identity . id == id_ ) . first ( ) return identity
Find an identity .
36
4
25,441
def find_organization ( session , name ) : organization = session . query ( Organization ) . filter ( Organization . name == name ) . first ( ) return organization
Find an organization .
34
4
25,442
def find_domain ( session , name ) : domain = session . query ( Domain ) . filter ( Domain . domain == name ) . first ( ) return domain
Find a domain .
33
4
25,443
def find_country ( session , code ) : country = session . query ( Country ) . filter ( Country . code == code ) . first ( ) return country
Find a country .
33
4
25,444
def add_unique_identity ( session , uuid ) : if uuid is None : raise ValueError ( "'uuid' cannot be None" ) if uuid == '' : raise ValueError ( "'uuid' cannot be an empty string" ) uidentity = UniqueIdentity ( uuid = uuid ) uidentity . profile = Profile ( ) uidentity . last_modified = datetime . datetime . utcnow ( ) session . add ( uidentity ) return uidentity
Add a unique identity to the session .
108
8
25,445
def add_identity ( session , uidentity , identity_id , source , name = None , email = None , username = None ) : if identity_id is None : raise ValueError ( "'identity_id' cannot be None" ) if identity_id == '' : raise ValueError ( "'identity_id' cannot be an empty string" ) if source is None : raise ValueError ( "'source' cannot be None" ) if source == '' : raise ValueError ( "'source' cannot be an empty string" ) if not ( name or email or username ) : raise ValueError ( "identity data cannot be None or empty" ) identity = Identity ( id = identity_id , name = name , email = email , username = username , source = source ) identity . last_modified = datetime . datetime . utcnow ( ) identity . uidentity = uidentity identity . uidentity . last_modified = identity . last_modified session . add ( identity ) return identity
Add an identity to the session .
213
7
25,446
def delete_identity ( session , identity ) : uidentity = identity . uidentity uidentity . last_modified = datetime . datetime . utcnow ( ) session . delete ( identity ) session . flush ( )
Remove an identity from the session .
50
7
25,447
def add_organization ( session , name ) : if name is None : raise ValueError ( "'name' cannot be None" ) if name == '' : raise ValueError ( "'name' cannot be an empty string" ) organization = Organization ( name = name ) session . add ( organization ) return organization
Add an organization to the session .
63
7
25,448
def delete_organization ( session , organization ) : last_modified = datetime . datetime . utcnow ( ) for enrollment in organization . enrollments : enrollment . uidentity . last_modified = last_modified session . delete ( organization ) session . flush ( )
Remove an organization from the session .
58
7
25,449
def add_domain ( session , organization , domain_name , is_top_domain = False ) : if domain_name is None : raise ValueError ( "'domain_name' cannot be None" ) if domain_name == '' : raise ValueError ( "'domain_name' cannot be an empty string" ) if not isinstance ( is_top_domain , bool ) : raise ValueError ( "'is_top_domain' must have a boolean value" ) dom = Domain ( domain = domain_name , is_top_domain = is_top_domain ) dom . organization = organization session . add ( dom ) return dom
Add a domain to the session .
133
7
25,450
def delete_enrollment ( session , enrollment ) : uidentity = enrollment . uidentity uidentity . last_modified = datetime . datetime . utcnow ( ) session . delete ( enrollment ) session . flush ( )
Remove an enrollment from the session .
50
7
25,451
def move_enrollment ( session , enrollment , uidentity ) : if enrollment . uuid == uidentity . uuid : return False old_uidentity = enrollment . uidentity enrollment . uidentity = uidentity last_modified = datetime . datetime . utcnow ( ) old_uidentity . last_modified = last_modified uidentity . last_modified = last_modified session . add ( uidentity ) session . add ( old_uidentity ) return True
Move an enrollment to a unique identity .
109
8
25,452
def add_to_matching_blacklist ( session , term ) : if term is None : raise ValueError ( "'term' to blacklist cannot be None" ) if term == '' : raise ValueError ( "'term' to blacklist cannot be an empty string" ) mb = MatchingBlacklist ( excluded = term ) session . add ( mb ) return mb
Add term to the matching blacklist .
78
7
25,453
def genderize ( name , api_token = None ) : GENDERIZE_API_URL = "https://api.genderize.io/" TOTAL_RETRIES = 10 MAX_RETRIES = 5 SLEEP_TIME = 0.25 STATUS_FORCELIST = [ 502 ] params = { 'name' : name } if api_token : params [ 'apikey' ] = api_token session = requests . Session ( ) retries = urllib3 . util . Retry ( total = TOTAL_RETRIES , connect = MAX_RETRIES , status = MAX_RETRIES , status_forcelist = STATUS_FORCELIST , backoff_factor = SLEEP_TIME , raise_on_status = True ) session . mount ( 'http://' , requests . adapters . HTTPAdapter ( max_retries = retries ) ) session . mount ( 'https://' , requests . adapters . HTTPAdapter ( max_retries = retries ) ) r = session . get ( GENDERIZE_API_URL , params = params ) r . raise_for_status ( ) result = r . json ( ) gender = result [ 'gender' ] prob = result . get ( 'probability' , None ) acc = int ( prob * 100 ) if prob else None return gender , acc
Fetch gender from genderize . io
291
8
25,454
def run ( self , * args ) : params = self . parser . parse_args ( args ) api_token = params . api_token genderize_all = params . genderize_all code = self . autogender ( api_token = api_token , genderize_all = genderize_all ) return code
Autocomplete gender information .
69
6
25,455
def autogender ( self , api_token = None , genderize_all = False ) : name_cache = { } no_gender = not genderize_all pattern = re . compile ( r"(^\w+)\s\w+" ) profiles = api . search_profiles ( self . db , no_gender = no_gender ) for profile in profiles : if not profile . name : continue name = profile . name . strip ( ) m = pattern . match ( name ) if not m : continue firstname = m . group ( 1 ) . lower ( ) if firstname in name_cache : gender_data = name_cache [ firstname ] else : try : gender , acc = genderize ( firstname , api_token ) except ( requests . exceptions . RequestException , requests . exceptions . RetryError ) as e : msg = "Skipping '%s' name (%s) due to a connection error. Error: %s" msg = msg % ( firstname , profile . uuid , str ( e ) ) self . warning ( msg ) continue gender_data = { 'gender' : gender , 'gender_acc' : acc } name_cache [ firstname ] = gender_data if not gender_data [ 'gender' ] : continue try : api . edit_profile ( self . db , profile . uuid , * * gender_data ) self . display ( 'autogender.tmpl' , uuid = profile . uuid , name = profile . name , gender_data = gender_data ) except ( NotFoundError , InvalidValueError ) as e : self . error ( str ( e ) ) return e . code return CMD_SUCCESS
Autocomplete gender information of unique identities .
363
9
25,456
def __parse_identities ( self , json ) : try : for mozillian in json [ 'results' ] : name = self . __encode ( mozillian [ 'full_name' ] [ 'value' ] ) email = self . __encode ( mozillian [ 'email' ] [ 'value' ] ) username = self . __encode ( mozillian [ 'username' ] ) uuid = username uid = UniqueIdentity ( uuid = uuid ) identity = Identity ( name = name , email = email , username = username , source = self . source , uuid = uuid ) uid . identities . append ( identity ) # Alternate emails for alt_email in mozillian [ 'alternate_emails' ] : alt_email = self . __encode ( alt_email [ 'email' ] ) if alt_email == email : continue identity = Identity ( name = name , email = alt_email , username = username , source = self . source , uuid = uuid ) uid . identities . append ( identity ) # IRC account ircname = self . __encode ( mozillian [ 'ircname' ] [ 'value' ] ) if ircname and ircname != username : identity = Identity ( name = None , email = None , username = ircname , source = self . source , uuid = uuid ) uid . identities . append ( identity ) # Mozilla affiliation affiliation = mozillian [ 'date_mozillian' ] rol = self . __parse_mozillian_affiliation ( affiliation ) uid . enrollments . append ( rol ) self . _identities [ uuid ] = uid except KeyError as e : msg = "invalid json format. Attribute %s not found" % e . args raise InvalidFormatError ( cause = msg )
Parse identities using Mozillians format .
399
9
25,457
def run ( self , * args ) : params = self . parser . parse_args ( args ) organization = params . organization domain = params . domain is_top_domain = params . top_domain overwrite = params . overwrite if params . add : code = self . add ( organization , domain , is_top_domain , overwrite ) elif params . delete : code = self . delete ( organization , domain ) else : term = organization code = self . registry ( term ) return code
List add or delete organizations and domains from the registry .
101
11
25,458
def add ( self , organization , domain = None , is_top_domain = False , overwrite = False ) : # Empty or None values for organizations are not allowed if not organization : return CMD_SUCCESS if not domain : try : api . add_organization ( self . db , organization ) except InvalidValueError as e : # If the code reaches here, something really wrong has happened # because organization cannot be None or empty raise RuntimeError ( str ( e ) ) except AlreadyExistsError as e : msg = "organization '%s' already exists in the registry" % organization self . error ( msg ) return e . code else : try : api . add_domain ( self . db , organization , domain , is_top_domain = is_top_domain , overwrite = overwrite ) except InvalidValueError as e : # Same as above, domains cannot be None or empty raise RuntimeError ( str ( e ) ) except AlreadyExistsError as e : msg = "domain '%s' already exists in the registry" % domain self . error ( msg ) return e . code except NotFoundError as e : self . error ( str ( e ) ) return e . code return CMD_SUCCESS
Add organizations and domains to the registry .
257
8
25,459
def delete ( self , organization , domain = None ) : if not organization : return CMD_SUCCESS if not domain : try : api . delete_organization ( self . db , organization ) except NotFoundError as e : self . error ( str ( e ) ) return e . code else : try : api . delete_domain ( self . db , organization , domain ) except NotFoundError as e : self . error ( str ( e ) ) return e . code return CMD_SUCCESS
Remove organizations and domains from the registry .
107
8
25,460
def registry ( self , term = None ) : try : orgs = api . registry ( self . db , term ) self . display ( 'organizations.tmpl' , organizations = orgs ) except NotFoundError as e : self . error ( str ( e ) ) return e . code return CMD_SUCCESS
List organizations and domains .
69
5
25,461
def create_organizations_parser ( stream ) : import sortinghat . parsing as parsing # First, try with default parser for p in parsing . SORTINGHAT_ORGS_PARSERS : klass = parsing . SORTINGHAT_ORGS_PARSERS [ p ] parser = klass ( ) if parser . check ( stream ) : return parser raise InvalidFormatError ( cause = INVALID_FORMAT_MSG )
Create an organizations parser for the given stream .
96
9
25,462
def enroll ( self , uuid , organization , from_date = MIN_PERIOD_DATE , to_date = MAX_PERIOD_DATE , merge = False ) : # Empty or None values for uuid and organizations are not allowed if not uuid or not organization : return CMD_SUCCESS try : api . add_enrollment ( self . db , uuid , organization , from_date , to_date ) code = CMD_SUCCESS except ( NotFoundError , InvalidValueError ) as e : self . error ( str ( e ) ) code = e . code except AlreadyExistsError as e : if not merge : msg_data = { 'uuid' : uuid , 'org' : organization , 'from_dt' : str ( from_date ) , 'to_dt' : str ( to_date ) } msg = "enrollment for '%(uuid)s' at '%(org)s' (from: %(from_dt)s, to: %(to_dt)s) already exists in the registry" msg = msg % msg_data self . error ( msg ) code = e . code if not merge : return code try : api . merge_enrollments ( self . db , uuid , organization ) except ( NotFoundError , InvalidValueError ) as e : # These exceptions were checked above. If any of these raises # is due to something really wrong has happened raise RuntimeError ( str ( e ) ) return CMD_SUCCESS
Enroll a unique identity in an organization .
329
9
25,463
def __parse_identities ( self , json ) : try : for committer in json [ 'committers' ] . values ( ) : name = self . __encode ( committer [ 'first' ] + ' ' + committer [ 'last' ] ) email = self . __encode ( committer [ 'primary' ] ) username = self . __encode ( committer [ 'id' ] ) uuid = username uid = UniqueIdentity ( uuid = uuid ) identity = Identity ( name = name , email = email , username = username , source = self . source , uuid = uuid ) uid . identities . append ( identity ) if 'email' in committer : for alt_email in committer [ 'email' ] : alt_email = self . __encode ( alt_email ) if alt_email == email : continue identity = Identity ( name = name , email = alt_email , username = username , source = self . source , uuid = uuid ) uid . identities . append ( identity ) if 'affiliations' in committer : enrollments = self . __parse_affiliations_json ( committer [ 'affiliations' ] , uuid ) for rol in enrollments : uid . enrollments . append ( rol ) self . _identities [ uuid ] = uid except KeyError as e : msg = "invalid json format. Attribute %s not found" % e . args raise InvalidFormatError ( cause = msg )
Parse identities using Eclipse format .
326
7
25,464
def __parse_organizations ( self , json ) : try : for organization in json [ 'organizations' ] . values ( ) : name = self . __encode ( organization [ 'name' ] ) try : active = str_to_datetime ( organization [ 'active' ] ) inactive = str_to_datetime ( organization [ 'inactive' ] ) # Ignore organization if not active and not inactive : continue if not active : active = MIN_PERIOD_DATE if not inactive : inactive = MAX_PERIOD_DATE except InvalidDateError as e : raise InvalidFormatError ( cause = str ( e ) ) org = self . _organizations . get ( name , None ) if not org : org = Organization ( name = name ) # Store metadata valid for identities parsing org . active = active org . inactive = inactive self . _organizations [ name ] = org except KeyError as e : msg = "invalid json format. Attribute %s not found" % e . args raise InvalidFormatError ( cause = msg )
Parse Eclipse organizations .
224
5
25,465
def __parse_affiliations_json ( self , affiliations , uuid ) : enrollments = [ ] for affiliation in affiliations . values ( ) : name = self . __encode ( affiliation [ 'name' ] ) try : start_date = str_to_datetime ( affiliation [ 'active' ] ) end_date = str_to_datetime ( affiliation [ 'inactive' ] ) except InvalidDateError as e : raise InvalidFormatError ( cause = str ( e ) ) # Ignore affiliation if not start_date and not end_date : continue if not start_date : start_date = MIN_PERIOD_DATE if not end_date : end_date = MAX_PERIOD_DATE org = self . _organizations . get ( name , None ) # Set enrolllment period according to organization data if org : start_date = org . active if start_date < org . active else start_date end_date = org . inactive if end_date > org . inactive else end_date if not org : org = Organization ( name = name ) org . active = MIN_PERIOD_DATE org . inactive = MAX_PERIOD_DATE enrollment = Enrollment ( start = start_date , end = end_date , organization = org ) enrollments . append ( enrollment ) return enrollments
Parse identity s affiliations from a json dict
290
10
25,466
def add_unique_identity ( db , uuid ) : with db . connect ( ) as session : try : add_unique_identity_db ( session , uuid ) except ValueError as e : raise InvalidValueError ( e )
Add a unique identity to the registry .
52
8
25,467
def add_organization ( db , organization ) : with db . connect ( ) as session : try : add_organization_db ( session , organization ) except ValueError as e : raise InvalidValueError ( e )
Add an organization to the registry .
46
7
25,468
def add_domain ( db , organization , domain , is_top_domain = False , overwrite = False ) : with db . connect ( ) as session : org = find_organization ( session , organization ) if not org : raise NotFoundError ( entity = organization ) dom = find_domain ( session , domain ) if dom and not overwrite : raise AlreadyExistsError ( entity = 'Domain' , eid = dom . domain ) elif dom : delete_domain_db ( session , dom ) try : add_domain_db ( session , org , domain , is_top_domain = is_top_domain ) except ValueError as e : raise InvalidValueError ( e )
Add a domain to the registry .
145
7
25,469
def add_to_matching_blacklist ( db , entity ) : with db . connect ( ) as session : try : add_to_matching_blacklist_db ( session , entity ) except ValueError as e : raise InvalidValueError ( e )
Add entity to the matching blacklist .
56
7
25,470
def delete_unique_identity ( db , uuid ) : with db . connect ( ) as session : uidentity = find_unique_identity ( session , uuid ) if not uidentity : raise NotFoundError ( entity = uuid ) delete_unique_identity_db ( session , uidentity )
Remove a unique identity from the registry .
70
8
25,471
def delete_from_matching_blacklist ( db , entity ) : with db . connect ( ) as session : mb = session . query ( MatchingBlacklist ) . filter ( MatchingBlacklist . excluded == entity ) . first ( ) if not mb : raise NotFoundError ( entity = entity ) delete_from_matching_blacklist_db ( session , mb )
Remove an blacklisted entity from the registry .
84
9
25,472
def merge_enrollments ( db , uuid , organization ) : # Merge enrollments with db . connect ( ) as session : uidentity = find_unique_identity ( session , uuid ) if not uidentity : raise NotFoundError ( entity = uuid ) org = find_organization ( session , organization ) if not org : raise NotFoundError ( entity = organization ) disjoint = session . query ( Enrollment ) . filter ( Enrollment . uidentity == uidentity , Enrollment . organization == org ) . all ( ) if not disjoint : entity = '-' . join ( ( uuid , organization ) ) raise NotFoundError ( entity = entity ) dates = [ ( enr . start , enr . end ) for enr in disjoint ] for st , en in utils . merge_date_ranges ( dates ) : # We prefer this method to find duplicates # to avoid integrity exceptions when creating # enrollments that are already in the database is_dup = lambda x , st , en : x . start == st and x . end == en filtered = [ x for x in disjoint if not is_dup ( x , st , en ) ] if len ( filtered ) != len ( disjoint ) : disjoint = filtered continue # This means no dups where found so we need to add a # new enrollment try : enroll_db ( session , uidentity , org , from_date = st , to_date = en ) except ValueError as e : raise InvalidValueError ( e ) # Remove disjoint enrollments from the registry for enr in disjoint : delete_enrollment_db ( session , enr )
Merge overlapping enrollments .
366
6
25,473
def match_identities ( db , uuid , matcher ) : uidentities = [ ] with db . connect ( ) as session : uidentity = find_unique_identity ( session , uuid ) if not uidentity : raise NotFoundError ( entity = uuid ) # Get all identities expect of the one requested one query above (uid) candidates = session . query ( UniqueIdentity ) . filter ( UniqueIdentity . uuid != uuid ) . order_by ( UniqueIdentity . uuid ) for candidate in candidates : if not matcher . match ( uidentity , candidate ) : continue uidentities . append ( candidate ) # Detach objects from the session session . expunge_all ( ) return uidentities
Search for similar unique identities .
160
6
25,474
def unique_identities ( db , uuid = None , source = None ) : uidentities = [ ] with db . connect ( ) as session : query = session . query ( UniqueIdentity ) if source : query = query . join ( Identity ) . filter ( UniqueIdentity . uuid == Identity . uuid , Identity . source == source ) if uuid : uidentity = query . filter ( UniqueIdentity . uuid == uuid ) . first ( ) if not uidentity : raise NotFoundError ( entity = uuid ) uidentities = [ uidentity ] else : uidentities = query . order_by ( UniqueIdentity . uuid ) . all ( ) # Detach objects from the session session . expunge_all ( ) return uidentities
List the unique identities available in the registry .
169
9
25,475
def search_unique_identities ( db , term , source = None ) : uidentities = [ ] pattern = '%' + term + '%' if term else None with db . connect ( ) as session : query = session . query ( UniqueIdentity ) . join ( Identity ) . filter ( UniqueIdentity . uuid == Identity . uuid ) if source : query = query . filter ( Identity . source == source ) if pattern : query = query . filter ( Identity . name . like ( pattern ) | Identity . email . like ( pattern ) | Identity . username . like ( pattern ) | Identity . source . like ( pattern ) ) else : query = query . filter ( ( Identity . name == None ) | ( Identity . email == None ) | ( Identity . username == None ) | ( Identity . source == None ) ) uidentities = query . order_by ( UniqueIdentity . uuid ) . all ( ) if not uidentities : raise NotFoundError ( entity = term ) # Detach objects from the session session . expunge_all ( ) return uidentities
Look for unique identities .
233
5
25,476
def search_unique_identities_slice ( db , term , offset , limit ) : uidentities = [ ] pattern = '%' + term + '%' if term else None if offset < 0 : raise InvalidValueError ( 'offset must be greater than 0 - %s given' % str ( offset ) ) if limit < 0 : raise InvalidValueError ( 'limit must be greater than 0 - %s given' % str ( limit ) ) with db . connect ( ) as session : query = session . query ( UniqueIdentity ) . join ( Identity ) . filter ( UniqueIdentity . uuid == Identity . uuid ) if pattern : query = query . filter ( Identity . name . like ( pattern ) | Identity . email . like ( pattern ) | Identity . username . like ( pattern ) | Identity . source . like ( pattern ) ) query = query . group_by ( UniqueIdentity ) . order_by ( UniqueIdentity . uuid ) # Get the total number of unique identities for that search nuids = query . count ( ) start = offset end = offset + limit uidentities = query . slice ( start , end ) . all ( ) # Detach objects from the session session . expunge_all ( ) return uidentities , nuids
Look for unique identities using slicing .
270
7
25,477
def search_last_modified_identities ( db , after ) : with db . connect ( ) as session : query = session . query ( Identity . id ) . filter ( Identity . last_modified >= after ) ids = [ id_ . id for id_ in query . order_by ( Identity . id ) . all ( ) ] return ids
Look for the uuids of identities modified on or after a given date .
75
16
25,478
def search_last_modified_unique_identities ( db , after ) : with db . connect ( ) as session : query = session . query ( UniqueIdentity . uuid ) . filter ( UniqueIdentity . last_modified >= after ) uids = [ uid . uuid for uid in query . order_by ( UniqueIdentity . uuid ) . all ( ) ] return uids
Look for the uuids of unique identities modified on or after a given date .
86
17
25,479
def search_profiles ( db , no_gender = False ) : profiles = [ ] with db . connect ( ) as session : query = session . query ( Profile ) if no_gender : query = query . filter ( Profile . gender == None ) profiles = query . order_by ( Profile . uuid ) . all ( ) # Detach objects from the session session . expunge_all ( ) return profiles
List unique identities profiles .
88
5
25,480
def registry ( db , term = None ) : orgs = [ ] with db . connect ( ) as session : if term : orgs = session . query ( Organization ) . filter ( Organization . name . like ( '%' + term + '%' ) ) . order_by ( Organization . name ) . all ( ) if not orgs : raise NotFoundError ( entity = term ) else : orgs = session . query ( Organization ) . order_by ( Organization . name ) . all ( ) # Detach objects from the session session . expunge_all ( ) return orgs
List the organizations available in the registry .
126
8
25,481
def domains ( db , domain = None , top = False ) : doms = [ ] with db . connect ( ) as session : if domain : dom = find_domain ( session , domain ) if not dom : if not top : raise NotFoundError ( entity = domain ) else : # Adds a dot to the beggining of the domain. # Useful to compare domains like example.com and # myexample.com add_dot = lambda d : '.' + d if not d . startswith ( '.' ) else d d = add_dot ( domain ) tops = session . query ( Domain ) . filter ( Domain . is_top_domain ) . order_by ( Domain . domain ) . all ( ) doms = [ t for t in tops if d . endswith ( add_dot ( t . domain ) ) ] if not doms : raise NotFoundError ( entity = domain ) else : doms = [ dom ] else : query = session . query ( Domain ) if top : query = query . filter ( Domain . is_top_domain ) doms = query . order_by ( Domain . domain ) . all ( ) # Detach objects from the session session . expunge_all ( ) return doms
List the domains available in the registry .
262
8
25,482
def countries ( db , code = None , term = None ) : def _is_code_valid ( code ) : return type ( code ) == str and len ( code ) == 2 and code . isalpha ( ) if code is not None and not _is_code_valid ( code ) : raise InvalidValueError ( 'country code must be a 2 length alpha string - %s given' % str ( code ) ) cs = [ ] with db . connect ( ) as session : query = session . query ( Country ) if code or term : if code : query = query . filter ( Country . code == code . upper ( ) ) elif term : query = query . filter ( Country . name . like ( '%' + term + '%' ) ) cs = query . order_by ( Country . code ) . all ( ) if not cs : e = code if code else term raise NotFoundError ( entity = e ) else : cs = session . query ( Country ) . order_by ( Country . code ) . all ( ) # Detach objects from the session session . expunge_all ( ) return cs
List the countries available in the registry .
238
8
25,483
def enrollments ( db , uuid = None , organization = None , from_date = None , to_date = None ) : if not from_date : from_date = MIN_PERIOD_DATE if not to_date : to_date = MAX_PERIOD_DATE if from_date < MIN_PERIOD_DATE or from_date > MAX_PERIOD_DATE : raise InvalidValueError ( "'from_date' %s is out of bounds" % str ( from_date ) ) if to_date < MIN_PERIOD_DATE or to_date > MAX_PERIOD_DATE : raise InvalidValueError ( "'to_date' %s is out of bounds" % str ( to_date ) ) if from_date and to_date and from_date > to_date : raise InvalidValueError ( "'from_date' %s cannot be greater than %s" % ( from_date , to_date ) ) enrollments = [ ] with db . connect ( ) as session : query = session . query ( Enrollment ) . join ( UniqueIdentity , Organization ) . filter ( Enrollment . start >= from_date , Enrollment . end <= to_date ) # Filter by uuid if uuid : uidentity = find_unique_identity ( session , uuid ) if not uidentity : raise NotFoundError ( entity = uuid ) query = query . filter ( Enrollment . uidentity == uidentity ) # Filter by organization if organization : org = find_organization ( session , organization ) if not org : raise NotFoundError ( entity = organization ) query = query . filter ( Enrollment . organization == org ) # Get the results enrollments = query . order_by ( UniqueIdentity . uuid , Organization . name , Enrollment . start , Enrollment . end ) . all ( ) # Detach objects from the session session . expunge_all ( ) return enrollments
List the enrollment information available in the registry .
427
9
25,484
def blacklist ( db , term = None ) : mbs = [ ] with db . connect ( ) as session : if term : mbs = session . query ( MatchingBlacklist ) . filter ( MatchingBlacklist . excluded . like ( '%' + term + '%' ) ) . order_by ( MatchingBlacklist . excluded ) . all ( ) if not mbs : raise NotFoundError ( entity = term ) else : mbs = session . query ( MatchingBlacklist ) . order_by ( MatchingBlacklist . excluded ) . all ( ) # Detach objects from the session session . expunge_all ( ) return mbs
List the blacklisted entities available in the registry .
141
10
25,485
def run ( self , * args ) : uuid , kwargs = self . __parse_arguments ( * args ) code = self . edit_profile ( uuid , * * kwargs ) return code
Endit profile information .
46
5
25,486
def __unify_unique_identities ( self , uidentities , matcher , fast_matching , interactive ) : self . total = len ( uidentities ) self . matched = 0 if self . recovery and self . recovery_file . exists ( ) : print ( "Loading matches from recovery file: %s" % self . recovery_file . location ( ) ) matched = self . recovery_file . load_matches ( ) else : matched = match ( uidentities , matcher , fastmode = fast_matching ) # convert the matched identities to a common JSON format to ease resuming operations matched = self . __marshal_matches ( matched ) self . __merge ( matched , interactive ) if self . recovery : self . recovery_file . delete ( )
Unify unique identities looking for similar identities .
168
9
25,487
def __merge ( self , matched , interactive ) : for m in matched : identities = m [ 'identities' ] uuid = identities [ 0 ] try : for c in identities [ 1 : ] : if self . __merge_unique_identities ( c , uuid , interactive ) : self . matched += 1 # Retrieve unique identity to show updated info if interactive : uuid = api . unique_identities ( self . db , uuid = uuid ) [ 0 ] except Exception as e : if self . recovery : self . recovery_file . save_matches ( matched ) raise e m [ 'processed' ] = True
Merge a lists of matched unique identities
138
8
25,488
def __display_stats ( self ) : self . display ( 'unify.tmpl' , processed = self . total , matched = self . matched , unified = self . total - self . matched )
Display some stats regarding unify process
43
7
25,489
def __marshal_matches ( matched ) : json_matches = [ ] for m in matched : identities = [ i . uuid for i in m ] if len ( identities ) == 1 : continue json_match = { 'identities' : identities , 'processed' : False } json_matches . append ( json_match ) return json_matches
Convert matches to JSON format .
80
7
25,490
def load_matches ( self ) : if not self . exists ( ) : return [ ] matches = [ ] with open ( self . location ( ) , 'r' ) as f : for line in f . readlines ( ) : match_obj = json . loads ( line . strip ( "\n" ) ) if match_obj [ 'processed' ] : continue matches . append ( match_obj ) return matches
Load matches of the previous failed execution from the recovery file .
89
12
25,491
def save_matches ( self , matches ) : if not os . path . exists ( os . path . dirname ( self . location ( ) ) ) : os . makedirs ( os . path . dirname ( self . location ( ) ) ) with open ( self . location ( ) , "w+" ) as f : matches = [ m for m in matches if not m [ 'processed' ] ] for m in matches : match_obj = json . dumps ( m ) f . write ( match_obj + "\n" )
Save matches of a failed execution to the log .
116
10
25,492
def __uuid ( * args ) : s = '-' . join ( args ) sha1 = hashlib . sha1 ( s . encode ( 'utf-8' , errors = 'surrogateescape' ) ) uuid_sha1 = sha1 . hexdigest ( ) return uuid_sha1
Generate a UUID based on the given parameters .
70
11
25,493
def __parse ( self , identities_stream , organizations_stream ) : if organizations_stream : self . __parse_organizations ( organizations_stream ) if identities_stream : self . __parse_identities ( identities_stream )
Parse GrimoireLab stream
49
5
25,494
def __parse_identities ( self , stream ) : def __create_sh_identities ( name , emails , yaml_entry ) : """Create SH identities based on name, emails and backens data in yaml_entry""" ids = [ ] ids . append ( Identity ( name = name , source = self . source ) ) # FIXME we should encourage our users to add email or usernames # and if not returning at least a WARNING if emails : for m in emails : ids . append ( Identity ( email = m , source = self . source ) ) for pb in PERCEVAL_BACKENDS : if pb not in yaml_entry : continue for username in yaml_entry [ pb ] : identity = Identity ( username = username , source = pb ) ids . append ( identity ) return ids yaml_file = self . __load_yml ( stream ) yid_counter = 0 try : for yid in yaml_file : profile = yid [ 'profile' ] if profile is None : raise AttributeError ( 'profile' ) # we want the KeyError if name is missing name = yid [ 'profile' ] [ 'name' ] is_bot = profile . get ( 'is_bot' , False ) emails = yid . get ( 'email' , None ) if emails and self . email_validation : self . __validate_email ( emails [ 0 ] ) enrollments = yid . get ( 'enrollments' , None ) uuid = str ( yid_counter ) yid_counter += 1 uid = UniqueIdentity ( uuid = uuid ) prf = Profile ( name = name , is_bot = is_bot ) uid . profile = prf # now it is time to add the identities for name, emails and backends sh_identities = __create_sh_identities ( name , emails , yid ) uid . identities += sh_identities if enrollments : affiliations = self . __parse_affiliations_yml ( enrollments ) uid . enrollments += affiliations self . _identities [ uuid ] = uid except KeyError as e : error = "Attribute %s not found" % e . args msg = self . GRIMOIRELAB_INVALID_FORMAT % { 'error' : error } raise InvalidFormatError ( cause = msg )
Parse identities using GrimoireLab format .
521
8
25,495
def __parse_organizations ( self , stream ) : if not stream : return yaml_file = self . __load_yml ( stream ) try : for element in yaml_file : name = self . __encode ( element [ 'organization' ] ) if not name : error = "Empty organization name" msg = self . GRIMOIRELAB_INVALID_FORMAT % { 'error' : error } raise InvalidFormatError ( cause = msg ) o = Organization ( name = name ) if 'domains' in element : if not isinstance ( element [ 'domains' ] , list ) : error = "List of elements expected for organization %s" % name msg = self . GRIMOIRELAB_INVALID_FORMAT % { 'error' : error } raise InvalidFormatError ( cause = msg ) for dom in element [ 'domains' ] : if dom : d = Domain ( domain = dom , is_top_domain = False ) o . domains . append ( d ) else : error = "Empty domain name for organization %s" % name msg = self . GRIMOIRELAB_INVALID_FORMAT % { 'error' : error } raise InvalidFormatError ( cause = msg ) self . _organizations [ name ] = o except KeyError as e : error = "Attribute %s not found" % e . args msg = self . GRIMOIRELAB_INVALID_FORMAT % { 'error' : error } raise InvalidFormatError ( cause = msg ) except TypeError as e : error = "%s" % e . args msg = self . GRIMOIRELAB_INVALID_FORMAT % { 'error' : error } raise InvalidFormatError ( cause = msg )
Parse GrimoireLab organizations .
382
6
25,496
def __parse_affiliations_yml ( self , affiliations ) : enrollments = [ ] for aff in affiliations : name = self . __encode ( aff [ 'organization' ] ) if not name : error = "Empty organization name" msg = self . GRIMOIRELAB_INVALID_FORMAT % { 'error' : error } raise InvalidFormatError ( cause = msg ) elif name . lower ( ) == 'unknown' : continue # we trust the Organization name included in the identities file org = Organization ( name = name ) if org is None : continue if 'start' in aff : start_date = self . __force_datetime ( aff [ 'start' ] ) else : start_date = MIN_PERIOD_DATE if 'end' in aff : end_date = self . __force_datetime ( aff [ 'end' ] ) else : end_date = MAX_PERIOD_DATE enrollment = Enrollment ( start = start_date , end = end_date , organization = org ) enrollments . append ( enrollment ) self . __validate_enrollment_periods ( enrollments ) return enrollments
Parse identity s affiliations from a yaml dict .
253
12
25,497
def __force_datetime ( self , obj ) : if isinstance ( obj , datetime . datetime ) : return obj t = datetime . time ( 0 , 0 ) return datetime . datetime . combine ( obj , t )
Converts ojb to time . datetime . datetime
51
13
25,498
def __load_yml ( self , stream ) : try : return yaml . load ( stream , Loader = yaml . SafeLoader ) except ValueError as e : cause = "invalid yml format. %s" % str ( e ) raise InvalidFormatError ( cause = cause )
Load yml stream into a dict object
63
8
25,499
def __validate_email ( self , email ) : e = re . match ( self . EMAIL_ADDRESS_REGEX , email , re . UNICODE ) if e : return email else : error = "Invalid email address: " + str ( email ) msg = self . GRIMOIRELAB_INVALID_FORMAT % { 'error' : error } raise InvalidFormatError ( cause = msg )
Checks if a string looks like an email address
93
10