id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 51 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
27,000 | chaoss/grimoirelab-sortinghat | sortinghat/parsing/mailmap.py | MailmapParser.__parse_stream | def __parse_stream(self, stream):
"""Generic method to parse mailmap streams"""
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 | python | 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 | [
"def",
"__parse_stream",
"(",
"self",
",",
"stream",
")",
":",
"nline",
"=",
"0",
"lines",
"=",
"stream",
".",
"split",
"(",
"'\\n'",
")",
"for",
"line",
"in",
"lines",
":",
"nline",
"+=",
"1",
"# Ignore blank lines and comments",
"m",
"=",
"re",
".",
... | Generic method to parse mailmap streams | [
"Generic",
"method",
"to",
"parse",
"mailmap",
"streams"
] | 391cd37a75fea26311dc6908bc1c953c540a8e04 | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/parsing/mailmap.py#L170-L207 |
27,001 | chaoss/grimoirelab-sortinghat | sortinghat/cmd/merge.py | Merge.run | def run(self, *args):
"""Merge two identities.
When <from_uuid> or <to_uuid> are empty the command does not have
any effect. The same happens when both <from_uuid> and <to_uuid>
are the same unique identity.
"""
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 | python | 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 | [
"def",
"run",
"(",
"self",
",",
"*",
"args",
")",
":",
"params",
"=",
"self",
".",
"parser",
".",
"parse_args",
"(",
"args",
")",
"from_uuid",
"=",
"params",
".",
"from_uuid",
"to_uuid",
"=",
"params",
".",
"to_uuid",
"code",
"=",
"self",
".",
"merge... | Merge two identities.
When <from_uuid> or <to_uuid> are empty the command does not have
any effect. The same happens when both <from_uuid> and <to_uuid>
are the same unique identity. | [
"Merge",
"two",
"identities",
"."
] | 391cd37a75fea26311dc6908bc1c953c540a8e04 | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/cmd/merge.py#L67-L81 |
27,002 | chaoss/grimoirelab-sortinghat | sortinghat/matcher.py | create_identity_matcher | def create_identity_matcher(matcher='default', blacklist=None, sources=None,
strict=True):
"""Create an identity matcher of the given type.
Factory function that creates an identity matcher object of the type
defined on 'matcher' parameter. A blacklist can also be added to
ignore those values while matching.
:param matcher: type of the matcher
:param blacklist: list of entries to ignore while matching
:param sources: only match the identities from these sources
:param strict: strict matching (i.e, well-formed email addresses)
:returns: a identity matcher object of the given type
:raises MatcherNotSupportedError: when the given matcher type is not
supported or available
"""
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) | python | 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) | [
"def",
"create_identity_matcher",
"(",
"matcher",
"=",
"'default'",
",",
"blacklist",
"=",
"None",
",",
"sources",
"=",
"None",
",",
"strict",
"=",
"True",
")",
":",
"import",
"sortinghat",
".",
"matching",
"as",
"matching",
"if",
"matcher",
"not",
"in",
"... | Create an identity matcher of the given type.
Factory function that creates an identity matcher object of the type
defined on 'matcher' parameter. A blacklist can also be added to
ignore those values while matching.
:param matcher: type of the matcher
:param blacklist: list of entries to ignore while matching
:param sources: only match the identities from these sources
:param strict: strict matching (i.e, well-formed email addresses)
:returns: a identity matcher object of the given type
:raises MatcherNotSupportedError: when the given matcher type is not
supported or available | [
"Create",
"an",
"identity",
"matcher",
"of",
"the",
"given",
"type",
"."
] | 391cd37a75fea26311dc6908bc1c953c540a8e04 | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/matcher.py#L125-L150 |
27,003 | chaoss/grimoirelab-sortinghat | sortinghat/matcher.py | match | def match(uidentities, matcher, fastmode=False):
"""Find matches in a set of unique identities.
This function looks for possible similar or equal identities from a set
of unique identities. The result will be a list of subsets where each
subset is a list of matching identities.
When `fastmode` is set a new and experimental matching algorithm
will be used. It consumes more resources (a big amount of memory)
but it is, at least, two orders of maginute faster than the
classic algorithm.
:param uidentities: list of unique identities to match
:param matcher: instance of the matcher
:param fastmode: use a faster algorithm
:returns: a list of subsets with the matched unique identities
:raises MatcherNotSupportedError: when matcher does not support fast
mode matching
:raises TypeError: when matcher is not an instance of
IdentityMatcher class
"""
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 | python | 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 | [
"def",
"match",
"(",
"uidentities",
",",
"matcher",
",",
"fastmode",
"=",
"False",
")",
":",
"if",
"not",
"isinstance",
"(",
"matcher",
",",
"IdentityMatcher",
")",
":",
"raise",
"TypeError",
"(",
"\"matcher is not an instance of IdentityMatcher\"",
")",
"if",
"... | Find matches in a set of unique identities.
This function looks for possible similar or equal identities from a set
of unique identities. The result will be a list of subsets where each
subset is a list of matching identities.
When `fastmode` is set a new and experimental matching algorithm
will be used. It consumes more resources (a big amount of memory)
but it is, at least, two orders of maginute faster than the
classic algorithm.
:param uidentities: list of unique identities to match
:param matcher: instance of the matcher
:param fastmode: use a faster algorithm
:returns: a list of subsets with the matched unique identities
:raises MatcherNotSupportedError: when matcher does not support fast
mode matching
:raises TypeError: when matcher is not an instance of
IdentityMatcher class | [
"Find",
"matches",
"in",
"a",
"set",
"of",
"unique",
"identities",
"."
] | 391cd37a75fea26311dc6908bc1c953c540a8e04 | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/matcher.py#L153-L196 |
27,004 | chaoss/grimoirelab-sortinghat | sortinghat/matcher.py | _match | def _match(filtered, matcher):
"""Old method to find matches in a set of filtered identities."""
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 | python | 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 | [
"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",
... | Old method to find matches in a set of filtered identities. | [
"Old",
"method",
"to",
"find",
"matches",
"in",
"a",
"set",
"of",
"filtered",
"identities",
"."
] | 391cd37a75fea26311dc6908bc1c953c540a8e04 | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/matcher.py#L199-L234 |
27,005 | chaoss/grimoirelab-sortinghat | sortinghat/matcher.py | _match_with_pandas | def _match_with_pandas(filtered, matcher):
"""Find matches in a set using Pandas' library."""
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 | python | 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 | [
"def",
"_match_with_pandas",
"(",
"filtered",
",",
"matcher",
")",
":",
"import",
"pandas",
"data",
"=",
"[",
"fl",
".",
"to_dict",
"(",
")",
"for",
"fl",
"in",
"filtered",
"]",
"if",
"not",
"data",
":",
"return",
"[",
"]",
"df",
"=",
"pandas",
".",
... | Find matches in a set using Pandas' library. | [
"Find",
"matches",
"in",
"a",
"set",
"using",
"Pandas",
"library",
"."
] | 391cd37a75fea26311dc6908bc1c953c540a8e04 | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/matcher.py#L237-L267 |
27,006 | chaoss/grimoirelab-sortinghat | sortinghat/matcher.py | _filter_unique_identities | def _filter_unique_identities(uidentities, matcher):
"""Filter a set of unique identities.
This function will use the `matcher` to generate a list
of `FilteredIdentity` objects. It will return a tuple
with the list of filtered objects, the unique identities
not filtered and a table mapping uuids with unique
identities.
"""
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 | python | 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 | [
"def",
"_filter_unique_identities",
"(",
"uidentities",
",",
"matcher",
")",
":",
"filtered",
"=",
"[",
"]",
"no_filtered",
"=",
"[",
"]",
"uuids",
"=",
"{",
"}",
"for",
"uidentity",
"in",
"uidentities",
":",
"n",
"=",
"len",
"(",
"filtered",
")",
"filte... | Filter a set of unique identities.
This function will use the `matcher` to generate a list
of `FilteredIdentity` objects. It will return a tuple
with the list of filtered objects, the unique identities
not filtered and a table mapping uuids with unique
identities. | [
"Filter",
"a",
"set",
"of",
"unique",
"identities",
"."
] | 391cd37a75fea26311dc6908bc1c953c540a8e04 | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/matcher.py#L270-L292 |
27,007 | chaoss/grimoirelab-sortinghat | sortinghat/matcher.py | _build_matches | def _build_matches(matches, uuids, no_filtered, fastmode=False):
"""Build a list with matching subsets"""
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 | python | 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 | [
"def",
"_build_matches",
"(",
"matches",
",",
"uuids",
",",
"no_filtered",
",",
"fastmode",
"=",
"False",
")",
":",
"result",
"=",
"[",
"]",
"for",
"m",
"in",
"matches",
":",
"mk",
"=",
"m",
"[",
"0",
"]",
".",
"uuid",
"if",
"not",
"fastmode",
"els... | Build a list with matching subsets | [
"Build",
"a",
"list",
"with",
"matching",
"subsets"
] | 391cd37a75fea26311dc6908bc1c953c540a8e04 | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/matcher.py#L295-L321 |
27,008 | chaoss/grimoirelab-sortinghat | sortinghat/matcher.py | _calculate_matches_closures | def _calculate_matches_closures(groups):
"""Find the transitive closure of each unique identity.
This function uses a BFS algorithm to build set of matches.
For instance, given a list of matched unique identities like
A = {A, B}; B = {B,A,C}, C = {C,} and D = {D,} the output
will be A = {A, B, C} and D = {D,}.
:param groups: groups of unique identities
"""
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 | python | 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 | [
"def",
"_calculate_matches_closures",
"(",
"groups",
")",
":",
"matches",
"=",
"[",
"]",
"ns",
"=",
"sorted",
"(",
"groups",
".",
"groups",
".",
"keys",
"(",
")",
")",
"while",
"ns",
":",
"n",
"=",
"ns",
".",
"pop",
"(",
"0",
")",
"visited",
"=",
... | Find the transitive closure of each unique identity.
This function uses a BFS algorithm to build set of matches.
For instance, given a list of matched unique identities like
A = {A, B}; B = {B,A,C}, C = {C,} and D = {D,} the output
will be A = {A, B, C} and D = {D,}.
:param groups: groups of unique identities | [
"Find",
"the",
"transitive",
"closure",
"of",
"each",
"unique",
"identity",
"."
] | 391cd37a75fea26311dc6908bc1c953c540a8e04 | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/matcher.py#L324-L360 |
27,009 | chaoss/grimoirelab-sortinghat | sortinghat/matching/email_name.py | EmailNameMatcher.match | def match(self, a, b):
"""Determine if two unique identities are the same.
This method compares the email addresses or the names of each
identity to check if the given unique identities are the same.
When the given unique identities are the same object or share
the same UUID, this will also produce a positive match.
Identities which their email addresses or names are in the blacklist
will be ignored during the matching.
:param a: unique identity to match
:param b: unique identity to match
:returns: True when both unique identities are likely to be the same.
Otherwise, returns False.
:raises ValueError: when any of the given unique identities is not
an instance of UniqueIdentity class
"""
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 | python | 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 | [
"def",
"match",
"(",
"self",
",",
"a",
",",
"b",
")",
":",
"if",
"not",
"isinstance",
"(",
"a",
",",
"UniqueIdentity",
")",
":",
"raise",
"ValueError",
"(",
"\"<a> is not an instance of UniqueIdentity\"",
")",
"if",
"not",
"isinstance",
"(",
"b",
",",
"Uni... | Determine if two unique identities are the same.
This method compares the email addresses or the names of each
identity to check if the given unique identities are the same.
When the given unique identities are the same object or share
the same UUID, this will also produce a positive match.
Identities which their email addresses or names are in the blacklist
will be ignored during the matching.
:param a: unique identity to match
:param b: unique identity to match
:returns: True when both unique identities are likely to be the same.
Otherwise, returns False.
:raises ValueError: when any of the given unique identities is not
an instance of UniqueIdentity class | [
"Determine",
"if",
"two",
"unique",
"identities",
"are",
"the",
"same",
"."
] | 391cd37a75fea26311dc6908bc1c953c540a8e04 | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/matching/email_name.py#L77-L112 |
27,010 | chaoss/grimoirelab-sortinghat | sortinghat/db/api.py | find_unique_identity | def find_unique_identity(session, uuid):
"""Find a unique identity.
Find a unique identity by its UUID using the given `session`.
When the unique identity does not exist the function will
return `None`.
:param session: database session
:param uuid: id of the unique identity to find
:returns: a unique identity object; `None` when the unique
identity does not exist
"""
uidentity = session.query(UniqueIdentity). \
filter(UniqueIdentity.uuid == uuid).first()
return uidentity | python | def find_unique_identity(session, uuid):
uidentity = session.query(UniqueIdentity). \
filter(UniqueIdentity.uuid == uuid).first()
return uidentity | [
"def",
"find_unique_identity",
"(",
"session",
",",
"uuid",
")",
":",
"uidentity",
"=",
"session",
".",
"query",
"(",
"UniqueIdentity",
")",
".",
"filter",
"(",
"UniqueIdentity",
".",
"uuid",
"==",
"uuid",
")",
".",
"first",
"(",
")",
"return",
"uidentity"... | Find a unique identity.
Find a unique identity by its UUID using the given `session`.
When the unique identity does not exist the function will
return `None`.
:param session: database session
:param uuid: id of the unique identity to find
:returns: a unique identity object; `None` when the unique
identity does not exist | [
"Find",
"a",
"unique",
"identity",
"."
] | 391cd37a75fea26311dc6908bc1c953c540a8e04 | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/db/api.py#L40-L56 |
27,011 | chaoss/grimoirelab-sortinghat | sortinghat/db/api.py | find_identity | def find_identity(session, id_):
"""Find an identity.
Find an identity by its ID using the given `session`.
When the identity does not exist the function will
return `None`.
:param session: database session
:param id_: id of the identity to find
:returns: an identity object; `None` when the identity
does not exist
"""
identity = session.query(Identity). \
filter(Identity.id == id_).first()
return identity | python | def find_identity(session, id_):
identity = session.query(Identity). \
filter(Identity.id == id_).first()
return identity | [
"def",
"find_identity",
"(",
"session",
",",
"id_",
")",
":",
"identity",
"=",
"session",
".",
"query",
"(",
"Identity",
")",
".",
"filter",
"(",
"Identity",
".",
"id",
"==",
"id_",
")",
".",
"first",
"(",
")",
"return",
"identity"
] | Find an identity.
Find an identity by its ID using the given `session`.
When the identity does not exist the function will
return `None`.
:param session: database session
:param id_: id of the identity to find
:returns: an identity object; `None` when the identity
does not exist | [
"Find",
"an",
"identity",
"."
] | 391cd37a75fea26311dc6908bc1c953c540a8e04 | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/db/api.py#L59-L75 |
27,012 | chaoss/grimoirelab-sortinghat | sortinghat/db/api.py | find_organization | def find_organization(session, name):
"""Find an organization.
Find an organization by its `name` using the given `session`.
When the organization does not exist the function will
return `None`.
:param session: database session
:param name: name of the organization to find
:returns: an organization object; `None` when the organization
does not exist
"""
organization = session.query(Organization). \
filter(Organization.name == name).first()
return organization | python | def find_organization(session, name):
organization = session.query(Organization). \
filter(Organization.name == name).first()
return organization | [
"def",
"find_organization",
"(",
"session",
",",
"name",
")",
":",
"organization",
"=",
"session",
".",
"query",
"(",
"Organization",
")",
".",
"filter",
"(",
"Organization",
".",
"name",
"==",
"name",
")",
".",
"first",
"(",
")",
"return",
"organization"
... | Find an organization.
Find an organization by its `name` using the given `session`.
When the organization does not exist the function will
return `None`.
:param session: database session
:param name: name of the organization to find
:returns: an organization object; `None` when the organization
does not exist | [
"Find",
"an",
"organization",
"."
] | 391cd37a75fea26311dc6908bc1c953c540a8e04 | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/db/api.py#L78-L94 |
27,013 | chaoss/grimoirelab-sortinghat | sortinghat/db/api.py | find_domain | def find_domain(session, name):
"""Find a domain.
Find a domain by its domain name using the given `session`.
When the domain does not exist the function will
return `None`.
:param session: database session
:param name: name of the domain to find
:returns: a domain object; `None` when the domain
does not exist
"""
domain = session.query(Domain). \
filter(Domain.domain == name).first()
return domain | python | def find_domain(session, name):
domain = session.query(Domain). \
filter(Domain.domain == name).first()
return domain | [
"def",
"find_domain",
"(",
"session",
",",
"name",
")",
":",
"domain",
"=",
"session",
".",
"query",
"(",
"Domain",
")",
".",
"filter",
"(",
"Domain",
".",
"domain",
"==",
"name",
")",
".",
"first",
"(",
")",
"return",
"domain"
] | Find a domain.
Find a domain by its domain name using the given `session`.
When the domain does not exist the function will
return `None`.
:param session: database session
:param name: name of the domain to find
:returns: a domain object; `None` when the domain
does not exist | [
"Find",
"a",
"domain",
"."
] | 391cd37a75fea26311dc6908bc1c953c540a8e04 | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/db/api.py#L97-L113 |
27,014 | chaoss/grimoirelab-sortinghat | sortinghat/db/api.py | find_country | def find_country(session, code):
"""Find a country.
Find a country by its ISO-3166 `code` (i.e ES for Spain,
US for United States of America) using the given `session.
When the country does not exist the function will return
`None`.
:param session: database session
:param code: ISO-3166 code of the country to find
:return: a country object; `None` when the country
does not exist
"""
country = session.query(Country).\
filter(Country.code == code).first()
return country | python | def find_country(session, code):
country = session.query(Country).\
filter(Country.code == code).first()
return country | [
"def",
"find_country",
"(",
"session",
",",
"code",
")",
":",
"country",
"=",
"session",
".",
"query",
"(",
"Country",
")",
".",
"filter",
"(",
"Country",
".",
"code",
"==",
"code",
")",
".",
"first",
"(",
")",
"return",
"country"
] | Find a country.
Find a country by its ISO-3166 `code` (i.e ES for Spain,
US for United States of America) using the given `session.
When the country does not exist the function will return
`None`.
:param session: database session
:param code: ISO-3166 code of the country to find
:return: a country object; `None` when the country
does not exist | [
"Find",
"a",
"country",
"."
] | 391cd37a75fea26311dc6908bc1c953c540a8e04 | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/db/api.py#L116-L133 |
27,015 | chaoss/grimoirelab-sortinghat | sortinghat/db/api.py | add_unique_identity | def add_unique_identity(session, uuid):
"""Add a unique identity to the session.
This function adds a unique identity to the session with
`uuid` string as unique identifier. This identifier cannot
be empty or `None`.
When the unique identity is added, a new empty profile for
this object is created too.
As a result, the function returns a new `UniqueIdentity`
object.
:param session: database session
:param uuid: unique identifier for the unique identity
:return: a new unique identity
:raises ValueError: when `uuid` is `None` or an empty string
"""
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 | python | 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 | [
"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\"",
... | Add a unique identity to the session.
This function adds a unique identity to the session with
`uuid` string as unique identifier. This identifier cannot
be empty or `None`.
When the unique identity is added, a new empty profile for
this object is created too.
As a result, the function returns a new `UniqueIdentity`
object.
:param session: database session
:param uuid: unique identifier for the unique identity
:return: a new unique identity
:raises ValueError: when `uuid` is `None` or an empty string | [
"Add",
"a",
"unique",
"identity",
"to",
"the",
"session",
"."
] | 391cd37a75fea26311dc6908bc1c953c540a8e04 | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/db/api.py#L136-L167 |
27,016 | chaoss/grimoirelab-sortinghat | sortinghat/db/api.py | add_identity | def add_identity(session, uidentity, identity_id, source,
name=None, email=None, username=None):
"""Add an identity to the session.
This function adds a new identity to the session using
`identity_id` as its identifier. The new identity will
also be linked to the unique identity object of `uidentity`.
Neither the values given to `identity_id` nor to `source` can
be `None` or empty. Moreover, `name`, `email` or `username`
parameters need a non empty value.
As a result, the function returns a new `Identity` object.
:param session: database session
:param uidentity: links the new identity to this unique identity object
:param identity_id: identifier for the new identity
:param source: data source where this identity was found
:param name: full name of the identity
:param email: email of the identity
:param username: user name used by the identity
:return: a new identity
:raises ValueError: when `identity_id` and `source` are `None` or empty;
when all of the data parameters are `None` or empty.
"""
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 | python | 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 | [
"def",
"add_identity",
"(",
"session",
",",
"uidentity",
",",
"identity_id",
",",
"source",
",",
"name",
"=",
"None",
",",
"email",
"=",
"None",
",",
"username",
"=",
"None",
")",
":",
"if",
"identity_id",
"is",
"None",
":",
"raise",
"ValueError",
"(",
... | Add an identity to the session.
This function adds a new identity to the session using
`identity_id` as its identifier. The new identity will
also be linked to the unique identity object of `uidentity`.
Neither the values given to `identity_id` nor to `source` can
be `None` or empty. Moreover, `name`, `email` or `username`
parameters need a non empty value.
As a result, the function returns a new `Identity` object.
:param session: database session
:param uidentity: links the new identity to this unique identity object
:param identity_id: identifier for the new identity
:param source: data source where this identity was found
:param name: full name of the identity
:param email: email of the identity
:param username: user name used by the identity
:return: a new identity
:raises ValueError: when `identity_id` and `source` are `None` or empty;
when all of the data parameters are `None` or empty. | [
"Add",
"an",
"identity",
"to",
"the",
"session",
"."
] | 391cd37a75fea26311dc6908bc1c953c540a8e04 | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/db/api.py#L184-L230 |
27,017 | chaoss/grimoirelab-sortinghat | sortinghat/db/api.py | delete_identity | def delete_identity(session, identity):
"""Remove an identity from the session.
This function removes from the session the identity given
in `identity`. Take into account this function does not
remove unique identities in the case they get empty.
:param session: database session
:param identity: identity to remove
"""
uidentity = identity.uidentity
uidentity.last_modified = datetime.datetime.utcnow()
session.delete(identity)
session.flush() | python | def delete_identity(session, identity):
uidentity = identity.uidentity
uidentity.last_modified = datetime.datetime.utcnow()
session.delete(identity)
session.flush() | [
"def",
"delete_identity",
"(",
"session",
",",
"identity",
")",
":",
"uidentity",
"=",
"identity",
".",
"uidentity",
"uidentity",
".",
"last_modified",
"=",
"datetime",
".",
"datetime",
".",
"utcnow",
"(",
")",
"session",
".",
"delete",
"(",
"identity",
")",... | Remove an identity from the session.
This function removes from the session the identity given
in `identity`. Take into account this function does not
remove unique identities in the case they get empty.
:param session: database session
:param identity: identity to remove | [
"Remove",
"an",
"identity",
"from",
"the",
"session",
"."
] | 391cd37a75fea26311dc6908bc1c953c540a8e04 | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/db/api.py#L233-L247 |
27,018 | chaoss/grimoirelab-sortinghat | sortinghat/db/api.py | add_organization | def add_organization(session, name):
"""Add an organization to the session.
This function adds a new organization to the session,
using the given `name` as an identifier. Name cannot be
empty or `None`.
It returns a new `Organization` object.
:param session: database session
:param name: name of the organization
:return: a new organization
:raises ValueError: when `name` is `None` or empty
"""
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 | python | 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 | [
"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\"",
")... | Add an organization to the session.
This function adds a new organization to the session,
using the given `name` as an identifier. Name cannot be
empty or `None`.
It returns a new `Organization` object.
:param session: database session
:param name: name of the organization
:return: a new organization
:raises ValueError: when `name` is `None` or empty | [
"Add",
"an",
"organization",
"to",
"the",
"session",
"."
] | 391cd37a75fea26311dc6908bc1c953c540a8e04 | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/db/api.py#L250-L275 |
27,019 | chaoss/grimoirelab-sortinghat | sortinghat/db/api.py | delete_organization | def delete_organization(session, organization):
"""Remove an organization from the session.
Function that removes from the session the organization
given in `organization`. Data related such as domains
or enrollments are also removed.
:param session: database session
:param organization: organization to remove
"""
last_modified = datetime.datetime.utcnow()
for enrollment in organization.enrollments:
enrollment.uidentity.last_modified = last_modified
session.delete(organization)
session.flush() | python | 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() | [
"def",
"delete_organization",
"(",
"session",
",",
"organization",
")",
":",
"last_modified",
"=",
"datetime",
".",
"datetime",
".",
"utcnow",
"(",
")",
"for",
"enrollment",
"in",
"organization",
".",
"enrollments",
":",
"enrollment",
".",
"uidentity",
".",
"l... | Remove an organization from the session.
Function that removes from the session the organization
given in `organization`. Data related such as domains
or enrollments are also removed.
:param session: database session
:param organization: organization to remove | [
"Remove",
"an",
"organization",
"from",
"the",
"session",
"."
] | 391cd37a75fea26311dc6908bc1c953c540a8e04 | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/db/api.py#L278-L294 |
27,020 | chaoss/grimoirelab-sortinghat | sortinghat/db/api.py | add_domain | def add_domain(session, organization, domain_name, is_top_domain=False):
"""Add a domain to the session.
This function adds a new domain to the session using
`domain_name` as its identifier. The new domain will
also be linked to the organization object of `organization`.
Values assigned to `domain_name` cannot be `None` or empty.
The parameter `is_top_domain` only accepts `bool` values.
As a result, the function returns a new `Domain` object.
:param session: database session
:param organization: links the new domain to this organization object
:param domain_name: name of the domain
:param is_top_domain: set this domain as a top domain
:return: a new domain
:raises ValueError: raised when `domain_name` is `None` or an empty;
when `is_top_domain` does not have a `bool` value.
"""
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 | python | 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 | [
"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",
"==",
"'... | Add a domain to the session.
This function adds a new domain to the session using
`domain_name` as its identifier. The new domain will
also be linked to the organization object of `organization`.
Values assigned to `domain_name` cannot be `None` or empty.
The parameter `is_top_domain` only accepts `bool` values.
As a result, the function returns a new `Domain` object.
:param session: database session
:param organization: links the new domain to this organization object
:param domain_name: name of the domain
:param is_top_domain: set this domain as a top domain
:return: a new domain
:raises ValueError: raised when `domain_name` is `None` or an empty;
when `is_top_domain` does not have a `bool` value. | [
"Add",
"a",
"domain",
"to",
"the",
"session",
"."
] | 391cd37a75fea26311dc6908bc1c953c540a8e04 | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/db/api.py#L297-L331 |
27,021 | chaoss/grimoirelab-sortinghat | sortinghat/db/api.py | delete_enrollment | def delete_enrollment(session, enrollment):
"""Remove an enrollment from the session.
This function removes from the session the given enrollment.
:param session: database session
:param enrollment: enrollment to remove
"""
uidentity = enrollment.uidentity
uidentity.last_modified = datetime.datetime.utcnow()
session.delete(enrollment)
session.flush() | python | def delete_enrollment(session, enrollment):
uidentity = enrollment.uidentity
uidentity.last_modified = datetime.datetime.utcnow()
session.delete(enrollment)
session.flush() | [
"def",
"delete_enrollment",
"(",
"session",
",",
"enrollment",
")",
":",
"uidentity",
"=",
"enrollment",
".",
"uidentity",
"uidentity",
".",
"last_modified",
"=",
"datetime",
".",
"datetime",
".",
"utcnow",
"(",
")",
"session",
".",
"delete",
"(",
"enrollment"... | Remove an enrollment from the session.
This function removes from the session the given enrollment.
:param session: database session
:param enrollment: enrollment to remove | [
"Remove",
"an",
"enrollment",
"from",
"the",
"session",
"."
] | 391cd37a75fea26311dc6908bc1c953c540a8e04 | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/db/api.py#L453-L465 |
27,022 | chaoss/grimoirelab-sortinghat | sortinghat/db/api.py | move_enrollment | def move_enrollment(session, enrollment, uidentity):
"""Move an enrollment to a unique identity.
Shifts `enrollment` to the unique identity given in
`uidentity`. The function returns whether the operation
was executed successfully.
When `uidentity` is the unique identity currently related
to `enrollment`, this operation does not have any effect and
`False` will be returned as result.
:param session: database session
:param enrollment: enrollment to be moved
:param uidentity: unique identity where `enrollment` will be moved
:return: `True` if the enrollment was moved; `False` in any other
case
"""
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 | python | 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 | [
"def",
"move_enrollment",
"(",
"session",
",",
"enrollment",
",",
"uidentity",
")",
":",
"if",
"enrollment",
".",
"uuid",
"==",
"uidentity",
".",
"uuid",
":",
"return",
"False",
"old_uidentity",
"=",
"enrollment",
".",
"uidentity",
"enrollment",
".",
"uidentit... | Move an enrollment to a unique identity.
Shifts `enrollment` to the unique identity given in
`uidentity`. The function returns whether the operation
was executed successfully.
When `uidentity` is the unique identity currently related
to `enrollment`, this operation does not have any effect and
`False` will be returned as result.
:param session: database session
:param enrollment: enrollment to be moved
:param uidentity: unique identity where `enrollment` will be moved
:return: `True` if the enrollment was moved; `False` in any other
case | [
"Move",
"an",
"enrollment",
"to",
"a",
"unique",
"identity",
"."
] | 391cd37a75fea26311dc6908bc1c953c540a8e04 | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/db/api.py#L590-L622 |
27,023 | chaoss/grimoirelab-sortinghat | sortinghat/db/api.py | add_to_matching_blacklist | def add_to_matching_blacklist(session, term):
"""Add term to the matching blacklist.
This function adds a `term` to the matching blacklist.
The term to add cannot have a `None` or empty value,
on this case an `ValueError` will be raised.
:param session: database session
:param term: term, word or value to blacklist
:return: a new entry in the blacklist
:raises ValueError: raised when `term` is `None` or an empty string
"""
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 | python | 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 | [
"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... | Add term to the matching blacklist.
This function adds a `term` to the matching blacklist.
The term to add cannot have a `None` or empty value,
on this case an `ValueError` will be raised.
:param session: database session
:param term: term, word or value to blacklist
:return: a new entry in the blacklist
:raises ValueError: raised when `term` is `None` or an empty string | [
"Add",
"term",
"to",
"the",
"matching",
"blacklist",
"."
] | 391cd37a75fea26311dc6908bc1c953c540a8e04 | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/db/api.py#L625-L647 |
27,024 | chaoss/grimoirelab-sortinghat | sortinghat/cmd/autogender.py | genderize | def genderize(name, api_token=None):
"""Fetch gender from genderize.io"""
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 | python | 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 | [
"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... | Fetch gender from genderize.io | [
"Fetch",
"gender",
"from",
"genderize",
".",
"io"
] | 391cd37a75fea26311dc6908bc1c953c540a8e04 | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/cmd/autogender.py#L149-L186 |
27,025 | chaoss/grimoirelab-sortinghat | sortinghat/cmd/autogender.py | AutoGender.run | def run(self, *args):
"""Autocomplete gender information."""
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 | python | 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 | [
"def",
"run",
"(",
"self",
",",
"*",
"args",
")",
":",
"params",
"=",
"self",
".",
"parser",
".",
"parse_args",
"(",
"args",
")",
"api_token",
"=",
"params",
".",
"api_token",
"genderize_all",
"=",
"params",
".",
"genderize_all",
"code",
"=",
"self",
"... | Autocomplete gender information. | [
"Autocomplete",
"gender",
"information",
"."
] | 391cd37a75fea26311dc6908bc1c953c540a8e04 | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/cmd/autogender.py#L80-L89 |
27,026 | chaoss/grimoirelab-sortinghat | sortinghat/cmd/autogender.py | AutoGender.autogender | def autogender(self, api_token=None, genderize_all=False):
"""Autocomplete gender information of unique identities.
Autocomplete unique identities gender using genderize.io
API. Only those unique identities without an assigned
gender will be updated unless `genderize_all` option is given.
"""
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 | python | 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 | [
"def",
"autogender",
"(",
"self",
",",
"api_token",
"=",
"None",
",",
"genderize_all",
"=",
"False",
")",
":",
"name_cache",
"=",
"{",
"}",
"no_gender",
"=",
"not",
"genderize_all",
"pattern",
"=",
"re",
".",
"compile",
"(",
"r\"(^\\w+)\\s\\w+\"",
")",
"pr... | Autocomplete gender information of unique identities.
Autocomplete unique identities gender using genderize.io
API. Only those unique identities without an assigned
gender will be updated unless `genderize_all` option is given. | [
"Autocomplete",
"gender",
"information",
"of",
"unique",
"identities",
"."
] | 391cd37a75fea26311dc6908bc1c953c540a8e04 | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/cmd/autogender.py#L91-L146 |
27,027 | chaoss/grimoirelab-sortinghat | sortinghat/parsing/mozilla.py | MozilliansParser.__parse_identities | def __parse_identities(self, json):
"""Parse identities using Mozillians format.
The Mozillians identities format is a JSON document under the
"results" key. The document should follow the next schema:
{
"results" : [
{
"_url": "https://example.com/api/v2/users/1/",
"alternate_emails": [{
"email": "jsmith@example.net",
"privacy": "Public"
}],
"email": {
"privacy": "Public",
"value": "jsmith@example.com"
},
"full_name": {
"privacy": "Public",
"value": "John Smith"
},
"ircname": {
"privacy": "Public",
"value": "jsmith"
},
"url": "https://mozillians.org/en-US/u/2apreety18/",
"username": "2apreety18"
}
]
}
:parse data: JSON object to parse
:raise InvalidFormatError: raised when the format of the JSON is
not valid.
"""
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) | python | 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) | [
"def",
"__parse_identities",
"(",
"self",
",",
"json",
")",
":",
"try",
":",
"for",
"mozillian",
"in",
"json",
"[",
"'results'",
"]",
":",
"name",
"=",
"self",
".",
"__encode",
"(",
"mozillian",
"[",
"'full_name'",
"]",
"[",
"'value'",
"]",
")",
"email... | Parse identities using Mozillians format.
The Mozillians identities format is a JSON document under the
"results" key. The document should follow the next schema:
{
"results" : [
{
"_url": "https://example.com/api/v2/users/1/",
"alternate_emails": [{
"email": "jsmith@example.net",
"privacy": "Public"
}],
"email": {
"privacy": "Public",
"value": "jsmith@example.com"
},
"full_name": {
"privacy": "Public",
"value": "John Smith"
},
"ircname": {
"privacy": "Public",
"value": "jsmith"
},
"url": "https://mozillians.org/en-US/u/2apreety18/",
"username": "2apreety18"
}
]
}
:parse data: JSON object to parse
:raise InvalidFormatError: raised when the format of the JSON is
not valid. | [
"Parse",
"identities",
"using",
"Mozillians",
"format",
"."
] | 391cd37a75fea26311dc6908bc1c953c540a8e04 | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/parsing/mozilla.py#L84-L160 |
27,028 | chaoss/grimoirelab-sortinghat | sortinghat/cmd/organizations.py | Organizations.run | def run(self, *args):
"""List, add or delete organizations and domains from the registry.
By default, it prints the list of organizations available on
the registry.
"""
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 | python | 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 | [
"def",
"run",
"(",
"self",
",",
"*",
"args",
")",
":",
"params",
"=",
"self",
".",
"parser",
".",
"parse_args",
"(",
"args",
")",
"organization",
"=",
"params",
".",
"organization",
"domain",
"=",
"params",
".",
"domain",
"is_top_domain",
"=",
"params",
... | List, add or delete organizations and domains from the registry.
By default, it prints the list of organizations available on
the registry. | [
"List",
"add",
"or",
"delete",
"organizations",
"and",
"domains",
"from",
"the",
"registry",
"."
] | 391cd37a75fea26311dc6908bc1c953c540a8e04 | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/cmd/organizations.py#L110-L131 |
27,029 | chaoss/grimoirelab-sortinghat | sortinghat/cmd/organizations.py | Organizations.add | def add(self, organization, domain=None, is_top_domain=False, overwrite=False):
"""Add organizations and domains to the registry.
This method adds the given 'organization' or 'domain' to the registry,
but not both at the same time.
When 'organization' is the only parameter given, it will be added to
the registry. When 'domain' parameter is also given, the function will
assign it to 'organization'. In this case, 'organization' must exists in
the registry prior adding the domain.
A domain can only be assigned to one company. If the given domain is already
in the registry, the method will fail. Set 'overwrite' to 'True' to create
the new relationship. In this case, previous relationships will be removed.
The new domain can be also set as a top domain. That is useful to avoid
the insertion of sub-domains that belong to the same organization (i.e
eu.example.com, us.example.com). Take into account when 'overwrite' is set
it will update 'is_top_domain' flag too.
:param organization: name of the organization to add
:param domain: domain to add to the registry
:param is_top_domain: set the domain as a top domain
:param overwrite: force to reassign the domain to the given company
"""
# 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 | python | 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 | [
"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_S... | Add organizations and domains to the registry.
This method adds the given 'organization' or 'domain' to the registry,
but not both at the same time.
When 'organization' is the only parameter given, it will be added to
the registry. When 'domain' parameter is also given, the function will
assign it to 'organization'. In this case, 'organization' must exists in
the registry prior adding the domain.
A domain can only be assigned to one company. If the given domain is already
in the registry, the method will fail. Set 'overwrite' to 'True' to create
the new relationship. In this case, previous relationships will be removed.
The new domain can be also set as a top domain. That is useful to avoid
the insertion of sub-domains that belong to the same organization (i.e
eu.example.com, us.example.com). Take into account when 'overwrite' is set
it will update 'is_top_domain' flag too.
:param organization: name of the organization to add
:param domain: domain to add to the registry
:param is_top_domain: set the domain as a top domain
:param overwrite: force to reassign the domain to the given company | [
"Add",
"organizations",
"and",
"domains",
"to",
"the",
"registry",
"."
] | 391cd37a75fea26311dc6908bc1c953c540a8e04 | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/cmd/organizations.py#L133-L189 |
27,030 | chaoss/grimoirelab-sortinghat | sortinghat/cmd/organizations.py | Organizations.delete | def delete(self, organization, domain=None):
"""Remove organizations and domains from the registry.
The method removes the given 'organization' or 'domain' from the registry,
but not both at the same time.
When 'organization' is the only parameter given, it will be removed from
the registry, including those domains related to it. When 'domain' parameter
is also given, only the domain will be deleted. 'organization' must exists in
the registry prior removing the domain.
:param organization: name of the organization to remove
:param domain: domain to remove from the registry
"""
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 | python | 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 | [
"def",
"delete",
"(",
"self",
",",
"organization",
",",
"domain",
"=",
"None",
")",
":",
"if",
"not",
"organization",
":",
"return",
"CMD_SUCCESS",
"if",
"not",
"domain",
":",
"try",
":",
"api",
".",
"delete_organization",
"(",
"self",
".",
"db",
",",
... | Remove organizations and domains from the registry.
The method removes the given 'organization' or 'domain' from the registry,
but not both at the same time.
When 'organization' is the only parameter given, it will be removed from
the registry, including those domains related to it. When 'domain' parameter
is also given, only the domain will be deleted. 'organization' must exists in
the registry prior removing the domain.
:param organization: name of the organization to remove
:param domain: domain to remove from the registry | [
"Remove",
"organizations",
"and",
"domains",
"from",
"the",
"registry",
"."
] | 391cd37a75fea26311dc6908bc1c953c540a8e04 | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/cmd/organizations.py#L191-L221 |
27,031 | chaoss/grimoirelab-sortinghat | sortinghat/cmd/organizations.py | Organizations.registry | def registry(self, term=None):
"""List organizations and domains.
When no term is given, the method will list the organizations
existing in the registry. If 'term' is set, the method will list
only those organizations and domains that match with that term.
:param term: term to match
"""
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 | python | 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 | [
"def",
"registry",
"(",
"self",
",",
"term",
"=",
"None",
")",
":",
"try",
":",
"orgs",
"=",
"api",
".",
"registry",
"(",
"self",
".",
"db",
",",
"term",
")",
"self",
".",
"display",
"(",
"'organizations.tmpl'",
",",
"organizations",
"=",
"orgs",
")"... | List organizations and domains.
When no term is given, the method will list the organizations
existing in the registry. If 'term' is set, the method will list
only those organizations and domains that match with that term.
:param term: term to match | [
"List",
"organizations",
"and",
"domains",
"."
] | 391cd37a75fea26311dc6908bc1c953c540a8e04 | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/cmd/organizations.py#L223-L239 |
27,032 | chaoss/grimoirelab-sortinghat | sortinghat/parser.py | create_organizations_parser | def create_organizations_parser(stream):
"""Create an organizations parser for the given stream.
Factory function that creates an organizations parser for the
given stream. The stream is only used to guess the type of the
required parser.
:param stream: stream used to guess the type of the parser
:returns: an organizations parser
:raise InvalidFormatError: raised when no one of the available
parsers can parse the given 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) | python | 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) | [
"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... | Create an organizations parser for the given stream.
Factory function that creates an organizations parser for the
given stream. The stream is only used to guess the type of the
required parser.
:param stream: stream used to guess the type of the parser
:returns: an organizations parser
:raise InvalidFormatError: raised when no one of the available
parsers can parse the given stream | [
"Create",
"an",
"organizations",
"parser",
"for",
"the",
"given",
"stream",
"."
] | 391cd37a75fea26311dc6908bc1c953c540a8e04 | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/parser.py#L44-L68 |
27,033 | chaoss/grimoirelab-sortinghat | sortinghat/cmd/enroll.py | Enroll.enroll | def enroll(self, uuid, organization, from_date=MIN_PERIOD_DATE, to_date=MAX_PERIOD_DATE,
merge=False):
"""Enroll a unique identity in an organization.
This method adds a new relationship between the unique identity,
identified by <uuid>, and <organization>. Both entities must exist
on the registry before creating the new enrollment.
The period of the enrollment can be given with the parameters <from_date>
and <to_date>, where "from_date <= to_date". Default values for these
dates are '1900-01-01' and '2100-01-01'.
When "merge" parameter is set to True, those overlapped enrollments related
to <uuid> and <organization> found on the registry will be merged. The given
enrollment will be also merged.
:param uuid: unique identifier
:param organization: name of the organization
:param from_date: date when the enrollment starts
:param to_date: date when the enrollment ends
:param merge: merge overlapped enrollments; by default, it is set to 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 | python | 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 | [
"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",
... | Enroll a unique identity in an organization.
This method adds a new relationship between the unique identity,
identified by <uuid>, and <organization>. Both entities must exist
on the registry before creating the new enrollment.
The period of the enrollment can be given with the parameters <from_date>
and <to_date>, where "from_date <= to_date". Default values for these
dates are '1900-01-01' and '2100-01-01'.
When "merge" parameter is set to True, those overlapped enrollments related
to <uuid> and <organization> found on the registry will be merged. The given
enrollment will be also merged.
:param uuid: unique identifier
:param organization: name of the organization
:param from_date: date when the enrollment starts
:param to_date: date when the enrollment ends
:param merge: merge overlapped enrollments; by default, it is set to False | [
"Enroll",
"a",
"unique",
"identity",
"in",
"an",
"organization",
"."
] | 391cd37a75fea26311dc6908bc1c953c540a8e04 | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/cmd/enroll.py#L110-L165 |
27,034 | chaoss/grimoirelab-sortinghat | sortinghat/parsing/eclipse.py | EclipseParser.__parse_identities | def __parse_identities(self, json):
"""Parse identities using Eclipse format.
The Eclipse identities format is a JSON document under the "commiters"
key. The document should follow the next schema:
{
'committers' : {
'john': {
'affiliations': {
'1': {
'active': '2001-01-01',
'inactive': null,
'name': 'Organization 1'
}
},
'email': [
'john@example.com'
],
'first': 'John',
'id': 'john',
'last': 'Doe',
'primary': 'john.doe@example.com'
}
}
}
:parse json: JSON object to parse
:raise InvalidFormatError: raised when the format of the JSON is
not valid.
"""
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) | python | 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) | [
"def",
"__parse_identities",
"(",
"self",
",",
"json",
")",
":",
"try",
":",
"for",
"committer",
"in",
"json",
"[",
"'committers'",
"]",
".",
"values",
"(",
")",
":",
"name",
"=",
"self",
".",
"__encode",
"(",
"committer",
"[",
"'first'",
"]",
"+",
"... | Parse identities using Eclipse format.
The Eclipse identities format is a JSON document under the "commiters"
key. The document should follow the next schema:
{
'committers' : {
'john': {
'affiliations': {
'1': {
'active': '2001-01-01',
'inactive': null,
'name': 'Organization 1'
}
},
'email': [
'john@example.com'
],
'first': 'John',
'id': 'john',
'last': 'Doe',
'primary': 'john.doe@example.com'
}
}
}
:parse json: JSON object to parse
:raise InvalidFormatError: raised when the format of the JSON is
not valid. | [
"Parse",
"identities",
"using",
"Eclipse",
"format",
"."
] | 391cd37a75fea26311dc6908bc1c953c540a8e04 | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/parsing/eclipse.py#L83-L147 |
27,035 | chaoss/grimoirelab-sortinghat | sortinghat/parsing/eclipse.py | EclipseParser.__parse_organizations | def __parse_organizations(self, json):
"""Parse Eclipse organizations.
The Eclipse organizations format is a JSON document stored under the
"organizations" key. The next JSON shows the structure of the
document:
{
'organizations' : {
'1': {
'active': '2001-01-01 18:00:00',
'id': '1',
'image' : 'http://example.com/image/1',
'inactive' : null,
'isMember': '1',
'name': 'Organization 1',
'url': 'http://example.com/org/1'
},
'2': {
'active': '2015-12-31 23:59:59',
'id': '1',
'image' : 'http://example.com/image/2',
'inactive': '2008-01-01 18:00:00',
'isMember': '1',
'name': 'Organization 2',
'url': 'http://example.com/org/2'
}
}
}
:param json: JSON object to parse
:raises InvalidFormatError: raised when the format of the JSON is
not valid.
"""
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) | python | 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) | [
"def",
"__parse_organizations",
"(",
"self",
",",
"json",
")",
":",
"try",
":",
"for",
"organization",
"in",
"json",
"[",
"'organizations'",
"]",
".",
"values",
"(",
")",
":",
"name",
"=",
"self",
".",
"__encode",
"(",
"organization",
"[",
"'name'",
"]",... | Parse Eclipse organizations.
The Eclipse organizations format is a JSON document stored under the
"organizations" key. The next JSON shows the structure of the
document:
{
'organizations' : {
'1': {
'active': '2001-01-01 18:00:00',
'id': '1',
'image' : 'http://example.com/image/1',
'inactive' : null,
'isMember': '1',
'name': 'Organization 1',
'url': 'http://example.com/org/1'
},
'2': {
'active': '2015-12-31 23:59:59',
'id': '1',
'image' : 'http://example.com/image/2',
'inactive': '2008-01-01 18:00:00',
'isMember': '1',
'name': 'Organization 2',
'url': 'http://example.com/org/2'
}
}
}
:param json: JSON object to parse
:raises InvalidFormatError: raised when the format of the JSON is
not valid. | [
"Parse",
"Eclipse",
"organizations",
"."
] | 391cd37a75fea26311dc6908bc1c953c540a8e04 | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/parsing/eclipse.py#L149-L215 |
27,036 | chaoss/grimoirelab-sortinghat | sortinghat/parsing/eclipse.py | EclipseParser.__parse_affiliations_json | def __parse_affiliations_json(self, affiliations, uuid):
"""Parse identity's affiliations from a json dict"""
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 | python | 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 | [
"def",
"__parse_affiliations_json",
"(",
"self",
",",
"affiliations",
",",
"uuid",
")",
":",
"enrollments",
"=",
"[",
"]",
"for",
"affiliation",
"in",
"affiliations",
".",
"values",
"(",
")",
":",
"name",
"=",
"self",
".",
"__encode",
"(",
"affiliation",
"... | Parse identity's affiliations from a json dict | [
"Parse",
"identity",
"s",
"affiliations",
"from",
"a",
"json",
"dict"
] | 391cd37a75fea26311dc6908bc1c953c540a8e04 | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/parsing/eclipse.py#L217-L256 |
27,037 | chaoss/grimoirelab-sortinghat | sortinghat/api.py | add_unique_identity | def add_unique_identity(db, uuid):
"""Add a unique identity to the registry.
This function adds a unique identity to the registry.
First, it checks if the unique identifier (uuid) used to create the
identity is already on the registry. When it is not found, a new unique
identity is created. Otherwise, it raises a 'AlreadyExistError' exception.
:param db: database manager
:param uuid: unique identifier for the identity
:raises InvalidValueError: when uuid is None or an empty string
:raises AlreadyExistsError: when the identifier already exists
in the registry.
"""
with db.connect() as session:
try:
add_unique_identity_db(session, uuid)
except ValueError as e:
raise InvalidValueError(e) | python | 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) | [
"def",
"add_unique_identity",
"(",
"db",
",",
"uuid",
")",
":",
"with",
"db",
".",
"connect",
"(",
")",
"as",
"session",
":",
"try",
":",
"add_unique_identity_db",
"(",
"session",
",",
"uuid",
")",
"except",
"ValueError",
"as",
"e",
":",
"raise",
"Invali... | Add a unique identity to the registry.
This function adds a unique identity to the registry.
First, it checks if the unique identifier (uuid) used to create the
identity is already on the registry. When it is not found, a new unique
identity is created. Otherwise, it raises a 'AlreadyExistError' exception.
:param db: database manager
:param uuid: unique identifier for the identity
:raises InvalidValueError: when uuid is None or an empty string
:raises AlreadyExistsError: when the identifier already exists
in the registry. | [
"Add",
"a",
"unique",
"identity",
"to",
"the",
"registry",
"."
] | 391cd37a75fea26311dc6908bc1c953c540a8e04 | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/api.py#L54-L73 |
27,038 | chaoss/grimoirelab-sortinghat | sortinghat/api.py | add_organization | def add_organization(db, organization):
"""Add an organization to the registry.
This function adds an organization to the registry.
It checks first whether the organization is already on the registry.
When it is not found, the new organization is added. Otherwise,
it raises a 'AlreadyExistsError' exception to notify that the organization
already exists.
:param db: database manager
:param organization: name of the organization
:raises InvalidValueError: raised when organization is None or an empty string
:raises AlreadyExistsError: raised when the organization already exists
in the registry.
"""
with db.connect() as session:
try:
add_organization_db(session, organization)
except ValueError as e:
raise InvalidValueError(e) | python | def add_organization(db, organization):
with db.connect() as session:
try:
add_organization_db(session, organization)
except ValueError as e:
raise InvalidValueError(e) | [
"def",
"add_organization",
"(",
"db",
",",
"organization",
")",
":",
"with",
"db",
".",
"connect",
"(",
")",
"as",
"session",
":",
"try",
":",
"add_organization_db",
"(",
"session",
",",
"organization",
")",
"except",
"ValueError",
"as",
"e",
":",
"raise",... | Add an organization to the registry.
This function adds an organization to the registry.
It checks first whether the organization is already on the registry.
When it is not found, the new organization is added. Otherwise,
it raises a 'AlreadyExistsError' exception to notify that the organization
already exists.
:param db: database manager
:param organization: name of the organization
:raises InvalidValueError: raised when organization is None or an empty string
:raises AlreadyExistsError: raised when the organization already exists
in the registry. | [
"Add",
"an",
"organization",
"to",
"the",
"registry",
"."
] | 391cd37a75fea26311dc6908bc1c953c540a8e04 | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/api.py#L140-L160 |
27,039 | chaoss/grimoirelab-sortinghat | sortinghat/api.py | add_domain | def add_domain(db, organization, domain, is_top_domain=False, overwrite=False):
"""Add a domain to the registry.
This function adds a new domain to the given organization.
The organization must exists on the registry prior to insert the new
domain. Otherwise, it will raise a 'NotFoundError' exception. Moreover,
if the given domain is already in the registry an 'AlreadyExistsError'
exception will be raised.
The new domain can be also set as a top domain. That is useful to avoid
the insertion of sub-domains that belong to the same organization (i.e
eu.example.com, us.example.com).
Remember that a domain can only be assigned to one (and only one)
organization.
When the given domain already exist on the registry, you can use
'overwrite' parameter to update its information. For instance, shift
the domain to another organization or to update the top domain flag.
Take into account that both fields will be updated at the same time.
:param db: database manager
:param organization: name of the organization
:param domain: domain to add to the registry
:param is_top_domain: set this domain as a top domain
:param overwrite: force to reassign the domain to the given organization
and to update top domain field
:raises InvalidValueError: raised when domain is None or an empty string or
is_top_domain does not have a boolean value
:raises NotFoundError: raised when the given organization is not found
in the registry
:raises AlreadyExistsError: raised when the domain already exists
in the registry
"""
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) | python | 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) | [
"def",
"add_domain",
"(",
"db",
",",
"organization",
",",
"domain",
",",
"is_top_domain",
"=",
"False",
",",
"overwrite",
"=",
"False",
")",
":",
"with",
"db",
".",
"connect",
"(",
")",
"as",
"session",
":",
"org",
"=",
"find_organization",
"(",
"session... | Add a domain to the registry.
This function adds a new domain to the given organization.
The organization must exists on the registry prior to insert the new
domain. Otherwise, it will raise a 'NotFoundError' exception. Moreover,
if the given domain is already in the registry an 'AlreadyExistsError'
exception will be raised.
The new domain can be also set as a top domain. That is useful to avoid
the insertion of sub-domains that belong to the same organization (i.e
eu.example.com, us.example.com).
Remember that a domain can only be assigned to one (and only one)
organization.
When the given domain already exist on the registry, you can use
'overwrite' parameter to update its information. For instance, shift
the domain to another organization or to update the top domain flag.
Take into account that both fields will be updated at the same time.
:param db: database manager
:param organization: name of the organization
:param domain: domain to add to the registry
:param is_top_domain: set this domain as a top domain
:param overwrite: force to reassign the domain to the given organization
and to update top domain field
:raises InvalidValueError: raised when domain is None or an empty string or
is_top_domain does not have a boolean value
:raises NotFoundError: raised when the given organization is not found
in the registry
:raises AlreadyExistsError: raised when the domain already exists
in the registry | [
"Add",
"a",
"domain",
"to",
"the",
"registry",
"."
] | 391cd37a75fea26311dc6908bc1c953c540a8e04 | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/api.py#L163-L215 |
27,040 | chaoss/grimoirelab-sortinghat | sortinghat/api.py | add_to_matching_blacklist | def add_to_matching_blacklist(db, entity):
"""Add entity to the matching blacklist.
This function adds an 'entity' o term to the matching blacklist.
The term to add cannot have a None or empty value, in this case
a InvalidValueError will be raised. If the given 'entity' exists in the
registry, the function will raise an AlreadyExistsError exception.
:param db: database manager
:param entity: term, word or value to blacklist
:raises InvalidValueError: raised when entity is None or an empty string
:raises AlreadyExistsError: raised when the entity already exists
in the registry.
"""
with db.connect() as session:
try:
add_to_matching_blacklist_db(session, entity)
except ValueError as e:
raise InvalidValueError(e) | python | 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) | [
"def",
"add_to_matching_blacklist",
"(",
"db",
",",
"entity",
")",
":",
"with",
"db",
".",
"connect",
"(",
")",
"as",
"session",
":",
"try",
":",
"add_to_matching_blacklist_db",
"(",
"session",
",",
"entity",
")",
"except",
"ValueError",
"as",
"e",
":",
"r... | Add entity to the matching blacklist.
This function adds an 'entity' o term to the matching blacklist.
The term to add cannot have a None or empty value, in this case
a InvalidValueError will be raised. If the given 'entity' exists in the
registry, the function will raise an AlreadyExistsError exception.
:param db: database manager
:param entity: term, word or value to blacklist
:raises InvalidValueError: raised when entity is None or an empty string
:raises AlreadyExistsError: raised when the entity already exists
in the registry. | [
"Add",
"entity",
"to",
"the",
"matching",
"blacklist",
"."
] | 391cd37a75fea26311dc6908bc1c953c540a8e04 | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/api.py#L279-L298 |
27,041 | chaoss/grimoirelab-sortinghat | sortinghat/api.py | delete_unique_identity | def delete_unique_identity(db, uuid):
"""Remove a unique identity from the registry.
Function that removes from the registry, the unique identity
that matches with uuid. Data related to this identity will be
also removed.
It checks first whether the unique identity is already on the registry.
When it is found, the unique identity is removed. Otherwise, it will
raise a 'NotFoundError' exception.
:param db: database manager
:param uuid: unique identifier assigned to the unique identity set
for being removed
:raises NotFoundError: raised when the unique identity does not exist
in the registry.
"""
with db.connect() as session:
uidentity = find_unique_identity(session, uuid)
if not uidentity:
raise NotFoundError(entity=uuid)
delete_unique_identity_db(session, uidentity) | python | 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) | [
"def",
"delete_unique_identity",
"(",
"db",
",",
"uuid",
")",
":",
"with",
"db",
".",
"connect",
"(",
")",
"as",
"session",
":",
"uidentity",
"=",
"find_unique_identity",
"(",
"session",
",",
"uuid",
")",
"if",
"not",
"uidentity",
":",
"raise",
"NotFoundEr... | Remove a unique identity from the registry.
Function that removes from the registry, the unique identity
that matches with uuid. Data related to this identity will be
also removed.
It checks first whether the unique identity is already on the registry.
When it is found, the unique identity is removed. Otherwise, it will
raise a 'NotFoundError' exception.
:param db: database manager
:param uuid: unique identifier assigned to the unique identity set
for being removed
:raises NotFoundError: raised when the unique identity does not exist
in the registry. | [
"Remove",
"a",
"unique",
"identity",
"from",
"the",
"registry",
"."
] | 391cd37a75fea26311dc6908bc1c953c540a8e04 | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/api.py#L339-L363 |
27,042 | chaoss/grimoirelab-sortinghat | sortinghat/api.py | delete_from_matching_blacklist | def delete_from_matching_blacklist(db, entity):
"""Remove an blacklisted entity from the registry.
This function removes the given blacklisted entity from the registry.
It checks first whether the excluded entity is already on the registry.
When it is found, the entity is removed. Otherwise, it will raise
a 'NotFoundError'.
:param db: database manager
:param entity: blacklisted entity to remove
:raises NotFoundError: raised when the blacklisted entity does not exist
in the registry.
"""
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) | python | 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) | [
"def",
"delete_from_matching_blacklist",
"(",
"db",
",",
"entity",
")",
":",
"with",
"db",
".",
"connect",
"(",
")",
"as",
"session",
":",
"mb",
"=",
"session",
".",
"query",
"(",
"MatchingBlacklist",
")",
".",
"filter",
"(",
"MatchingBlacklist",
".",
"exc... | Remove an blacklisted entity from the registry.
This function removes the given blacklisted entity from the registry.
It checks first whether the excluded entity is already on the registry.
When it is found, the entity is removed. Otherwise, it will raise
a 'NotFoundError'.
:param db: database manager
:param entity: blacklisted entity to remove
:raises NotFoundError: raised when the blacklisted entity does not exist
in the registry. | [
"Remove",
"an",
"blacklisted",
"entity",
"from",
"the",
"registry",
"."
] | 391cd37a75fea26311dc6908bc1c953c540a8e04 | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/api.py#L509-L530 |
27,043 | chaoss/grimoirelab-sortinghat | sortinghat/api.py | merge_enrollments | def merge_enrollments(db, uuid, organization):
"""Merge overlapping enrollments.
This function merges those enrollments, related to the given 'uuid' and
'organization', that have overlapping dates. Default start and end dates
(1900-01-01 and 2100-01-01) are considered range limits and will be
removed when a set of ranges overlap. For example:
* [(1900-01-01, 2010-01-01), (2008-01-01, 2100-01-01)]
--> (2008-01-01, 2010-01-01)
* [(1900-01-01, 2010-01-01), (2008-01-01, 2010-01-01), (2010-01-02, 2100-01-01)]
--> (2008-01-01, 2010-01-01),(2010-01-02, 2100-01-01)
* [(1900-01-01, 2010-01-01), (2010-01-02, 2100-01-01)]
--> (1900-01-01, 2010-01-01), (2010-01-02, 2100-01-01)
It may raise a InvalidValueError when any date is out of bounds. In other words, when
any date < 1900-01-01 or date > 2100-01-01.
:param db: database manager
:param uuid: unique identifier
:param organization: name of the organization
:raises NotFoundError: when either 'uuid' or 'organization' are not
found in the registry. It is also raised when there are not enrollments
related to 'uuid' and 'organization'
:raises InvalidValueError: when any date is out of bounds
"""
# 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) | python | 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) | [
"def",
"merge_enrollments",
"(",
"db",
",",
"uuid",
",",
"organization",
")",
":",
"# Merge enrollments",
"with",
"db",
".",
"connect",
"(",
")",
"as",
"session",
":",
"uidentity",
"=",
"find_unique_identity",
"(",
"session",
",",
"uuid",
")",
"if",
"not",
... | Merge overlapping enrollments.
This function merges those enrollments, related to the given 'uuid' and
'organization', that have overlapping dates. Default start and end dates
(1900-01-01 and 2100-01-01) are considered range limits and will be
removed when a set of ranges overlap. For example:
* [(1900-01-01, 2010-01-01), (2008-01-01, 2100-01-01)]
--> (2008-01-01, 2010-01-01)
* [(1900-01-01, 2010-01-01), (2008-01-01, 2010-01-01), (2010-01-02, 2100-01-01)]
--> (2008-01-01, 2010-01-01),(2010-01-02, 2100-01-01)
* [(1900-01-01, 2010-01-01), (2010-01-02, 2100-01-01)]
--> (1900-01-01, 2010-01-01), (2010-01-02, 2100-01-01)
It may raise a InvalidValueError when any date is out of bounds. In other words, when
any date < 1900-01-01 or date > 2100-01-01.
:param db: database manager
:param uuid: unique identifier
:param organization: name of the organization
:raises NotFoundError: when either 'uuid' or 'organization' are not
found in the registry. It is also raised when there are not enrollments
related to 'uuid' and 'organization'
:raises InvalidValueError: when any date is out of bounds | [
"Merge",
"overlapping",
"enrollments",
"."
] | 391cd37a75fea26311dc6908bc1c953c540a8e04 | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/api.py#L632-L703 |
27,044 | chaoss/grimoirelab-sortinghat | sortinghat/api.py | match_identities | def match_identities(db, uuid, matcher):
"""Search for similar unique identities.
The function will search in the registry for similar identities to 'uuid'.
The result will be a list matches containing unique identities objects.
This list will not(!) include the given unique identity.
The criteria used to check when an identity matches with another one
is defined by 'matcher' parameter. This parameter is an instance
of 'IdentityMatcher' class.
:param db: database manager
:param uuid: identifier of the identity to match
:param matcher: criteria used to match identities
:returns: list of matched unique identities
:raises NotFoundError: raised when 'uuid' does not exist in the
registry
"""
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 | python | 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 | [
"def",
"match_identities",
"(",
"db",
",",
"uuid",
",",
"matcher",
")",
":",
"uidentities",
"=",
"[",
"]",
"with",
"db",
".",
"connect",
"(",
")",
"as",
"session",
":",
"uidentity",
"=",
"find_unique_identity",
"(",
"session",
",",
"uuid",
")",
"if",
"... | Search for similar unique identities.
The function will search in the registry for similar identities to 'uuid'.
The result will be a list matches containing unique identities objects.
This list will not(!) include the given unique identity.
The criteria used to check when an identity matches with another one
is defined by 'matcher' parameter. This parameter is an instance
of 'IdentityMatcher' class.
:param db: database manager
:param uuid: identifier of the identity to match
:param matcher: criteria used to match identities
:returns: list of matched unique identities
:raises NotFoundError: raised when 'uuid' does not exist in the
registry | [
"Search",
"for",
"similar",
"unique",
"identities",
"."
] | 391cd37a75fea26311dc6908bc1c953c540a8e04 | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/api.py#L745-L786 |
27,045 | chaoss/grimoirelab-sortinghat | sortinghat/api.py | unique_identities | def unique_identities(db, uuid=None, source=None):
"""List the unique identities available in the registry.
The function returns a list of unique identities. When 'uuid'
parameter is set, it will only return the information related
to the unique identity identified by 'uuid'. When 'source' is
given, only thouse unique identities with one or more identities
related to that source will be returned.
When the given 'uuid', assigned to the given 'source', is not in the
registry, a 'NotFoundError' exception will be raised.
:param db: database manager
:param uuid: unique identifier for the identity
:param source: source of the identities
:raises NotFoundError: raised when the given uuid is not found
in the registry
"""
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 | python | 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 | [
"def",
"unique_identities",
"(",
"db",
",",
"uuid",
"=",
"None",
",",
"source",
"=",
"None",
")",
":",
"uidentities",
"=",
"[",
"]",
"with",
"db",
".",
"connect",
"(",
")",
"as",
"session",
":",
"query",
"=",
"session",
".",
"query",
"(",
"UniqueIden... | List the unique identities available in the registry.
The function returns a list of unique identities. When 'uuid'
parameter is set, it will only return the information related
to the unique identity identified by 'uuid'. When 'source' is
given, only thouse unique identities with one or more identities
related to that source will be returned.
When the given 'uuid', assigned to the given 'source', is not in the
registry, a 'NotFoundError' exception will be raised.
:param db: database manager
:param uuid: unique identifier for the identity
:param source: source of the identities
:raises NotFoundError: raised when the given uuid is not found
in the registry | [
"List",
"the",
"unique",
"identities",
"available",
"in",
"the",
"registry",
"."
] | 391cd37a75fea26311dc6908bc1c953c540a8e04 | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/api.py#L789-L833 |
27,046 | chaoss/grimoirelab-sortinghat | sortinghat/api.py | search_unique_identities | def search_unique_identities(db, term, source=None):
"""Look for unique identities.
This function returns those unique identities which match with the
given 'term'. The term will be compated with name, email, username
and source values of each identity. When `source` is given, this
search will be only performed on identities linked to this source.
:param db: database manater
:param term: term to match with unique identities data
:param source: search only on identities from this source
:raises NotFoundError: raised when the given term is not found on
any unique identity from the registry
"""
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 | python | 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 | [
"def",
"search_unique_identities",
"(",
"db",
",",
"term",
",",
"source",
"=",
"None",
")",
":",
"uidentities",
"=",
"[",
"]",
"pattern",
"=",
"'%'",
"+",
"term",
"+",
"'%'",
"if",
"term",
"else",
"None",
"with",
"db",
".",
"connect",
"(",
")",
"as",... | Look for unique identities.
This function returns those unique identities which match with the
given 'term'. The term will be compated with name, email, username
and source values of each identity. When `source` is given, this
search will be only performed on identities linked to this source.
:param db: database manater
:param term: term to match with unique identities data
:param source: search only on identities from this source
:raises NotFoundError: raised when the given term is not found on
any unique identity from the registry | [
"Look",
"for",
"unique",
"identities",
"."
] | 391cd37a75fea26311dc6908bc1c953c540a8e04 | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/api.py#L836-L881 |
27,047 | chaoss/grimoirelab-sortinghat | sortinghat/api.py | search_unique_identities_slice | def search_unique_identities_slice(db, term, offset, limit):
"""Look for unique identities using slicing.
This function returns those unique identities which match with the
given `term`. The term will be compared with name, email, username
and source values of each identity. When an empty term is given,
all unique identities will be returned. The results are limited
by `offset` (starting on 0) and `limit`.
Along with the list of unique identities, this function returns
the total number of unique identities that match the given `term`.
:param db: database manager
:param term: term to match with unique identities data
:param offset: return results starting on this position
:param limit: maximum number of unique identities to return
:raises InvalidValueError: raised when either the given value of
`offset` or `limit` is lower than zero
"""
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 | python | 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 | [
"def",
"search_unique_identities_slice",
"(",
"db",
",",
"term",
",",
"offset",
",",
"limit",
")",
":",
"uidentities",
"=",
"[",
"]",
"pattern",
"=",
"'%'",
"+",
"term",
"+",
"'%'",
"if",
"term",
"else",
"None",
"if",
"offset",
"<",
"0",
":",
"raise",
... | Look for unique identities using slicing.
This function returns those unique identities which match with the
given `term`. The term will be compared with name, email, username
and source values of each identity. When an empty term is given,
all unique identities will be returned. The results are limited
by `offset` (starting on 0) and `limit`.
Along with the list of unique identities, this function returns
the total number of unique identities that match the given `term`.
:param db: database manager
:param term: term to match with unique identities data
:param offset: return results starting on this position
:param limit: maximum number of unique identities to return
:raises InvalidValueError: raised when either the given value of
`offset` or `limit` is lower than zero | [
"Look",
"for",
"unique",
"identities",
"using",
"slicing",
"."
] | 391cd37a75fea26311dc6908bc1c953c540a8e04 | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/api.py#L884-L939 |
27,048 | chaoss/grimoirelab-sortinghat | sortinghat/api.py | search_last_modified_identities | def search_last_modified_identities(db, after):
"""Look for the uuids of identities modified on or after a given date.
This function returns the uuids of identities modified on
the given date or after it. The result is a list of uuids
identities.
:param db: database manager
:param after: look for identities modified on or after this date
:returns: a list of uuids of identities modified
"""
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 | python | 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 | [
"def",
"search_last_modified_identities",
"(",
"db",
",",
"after",
")",
":",
"with",
"db",
".",
"connect",
"(",
")",
"as",
"session",
":",
"query",
"=",
"session",
".",
"query",
"(",
"Identity",
".",
"id",
")",
".",
"filter",
"(",
"Identity",
".",
"las... | Look for the uuids of identities modified on or after a given date.
This function returns the uuids of identities modified on
the given date or after it. The result is a list of uuids
identities.
:param db: database manager
:param after: look for identities modified on or after this date
:returns: a list of uuids of identities modified | [
"Look",
"for",
"the",
"uuids",
"of",
"identities",
"modified",
"on",
"or",
"after",
"a",
"given",
"date",
"."
] | 391cd37a75fea26311dc6908bc1c953c540a8e04 | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/api.py#L942-L959 |
27,049 | chaoss/grimoirelab-sortinghat | sortinghat/api.py | search_last_modified_unique_identities | def search_last_modified_unique_identities(db, after):
"""Look for the uuids of unique identities modified on or
after a given date.
This function returns the uuids of unique identities
modified on the given date or after it. The result is a
list of uuids unique identities.
:param db: database manager
:param after: look for identities modified on or after this date
:returns: a list of uuids of unique identities modified
"""
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 | python | 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 | [
"def",
"search_last_modified_unique_identities",
"(",
"db",
",",
"after",
")",
":",
"with",
"db",
".",
"connect",
"(",
")",
"as",
"session",
":",
"query",
"=",
"session",
".",
"query",
"(",
"UniqueIdentity",
".",
"uuid",
")",
".",
"filter",
"(",
"UniqueIde... | Look for the uuids of unique identities modified on or
after a given date.
This function returns the uuids of unique identities
modified on the given date or after it. The result is a
list of uuids unique identities.
:param db: database manager
:param after: look for identities modified on or after this date
:returns: a list of uuids of unique identities modified | [
"Look",
"for",
"the",
"uuids",
"of",
"unique",
"identities",
"modified",
"on",
"or",
"after",
"a",
"given",
"date",
"."
] | 391cd37a75fea26311dc6908bc1c953c540a8e04 | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/api.py#L962-L980 |
27,050 | chaoss/grimoirelab-sortinghat | sortinghat/api.py | search_profiles | def search_profiles(db, no_gender=False):
"""List unique identities profiles.
The function will return the list of profiles filtered by the
given parameters. When `no_gender` is set, only profiles without
gender values will be returned.
:param db: database manager
:param no_gender: return only those profiles without gender
:returns: a list of profile entities
"""
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 | python | 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 | [
"def",
"search_profiles",
"(",
"db",
",",
"no_gender",
"=",
"False",
")",
":",
"profiles",
"=",
"[",
"]",
"with",
"db",
".",
"connect",
"(",
")",
"as",
"session",
":",
"query",
"=",
"session",
".",
"query",
"(",
"Profile",
")",
"if",
"no_gender",
":"... | List unique identities profiles.
The function will return the list of profiles filtered by the
given parameters. When `no_gender` is set, only profiles without
gender values will be returned.
:param db: database manager
:param no_gender: return only those profiles without gender
:returns: a list of profile entities | [
"List",
"unique",
"identities",
"profiles",
"."
] | 391cd37a75fea26311dc6908bc1c953c540a8e04 | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/api.py#L983-L1008 |
27,051 | chaoss/grimoirelab-sortinghat | sortinghat/api.py | registry | def registry(db, term=None):
"""List the organizations available in the registry.
The function will return the list of organizations. If term
parameter is set, it will only return the information about
the organizations which match that term. When the given term does
not match with any organization from the registry a 'NotFounError'
exception will be raised.
:param db: database manager
:param term: term to match with organizations names
:returns: a list of organizations sorted by their name
:raises NotFoundError: raised when the given term is not found on
any organization from the registry
"""
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 | python | 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 | [
"def",
"registry",
"(",
"db",
",",
"term",
"=",
"None",
")",
":",
"orgs",
"=",
"[",
"]",
"with",
"db",
".",
"connect",
"(",
")",
"as",
"session",
":",
"if",
"term",
":",
"orgs",
"=",
"session",
".",
"query",
"(",
"Organization",
")",
".",
"filter... | List the organizations available in the registry.
The function will return the list of organizations. If term
parameter is set, it will only return the information about
the organizations which match that term. When the given term does
not match with any organization from the registry a 'NotFounError'
exception will be raised.
:param db: database manager
:param term: term to match with organizations names
:returns: a list of organizations sorted by their name
:raises NotFoundError: raised when the given term is not found on
any organization from the registry | [
"List",
"the",
"organizations",
"available",
"in",
"the",
"registry",
"."
] | 391cd37a75fea26311dc6908bc1c953c540a8e04 | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/api.py#L1011-L1045 |
27,052 | chaoss/grimoirelab-sortinghat | sortinghat/api.py | domains | def domains(db, domain=None, top=False):
"""List the domains available in the registry.
The function will return the list of domains. Settting the top flag,
it will look for those domains that are top domains. If domain parameter
is set, it will only return the information about that domain.
When both paramaters are set, it will first search for the given domain.
If it is not found, it will look for its top domains. In the case of
neither the domain exists nor has top domains, a 'NotFoundError' exception
will be raised.
:param db: database manager
:param domain: name of the domain
:param top: filter by top domains
:returns: a list of domains
:raises NotFoundError: raised when the given domain is not found in the
registry
"""
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 | python | 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 | [
"def",
"domains",
"(",
"db",
",",
"domain",
"=",
"None",
",",
"top",
"=",
"False",
")",
":",
"doms",
"=",
"[",
"]",
"with",
"db",
".",
"connect",
"(",
")",
"as",
"session",
":",
"if",
"domain",
":",
"dom",
"=",
"find_domain",
"(",
"session",
",",... | List the domains available in the registry.
The function will return the list of domains. Settting the top flag,
it will look for those domains that are top domains. If domain parameter
is set, it will only return the information about that domain.
When both paramaters are set, it will first search for the given domain.
If it is not found, it will look for its top domains. In the case of
neither the domain exists nor has top domains, a 'NotFoundError' exception
will be raised.
:param db: database manager
:param domain: name of the domain
:param top: filter by top domains
:returns: a list of domains
:raises NotFoundError: raised when the given domain is not found in the
registry | [
"List",
"the",
"domains",
"available",
"in",
"the",
"registry",
"."
] | 391cd37a75fea26311dc6908bc1c953c540a8e04 | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/api.py#L1048-L1107 |
27,053 | chaoss/grimoirelab-sortinghat | sortinghat/api.py | countries | def countries(db, code=None, term=None):
"""List the countries available in the registry.
The function will return the list of countries. When either 'code' or
'term' parameters are set, it will only return the information about
those countries that match them.
Take into account that 'code' is a country identifier composed by two
letters (i.e ES or US). A 'InvalidValueError' exception will be raised when
this identifier is not valid. If this value is valid, 'term' parameter
will be ignored.
When the given values do not match with any country from the registry
a 'NotFounError' exception will be raised.
:param db: database manager
:param code: country identifier composed by two letters
:param term: term to match with countries names
:returns: a list of countries sorted by their country id
:raises InvalidValueError: raised when 'code' is not a string composed by
two letters
:raises NotFoundError: raised when the given 'code' or 'term' is not
found for any country from the registry
"""
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 | python | 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 | [
"def",
"countries",
"(",
"db",
",",
"code",
"=",
"None",
",",
"term",
"=",
"None",
")",
":",
"def",
"_is_code_valid",
"(",
"code",
")",
":",
"return",
"type",
"(",
"code",
")",
"==",
"str",
"and",
"len",
"(",
"code",
")",
"==",
"2",
"and",
"code"... | List the countries available in the registry.
The function will return the list of countries. When either 'code' or
'term' parameters are set, it will only return the information about
those countries that match them.
Take into account that 'code' is a country identifier composed by two
letters (i.e ES or US). A 'InvalidValueError' exception will be raised when
this identifier is not valid. If this value is valid, 'term' parameter
will be ignored.
When the given values do not match with any country from the registry
a 'NotFounError' exception will be raised.
:param db: database manager
:param code: country identifier composed by two letters
:param term: term to match with countries names
:returns: a list of countries sorted by their country id
:raises InvalidValueError: raised when 'code' is not a string composed by
two letters
:raises NotFoundError: raised when the given 'code' or 'term' is not
found for any country from the registry | [
"List",
"the",
"countries",
"available",
"in",
"the",
"registry",
"."
] | 391cd37a75fea26311dc6908bc1c953c540a8e04 | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/api.py#L1110-L1169 |
27,054 | chaoss/grimoirelab-sortinghat | sortinghat/api.py | enrollments | def enrollments(db, uuid=None, organization=None, from_date=None, to_date=None):
"""List the enrollment information available in the registry.
This function will return a list of enrollments. If 'uuid'
parameter is set, it will return the enrollments related to that
unique identity; if 'organization' parameter is given, it will
return the enrollments related to that organization; if both
parameters are set, the function will return the list of enrollments
of 'uuid' on the 'organization'.
Enrollments between a period can also be listed using 'from_date' and
'to_date' parameters. When these are set, the function will return
all those enrollments where Enrollment.start >= from_date AND
Enrollment.end <= to_date. Defaults values for these dates are
1900-01-01 and 2100-01-01.
When either 'uuid' or 'organization' are not in the registry a
'NotFoundError' exception will be raised.
:param db: database manager
:param uuid: unique identifier
:param organization: name of the organization
:param from_date: date when the enrollment starts
:param to_date: date when the enrollment ends
:returns: a list of enrollments sorted by uuid or by organization.
:raises NotFoundError: when either 'uuid' or 'organization' are not
found in the registry.
:raises InvalidValeError: it is raised in two cases, when "from_date" < 1900-01-01 or
"to_date" > 2100-01-01; when "from_date > to_date".
"""
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 | python | 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 | [
"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",... | List the enrollment information available in the registry.
This function will return a list of enrollments. If 'uuid'
parameter is set, it will return the enrollments related to that
unique identity; if 'organization' parameter is given, it will
return the enrollments related to that organization; if both
parameters are set, the function will return the list of enrollments
of 'uuid' on the 'organization'.
Enrollments between a period can also be listed using 'from_date' and
'to_date' parameters. When these are set, the function will return
all those enrollments where Enrollment.start >= from_date AND
Enrollment.end <= to_date. Defaults values for these dates are
1900-01-01 and 2100-01-01.
When either 'uuid' or 'organization' are not in the registry a
'NotFoundError' exception will be raised.
:param db: database manager
:param uuid: unique identifier
:param organization: name of the organization
:param from_date: date when the enrollment starts
:param to_date: date when the enrollment ends
:returns: a list of enrollments sorted by uuid or by organization.
:raises NotFoundError: when either 'uuid' or 'organization' are not
found in the registry.
:raises InvalidValeError: it is raised in two cases, when "from_date" < 1900-01-01 or
"to_date" > 2100-01-01; when "from_date > to_date". | [
"List",
"the",
"enrollment",
"information",
"available",
"in",
"the",
"registry",
"."
] | 391cd37a75fea26311dc6908bc1c953c540a8e04 | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/api.py#L1172-L1253 |
27,055 | chaoss/grimoirelab-sortinghat | sortinghat/api.py | blacklist | def blacklist(db, term=None):
"""List the blacklisted entities available in the registry.
The function will return the list of blacklisted entities. If term
parameter is set, it will only return the information about the
entities which match that term. When the given term does not match
with any entry on the blacklist a 'NotFoundError' exception will
be raised.
:param db: database manager
:param term: term to match with blacklisted entries
:returns: a list of blacklisted entities sorted by their name
:raises NotFoundError: raised when the given term is not found on
any blacklisted entry from the registry
"""
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 | python | 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 | [
"def",
"blacklist",
"(",
"db",
",",
"term",
"=",
"None",
")",
":",
"mbs",
"=",
"[",
"]",
"with",
"db",
".",
"connect",
"(",
")",
"as",
"session",
":",
"if",
"term",
":",
"mbs",
"=",
"session",
".",
"query",
"(",
"MatchingBlacklist",
")",
".",
"fi... | List the blacklisted entities available in the registry.
The function will return the list of blacklisted entities. If term
parameter is set, it will only return the information about the
entities which match that term. When the given term does not match
with any entry on the blacklist a 'NotFoundError' exception will
be raised.
:param db: database manager
:param term: term to match with blacklisted entries
:returns: a list of blacklisted entities sorted by their name
:raises NotFoundError: raised when the given term is not found on
any blacklisted entry from the registry | [
"List",
"the",
"blacklisted",
"entities",
"available",
"in",
"the",
"registry",
"."
] | 391cd37a75fea26311dc6908bc1c953c540a8e04 | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/api.py#L1256-L1290 |
27,056 | chaoss/grimoirelab-sortinghat | sortinghat/cmd/profile.py | Profile.run | def run(self, *args):
"""Endit profile information."""
uuid, kwargs = self.__parse_arguments(*args)
code = self.edit_profile(uuid, **kwargs)
return code | python | def run(self, *args):
uuid, kwargs = self.__parse_arguments(*args)
code = self.edit_profile(uuid, **kwargs)
return code | [
"def",
"run",
"(",
"self",
",",
"*",
"args",
")",
":",
"uuid",
",",
"kwargs",
"=",
"self",
".",
"__parse_arguments",
"(",
"*",
"args",
")",
"code",
"=",
"self",
".",
"edit_profile",
"(",
"uuid",
",",
"*",
"*",
"kwargs",
")",
"return",
"code"
] | Endit profile information. | [
"Endit",
"profile",
"information",
"."
] | 391cd37a75fea26311dc6908bc1c953c540a8e04 | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/cmd/profile.py#L89-L95 |
27,057 | chaoss/grimoirelab-sortinghat | sortinghat/cmd/unify.py | Unify.__unify_unique_identities | def __unify_unique_identities(self, uidentities, matcher,
fast_matching, interactive):
"""Unify unique identities looking for similar identities."""
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() | python | 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() | [
"def",
"__unify_unique_identities",
"(",
"self",
",",
"uidentities",
",",
"matcher",
",",
"fast_matching",
",",
"interactive",
")",
":",
"self",
".",
"total",
"=",
"len",
"(",
"uidentities",
")",
"self",
".",
"matched",
"=",
"0",
"if",
"self",
".",
"recove... | Unify unique identities looking for similar identities. | [
"Unify",
"unique",
"identities",
"looking",
"for",
"similar",
"identities",
"."
] | 391cd37a75fea26311dc6908bc1c953c540a8e04 | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/cmd/unify.py#L166-L184 |
27,058 | chaoss/grimoirelab-sortinghat | sortinghat/cmd/unify.py | Unify.__merge | def __merge(self, matched, interactive):
"""Merge a lists of matched unique identities"""
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 | python | 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 | [
"def",
"__merge",
"(",
"self",
",",
"matched",
",",
"interactive",
")",
":",
"for",
"m",
"in",
"matched",
":",
"identities",
"=",
"m",
"[",
"'identities'",
"]",
"uuid",
"=",
"identities",
"[",
"0",
"]",
"try",
":",
"for",
"c",
"in",
"identities",
"["... | Merge a lists of matched unique identities | [
"Merge",
"a",
"lists",
"of",
"matched",
"unique",
"identities"
] | 391cd37a75fea26311dc6908bc1c953c540a8e04 | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/cmd/unify.py#L186-L206 |
27,059 | chaoss/grimoirelab-sortinghat | sortinghat/cmd/unify.py | Unify.__display_stats | def __display_stats(self):
"""Display some stats regarding unify process"""
self.display('unify.tmpl', processed=self.total,
matched=self.matched,
unified=self.total - self.matched) | python | def __display_stats(self):
self.display('unify.tmpl', processed=self.total,
matched=self.matched,
unified=self.total - self.matched) | [
"def",
"__display_stats",
"(",
"self",
")",
":",
"self",
".",
"display",
"(",
"'unify.tmpl'",
",",
"processed",
"=",
"self",
".",
"total",
",",
"matched",
"=",
"self",
".",
"matched",
",",
"unified",
"=",
"self",
".",
"total",
"-",
"self",
".",
"matche... | Display some stats regarding unify process | [
"Display",
"some",
"stats",
"regarding",
"unify",
"process"
] | 391cd37a75fea26311dc6908bc1c953c540a8e04 | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/cmd/unify.py#L240-L245 |
27,060 | chaoss/grimoirelab-sortinghat | sortinghat/cmd/unify.py | Unify.__marshal_matches | def __marshal_matches(matched):
"""Convert matches to JSON format.
:param matched: a list of matched identities
:returns json_matches: a list of matches in JSON format
"""
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 | python | 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 | [
"def",
"__marshal_matches",
"(",
"matched",
")",
":",
"json_matches",
"=",
"[",
"]",
"for",
"m",
"in",
"matched",
":",
"identities",
"=",
"[",
"i",
".",
"uuid",
"for",
"i",
"in",
"m",
"]",
"if",
"len",
"(",
"identities",
")",
"==",
"1",
":",
"conti... | Convert matches to JSON format.
:param matched: a list of matched identities
:returns json_matches: a list of matches in JSON format | [
"Convert",
"matches",
"to",
"JSON",
"format",
"."
] | 391cd37a75fea26311dc6908bc1c953c540a8e04 | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/cmd/unify.py#L248-L268 |
27,061 | chaoss/grimoirelab-sortinghat | sortinghat/cmd/unify.py | RecoveryFile.load_matches | def load_matches(self):
"""Load matches of the previous failed execution from the recovery file.
:returns matches: a list of matches in JSON format
"""
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 | python | 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 | [
"def",
"load_matches",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"exists",
"(",
")",
":",
"return",
"[",
"]",
"matches",
"=",
"[",
"]",
"with",
"open",
"(",
"self",
".",
"location",
"(",
")",
",",
"'r'",
")",
"as",
"f",
":",
"for",
"line... | Load matches of the previous failed execution from the recovery file.
:returns matches: a list of matches in JSON format | [
"Load",
"matches",
"of",
"the",
"previous",
"failed",
"execution",
"from",
"the",
"recovery",
"file",
"."
] | 391cd37a75fea26311dc6908bc1c953c540a8e04 | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/cmd/unify.py#L296-L313 |
27,062 | chaoss/grimoirelab-sortinghat | sortinghat/cmd/unify.py | RecoveryFile.save_matches | def save_matches(self, matches):
"""Save matches of a failed execution to the log.
:param matches: a list of matches in JSON format
"""
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") | python | 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") | [
"def",
"save_matches",
"(",
"self",
",",
"matches",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"self",
".",
"location",
"(",
")",
")",
")",
":",
"os",
".",
"makedirs",
"(",
"os",
".",
"... | Save matches of a failed execution to the log.
:param matches: a list of matches in JSON format | [
"Save",
"matches",
"of",
"a",
"failed",
"execution",
"to",
"the",
"log",
"."
] | 391cd37a75fea26311dc6908bc1c953c540a8e04 | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/cmd/unify.py#L315-L327 |
27,063 | chaoss/grimoirelab-sortinghat | sortinghat/cmd/unify.py | RecoveryFile.__uuid | def __uuid(*args):
"""Generate a UUID based on the given parameters."""
s = '-'.join(args)
sha1 = hashlib.sha1(s.encode('utf-8', errors='surrogateescape'))
uuid_sha1 = sha1.hexdigest()
return uuid_sha1 | python | def __uuid(*args):
s = '-'.join(args)
sha1 = hashlib.sha1(s.encode('utf-8', errors='surrogateescape'))
uuid_sha1 = sha1.hexdigest()
return uuid_sha1 | [
"def",
"__uuid",
"(",
"*",
"args",
")",
":",
"s",
"=",
"'-'",
".",
"join",
"(",
"args",
")",
"sha1",
"=",
"hashlib",
".",
"sha1",
"(",
"s",
".",
"encode",
"(",
"'utf-8'",
",",
"errors",
"=",
"'surrogateescape'",
")",
")",
"uuid_sha1",
"=",
"sha1",
... | Generate a UUID based on the given parameters. | [
"Generate",
"a",
"UUID",
"based",
"on",
"the",
"given",
"parameters",
"."
] | 391cd37a75fea26311dc6908bc1c953c540a8e04 | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/cmd/unify.py#L336-L344 |
27,064 | chaoss/grimoirelab-sortinghat | sortinghat/parsing/grimoirelab.py | GrimoireLabParser.__parse | def __parse(self, identities_stream, organizations_stream):
"""Parse GrimoireLab stream"""
if organizations_stream:
self.__parse_organizations(organizations_stream)
if identities_stream:
self.__parse_identities(identities_stream) | python | def __parse(self, identities_stream, organizations_stream):
if organizations_stream:
self.__parse_organizations(organizations_stream)
if identities_stream:
self.__parse_identities(identities_stream) | [
"def",
"__parse",
"(",
"self",
",",
"identities_stream",
",",
"organizations_stream",
")",
":",
"if",
"organizations_stream",
":",
"self",
".",
"__parse_organizations",
"(",
"organizations_stream",
")",
"if",
"identities_stream",
":",
"self",
".",
"__parse_identities"... | Parse GrimoireLab stream | [
"Parse",
"GrimoireLab",
"stream"
] | 391cd37a75fea26311dc6908bc1c953c540a8e04 | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/parsing/grimoirelab.py#L92-L99 |
27,065 | chaoss/grimoirelab-sortinghat | sortinghat/parsing/grimoirelab.py | GrimoireLabParser.__parse_identities | def __parse_identities(self, stream):
"""Parse identities using GrimoireLab format.
The GrimoireLab identities format is a YAML document following a
schema similar to the example below. More information available
at https://github.com/bitergia/identities
- profile:
name: Vivek K.
is_bot: false
github:
- vsekhark
email:
- vivek@****.com
enrollments:
- organization: Community
start: 1900-01-01
end: 2100-01-01
:parse json: YAML object to parse
:raise InvalidFormatError: raised when the format of the YAML is
not valid.
"""
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) | python | 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) | [
"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",
"=",
"[",
"]",
"i... | Parse identities using GrimoireLab format.
The GrimoireLab identities format is a YAML document following a
schema similar to the example below. More information available
at https://github.com/bitergia/identities
- profile:
name: Vivek K.
is_bot: false
github:
- vsekhark
email:
- vivek@****.com
enrollments:
- organization: Community
start: 1900-01-01
end: 2100-01-01
:parse json: YAML object to parse
:raise InvalidFormatError: raised when the format of the YAML is
not valid. | [
"Parse",
"identities",
"using",
"GrimoireLab",
"format",
"."
] | 391cd37a75fea26311dc6908bc1c953c540a8e04 | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/parsing/grimoirelab.py#L101-L187 |
27,066 | chaoss/grimoirelab-sortinghat | sortinghat/parsing/grimoirelab.py | GrimoireLabParser.__parse_organizations | def __parse_organizations(self, stream):
"""Parse GrimoireLab organizations.
The GrimoireLab organizations format is a YAML element stored
under the "organizations" key. The next example shows the
structure of the document:
- organizations:
Bitergia:
- bitergia.com
- support.bitergia.com
- biterg.io
LibreSoft:
- libresoft.es
:param json: YAML object to parse
:raises InvalidFormatError: raised when the format of the YAML is
not valid.
"""
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) | python | 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) | [
"def",
"__parse_organizations",
"(",
"self",
",",
"stream",
")",
":",
"if",
"not",
"stream",
":",
"return",
"yaml_file",
"=",
"self",
".",
"__load_yml",
"(",
"stream",
")",
"try",
":",
"for",
"element",
"in",
"yaml_file",
":",
"name",
"=",
"self",
".",
... | Parse GrimoireLab organizations.
The GrimoireLab organizations format is a YAML element stored
under the "organizations" key. The next example shows the
structure of the document:
- organizations:
Bitergia:
- bitergia.com
- support.bitergia.com
- biterg.io
LibreSoft:
- libresoft.es
:param json: YAML object to parse
:raises InvalidFormatError: raised when the format of the YAML is
not valid. | [
"Parse",
"GrimoireLab",
"organizations",
"."
] | 391cd37a75fea26311dc6908bc1c953c540a8e04 | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/parsing/grimoirelab.py#L189-L247 |
27,067 | chaoss/grimoirelab-sortinghat | sortinghat/parsing/grimoirelab.py | GrimoireLabParser.__parse_affiliations_yml | def __parse_affiliations_yml(self, affiliations):
"""Parse identity's affiliations from a yaml dict."""
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 | python | 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 | [
"def",
"__parse_affiliations_yml",
"(",
"self",
",",
"affiliations",
")",
":",
"enrollments",
"=",
"[",
"]",
"for",
"aff",
"in",
"affiliations",
":",
"name",
"=",
"self",
".",
"__encode",
"(",
"aff",
"[",
"'organization'",
"]",
")",
"if",
"not",
"name",
... | Parse identity's affiliations from a yaml dict. | [
"Parse",
"identity",
"s",
"affiliations",
"from",
"a",
"yaml",
"dict",
"."
] | 391cd37a75fea26311dc6908bc1c953c540a8e04 | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/parsing/grimoirelab.py#L249-L285 |
27,068 | chaoss/grimoirelab-sortinghat | sortinghat/parsing/grimoirelab.py | GrimoireLabParser.__force_datetime | def __force_datetime(self, obj):
"""Converts ojb to time.datetime.datetime
YAML parsing returns either date or datetime object depending
on how the date is written. YYYY-MM-DD will return a date and
YYYY-MM-DDThh:mm:ss will return a datetime
:param obj: date or datetime object
"""
if isinstance(obj, datetime.datetime):
return obj
t = datetime.time(0, 0)
return datetime.datetime.combine(obj, t) | python | def __force_datetime(self, obj):
if isinstance(obj, datetime.datetime):
return obj
t = datetime.time(0, 0)
return datetime.datetime.combine(obj, t) | [
"def",
"__force_datetime",
"(",
"self",
",",
"obj",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"datetime",
".",
"datetime",
")",
":",
"return",
"obj",
"t",
"=",
"datetime",
".",
"time",
"(",
"0",
",",
"0",
")",
"return",
"datetime",
".",
"datetim... | Converts ojb to time.datetime.datetime
YAML parsing returns either date or datetime object depending
on how the date is written. YYYY-MM-DD will return a date and
YYYY-MM-DDThh:mm:ss will return a datetime
:param obj: date or datetime object | [
"Converts",
"ojb",
"to",
"time",
".",
"datetime",
".",
"datetime"
] | 391cd37a75fea26311dc6908bc1c953c540a8e04 | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/parsing/grimoirelab.py#L287-L300 |
27,069 | chaoss/grimoirelab-sortinghat | sortinghat/parsing/grimoirelab.py | GrimoireLabParser.__load_yml | def __load_yml(self, stream):
"""Load yml stream into a dict object """
try:
return yaml.load(stream, Loader=yaml.SafeLoader)
except ValueError as e:
cause = "invalid yml format. %s" % str(e)
raise InvalidFormatError(cause=cause) | python | 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) | [
"def",
"__load_yml",
"(",
"self",
",",
"stream",
")",
":",
"try",
":",
"return",
"yaml",
".",
"load",
"(",
"stream",
",",
"Loader",
"=",
"yaml",
".",
"SafeLoader",
")",
"except",
"ValueError",
"as",
"e",
":",
"cause",
"=",
"\"invalid yml format. %s\"",
"... | Load yml stream into a dict object | [
"Load",
"yml",
"stream",
"into",
"a",
"dict",
"object"
] | 391cd37a75fea26311dc6908bc1c953c540a8e04 | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/parsing/grimoirelab.py#L302-L309 |
27,070 | chaoss/grimoirelab-sortinghat | sortinghat/parsing/grimoirelab.py | GrimoireLabParser.__validate_email | def __validate_email(self, email):
"""Checks if a string looks like an email address"""
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) | python | 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) | [
"def",
"__validate_email",
"(",
"self",
",",
"email",
")",
":",
"e",
"=",
"re",
".",
"match",
"(",
"self",
".",
"EMAIL_ADDRESS_REGEX",
",",
"email",
",",
"re",
".",
"UNICODE",
")",
"if",
"e",
":",
"return",
"email",
"else",
":",
"error",
"=",
"\"Inva... | Checks if a string looks like an email address | [
"Checks",
"if",
"a",
"string",
"looks",
"like",
"an",
"email",
"address"
] | 391cd37a75fea26311dc6908bc1c953c540a8e04 | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/parsing/grimoirelab.py#L314-L323 |
27,071 | chaoss/grimoirelab-sortinghat | sortinghat/parsing/grimoirelab.py | GrimoireLabParser.__validate_enrollment_periods | def __validate_enrollment_periods(self, enrollments):
"""Check for overlapped periods in the enrollments"""
for a, b in itertools.combinations(enrollments, 2):
max_start = max(a.start, b.start)
min_end = min(a.end, b.end)
if max_start < min_end:
msg = "invalid GrimoireLab enrollment dates. " \
"Organization dates overlap."
raise InvalidFormatError(cause=msg)
return enrollments | python | def __validate_enrollment_periods(self, enrollments):
for a, b in itertools.combinations(enrollments, 2):
max_start = max(a.start, b.start)
min_end = min(a.end, b.end)
if max_start < min_end:
msg = "invalid GrimoireLab enrollment dates. " \
"Organization dates overlap."
raise InvalidFormatError(cause=msg)
return enrollments | [
"def",
"__validate_enrollment_periods",
"(",
"self",
",",
"enrollments",
")",
":",
"for",
"a",
",",
"b",
"in",
"itertools",
".",
"combinations",
"(",
"enrollments",
",",
"2",
")",
":",
"max_start",
"=",
"max",
"(",
"a",
".",
"start",
",",
"b",
".",
"st... | Check for overlapped periods in the enrollments | [
"Check",
"for",
"overlapped",
"periods",
"in",
"the",
"enrollments"
] | 391cd37a75fea26311dc6908bc1c953c540a8e04 | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/parsing/grimoirelab.py#L325-L338 |
27,072 | chaoss/grimoirelab-sortinghat | sortinghat/parsing/sh.py | SortingHatParser.__parse | def __parse(self, stream):
"""Parse Sorting Hat stream"""
if not stream:
raise InvalidFormatError(cause="stream cannot be empty or None")
json = self.__load_json(stream)
self.__parse_organizations(json)
self.__parse_identities(json)
self.__parse_blacklist(json) | python | def __parse(self, stream):
if not stream:
raise InvalidFormatError(cause="stream cannot be empty or None")
json = self.__load_json(stream)
self.__parse_organizations(json)
self.__parse_identities(json)
self.__parse_blacklist(json) | [
"def",
"__parse",
"(",
"self",
",",
"stream",
")",
":",
"if",
"not",
"stream",
":",
"raise",
"InvalidFormatError",
"(",
"cause",
"=",
"\"stream cannot be empty or None\"",
")",
"json",
"=",
"self",
".",
"__load_json",
"(",
"stream",
")",
"self",
".",
"__pars... | Parse Sorting Hat stream | [
"Parse",
"Sorting",
"Hat",
"stream"
] | 391cd37a75fea26311dc6908bc1c953c540a8e04 | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/parsing/sh.py#L76-L86 |
27,073 | chaoss/grimoirelab-sortinghat | sortinghat/parsing/sh.py | SortingHatParser.__parse_blacklist | def __parse_blacklist(self, json):
"""Parse blacklist entries using Sorting Hat format.
The Sorting Hat blacklist format is a JSON stream that
stores a list of blacklisted entries.
Next, there is an example of a valid stream:
{
"blacklist": [
"John Doe",
"John Smith",
"root@example.com"
]
}
:param stream: stream to parse
:raises InvalidFormatError: raised when the format of the stream is
not valid.
"""
try:
for entry in json['blacklist']:
if not entry:
msg = "invalid json format. Blacklist entries cannot be null or empty"
raise InvalidFormatError(cause=msg)
excluded = self.__encode(entry)
bl = self._blacklist.get(excluded, None)
if not bl:
bl = MatchingBlacklist(excluded=excluded)
self._blacklist[excluded] = bl
except KeyError as e:
msg = "invalid json format. Attribute %s not found" % e.args
raise InvalidFormatError(cause=msg) | python | def __parse_blacklist(self, json):
try:
for entry in json['blacklist']:
if not entry:
msg = "invalid json format. Blacklist entries cannot be null or empty"
raise InvalidFormatError(cause=msg)
excluded = self.__encode(entry)
bl = self._blacklist.get(excluded, None)
if not bl:
bl = MatchingBlacklist(excluded=excluded)
self._blacklist[excluded] = bl
except KeyError as e:
msg = "invalid json format. Attribute %s not found" % e.args
raise InvalidFormatError(cause=msg) | [
"def",
"__parse_blacklist",
"(",
"self",
",",
"json",
")",
":",
"try",
":",
"for",
"entry",
"in",
"json",
"[",
"'blacklist'",
"]",
":",
"if",
"not",
"entry",
":",
"msg",
"=",
"\"invalid json format. Blacklist entries cannot be null or empty\"",
"raise",
"InvalidFo... | Parse blacklist entries using Sorting Hat format.
The Sorting Hat blacklist format is a JSON stream that
stores a list of blacklisted entries.
Next, there is an example of a valid stream:
{
"blacklist": [
"John Doe",
"John Smith",
"root@example.com"
]
}
:param stream: stream to parse
:raises InvalidFormatError: raised when the format of the stream is
not valid. | [
"Parse",
"blacklist",
"entries",
"using",
"Sorting",
"Hat",
"format",
"."
] | 391cd37a75fea26311dc6908bc1c953c540a8e04 | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/parsing/sh.py#L88-L124 |
27,074 | chaoss/grimoirelab-sortinghat | sortinghat/parsing/sh.py | SortingHatParser.__parse_organizations | def __parse_organizations(self, json):
"""Parse organizations using Sorting Hat format.
The Sorting Hat organizations format is a JSON stream which
its keys are the name of the organizations. Each organization
object has a list of domains. For instance:
{
"organizations": {
"Bitergia": [
{
"domain": "api.bitergia.com",
"is_top": false
},
{
"domain": "bitergia.com",
"is_top": true
}
],
"Example": []
},
"time": "2015-01-20 20:10:56.133378"
}
:param json: stream to parse
:raises InvalidFormatError: raised when the format of the stream is
not valid.
"""
try:
for organization in json['organizations']:
name = self.__encode(organization)
org = self._organizations.get(name, None)
if not org:
org = Organization(name=name)
self._organizations[name] = org
domains = json['organizations'][organization]
for domain in domains:
if type(domain['is_top']) != bool:
msg = "invalid json format. 'is_top' must have a bool value"
raise InvalidFormatError(cause=msg)
dom = Domain(domain=domain['domain'],
is_top_domain=domain['is_top'])
org.domains.append(dom)
except KeyError as e:
msg = "invalid json format. Attribute %s not found" % e.args
raise InvalidFormatError(cause=msg) | python | def __parse_organizations(self, json):
try:
for organization in json['organizations']:
name = self.__encode(organization)
org = self._organizations.get(name, None)
if not org:
org = Organization(name=name)
self._organizations[name] = org
domains = json['organizations'][organization]
for domain in domains:
if type(domain['is_top']) != bool:
msg = "invalid json format. 'is_top' must have a bool value"
raise InvalidFormatError(cause=msg)
dom = Domain(domain=domain['domain'],
is_top_domain=domain['is_top'])
org.domains.append(dom)
except KeyError as e:
msg = "invalid json format. Attribute %s not found" % e.args
raise InvalidFormatError(cause=msg) | [
"def",
"__parse_organizations",
"(",
"self",
",",
"json",
")",
":",
"try",
":",
"for",
"organization",
"in",
"json",
"[",
"'organizations'",
"]",
":",
"name",
"=",
"self",
".",
"__encode",
"(",
"organization",
")",
"org",
"=",
"self",
".",
"_organizations"... | Parse organizations using Sorting Hat format.
The Sorting Hat organizations format is a JSON stream which
its keys are the name of the organizations. Each organization
object has a list of domains. For instance:
{
"organizations": {
"Bitergia": [
{
"domain": "api.bitergia.com",
"is_top": false
},
{
"domain": "bitergia.com",
"is_top": true
}
],
"Example": []
},
"time": "2015-01-20 20:10:56.133378"
}
:param json: stream to parse
:raises InvalidFormatError: raised when the format of the stream is
not valid. | [
"Parse",
"organizations",
"using",
"Sorting",
"Hat",
"format",
"."
] | 391cd37a75fea26311dc6908bc1c953c540a8e04 | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/parsing/sh.py#L282-L333 |
27,075 | chaoss/grimoirelab-sortinghat | sortinghat/cmd/load.py | Load.run | def run(self, *args):
"""Import data on the registry.
By default, it reads the data from the standard input. If a positional
argument is given, it will read the data from there.
"""
params = self.parser.parse_args(args)
with params.infile as infile:
try:
stream = self.__read_file(infile)
parser = SortingHatParser(stream)
except InvalidFormatError as e:
self.error(str(e))
return e.code
except (IOError, TypeError, AttributeError) as e:
raise RuntimeError(str(e))
if params.identities:
self.import_blacklist(parser)
code = self.import_identities(parser,
matching=params.matching,
match_new=params.match_new,
no_strict_matching=params.no_strict,
reset=params.reset,
verbose=params.verbose)
elif params.orgs:
self.import_organizations(parser, params.overwrite)
code = CMD_SUCCESS
else:
self.import_organizations(parser, params.overwrite)
self.import_blacklist(parser)
code = self.import_identities(parser, matching=params.matching,
match_new=params.match_new,
no_strict_matching=params.no_strict,
reset=params.reset,
verbose=params.verbose)
return code | python | def run(self, *args):
params = self.parser.parse_args(args)
with params.infile as infile:
try:
stream = self.__read_file(infile)
parser = SortingHatParser(stream)
except InvalidFormatError as e:
self.error(str(e))
return e.code
except (IOError, TypeError, AttributeError) as e:
raise RuntimeError(str(e))
if params.identities:
self.import_blacklist(parser)
code = self.import_identities(parser,
matching=params.matching,
match_new=params.match_new,
no_strict_matching=params.no_strict,
reset=params.reset,
verbose=params.verbose)
elif params.orgs:
self.import_organizations(parser, params.overwrite)
code = CMD_SUCCESS
else:
self.import_organizations(parser, params.overwrite)
self.import_blacklist(parser)
code = self.import_identities(parser, matching=params.matching,
match_new=params.match_new,
no_strict_matching=params.no_strict,
reset=params.reset,
verbose=params.verbose)
return code | [
"def",
"run",
"(",
"self",
",",
"*",
"args",
")",
":",
"params",
"=",
"self",
".",
"parser",
".",
"parse_args",
"(",
"args",
")",
"with",
"params",
".",
"infile",
"as",
"infile",
":",
"try",
":",
"stream",
"=",
"self",
".",
"__read_file",
"(",
"inf... | Import data on the registry.
By default, it reads the data from the standard input. If a positional
argument is given, it will read the data from there. | [
"Import",
"data",
"on",
"the",
"registry",
"."
] | 391cd37a75fea26311dc6908bc1c953c540a8e04 | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/cmd/load.py#L129-L167 |
27,076 | chaoss/grimoirelab-sortinghat | sortinghat/cmd/load.py | Load.import_blacklist | def import_blacklist(self, parser):
"""Import blacklist.
New entries parsed by 'parser' will be added to the blacklist.
:param parser: sorting hat parser
"""
blacklist = parser.blacklist
self.log("Loading blacklist...")
n = 0
for entry in blacklist:
try:
api.add_to_matching_blacklist(self.db, entry.excluded)
self.display('load_blacklist.tmpl', entry=entry.excluded)
n += 1
except ValueError as e:
raise RuntimeError(str(e))
except AlreadyExistsError as e:
msg = "%s. Not added." % str(e)
self.warning(msg)
self.log("%d/%d blacklist entries loaded" % (n, len(blacklist))) | python | def import_blacklist(self, parser):
blacklist = parser.blacklist
self.log("Loading blacklist...")
n = 0
for entry in blacklist:
try:
api.add_to_matching_blacklist(self.db, entry.excluded)
self.display('load_blacklist.tmpl', entry=entry.excluded)
n += 1
except ValueError as e:
raise RuntimeError(str(e))
except AlreadyExistsError as e:
msg = "%s. Not added." % str(e)
self.warning(msg)
self.log("%d/%d blacklist entries loaded" % (n, len(blacklist))) | [
"def",
"import_blacklist",
"(",
"self",
",",
"parser",
")",
":",
"blacklist",
"=",
"parser",
".",
"blacklist",
"self",
".",
"log",
"(",
"\"Loading blacklist...\"",
")",
"n",
"=",
"0",
"for",
"entry",
"in",
"blacklist",
":",
"try",
":",
"api",
".",
"add_t... | Import blacklist.
New entries parsed by 'parser' will be added to the blacklist.
:param parser: sorting hat parser | [
"Import",
"blacklist",
"."
] | 391cd37a75fea26311dc6908bc1c953c540a8e04 | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/cmd/load.py#L169-L192 |
27,077 | chaoss/grimoirelab-sortinghat | sortinghat/cmd/load.py | Load.import_organizations | def import_organizations(self, parser, overwrite=False):
"""Import organizations.
New domains and organizations parsed by 'parser' will be added
to the registry. Remember that a domain can only be assigned to
one organization. If one of the given domains is already on the registry,
the new relationship will NOT be created unless 'overwrite' were set
to 'True'.
:param parser: sorting hat parser
:param overwrite: force to reassign domains
"""
orgs = parser.organizations
for org in orgs:
try:
api.add_organization(self.db, org.name)
except ValueError as e:
raise RuntimeError(str(e))
except AlreadyExistsError as e:
pass
for dom in org.domains:
try:
api.add_domain(self.db, org.name, dom.domain,
is_top_domain=dom.is_top_domain,
overwrite=overwrite)
self.display('load_domains.tmpl', domain=dom.domain,
organization=org.name)
except (ValueError, NotFoundError) as e:
raise RuntimeError(str(e))
except AlreadyExistsError as e:
msg = "%s. Not updated." % str(e)
self.warning(msg) | python | def import_organizations(self, parser, overwrite=False):
orgs = parser.organizations
for org in orgs:
try:
api.add_organization(self.db, org.name)
except ValueError as e:
raise RuntimeError(str(e))
except AlreadyExistsError as e:
pass
for dom in org.domains:
try:
api.add_domain(self.db, org.name, dom.domain,
is_top_domain=dom.is_top_domain,
overwrite=overwrite)
self.display('load_domains.tmpl', domain=dom.domain,
organization=org.name)
except (ValueError, NotFoundError) as e:
raise RuntimeError(str(e))
except AlreadyExistsError as e:
msg = "%s. Not updated." % str(e)
self.warning(msg) | [
"def",
"import_organizations",
"(",
"self",
",",
"parser",
",",
"overwrite",
"=",
"False",
")",
":",
"orgs",
"=",
"parser",
".",
"organizations",
"for",
"org",
"in",
"orgs",
":",
"try",
":",
"api",
".",
"add_organization",
"(",
"self",
".",
"db",
",",
... | Import organizations.
New domains and organizations parsed by 'parser' will be added
to the registry. Remember that a domain can only be assigned to
one organization. If one of the given domains is already on the registry,
the new relationship will NOT be created unless 'overwrite' were set
to 'True'.
:param parser: sorting hat parser
:param overwrite: force to reassign domains | [
"Import",
"organizations",
"."
] | 391cd37a75fea26311dc6908bc1c953c540a8e04 | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/cmd/load.py#L194-L227 |
27,078 | chaoss/grimoirelab-sortinghat | sortinghat/cmd/load.py | Load.import_identities | def import_identities(self, parser, matching=None, match_new=False,
no_strict_matching=False,
reset=False, verbose=False):
"""Import identities information on the registry.
New unique identities, organizations and enrollment data parsed
by 'parser' will be added to the registry.
Optionally, this method can look for possible identities that match with
the new one to insert using 'matching' method. If a match is found,
that means both identities are likely the same. Therefore, both identities
would be merged into one. The 'match_new' parameter can be set to match
and merge only new loaded identities. Rigorous validation of mathching
values (i.e, well formed email addresses) will be disabled when
<no_strict_matching> is set to to `True`.
When `reset` is set, relationships and enrollments will be removed
before loading any data.
:param parser: sorting hat parser
:param matching: type of matching used to merge existing identities
:param match_new: match and merge only the new loaded identities
:param no_strict_matching: disable strict matching (i.e, well-formed email addresses)
:param reset: remove relationships and enrollments before loading data
:param verbose: run in verbose mode when matching is set
"""
matcher = None
if matching:
strict = not no_strict_matching
try:
blacklist = api.blacklist(self.db)
matcher = create_identity_matcher(matching, blacklist, strict=strict)
except MatcherNotSupportedError as e:
self.error(str(e))
return e.code
uidentities = parser.identities
try:
self.__load_unique_identities(uidentities, matcher, match_new,
reset, verbose)
except LoadError as e:
self.error(str(e))
return e.code
return CMD_SUCCESS | python | def import_identities(self, parser, matching=None, match_new=False,
no_strict_matching=False,
reset=False, verbose=False):
matcher = None
if matching:
strict = not no_strict_matching
try:
blacklist = api.blacklist(self.db)
matcher = create_identity_matcher(matching, blacklist, strict=strict)
except MatcherNotSupportedError as e:
self.error(str(e))
return e.code
uidentities = parser.identities
try:
self.__load_unique_identities(uidentities, matcher, match_new,
reset, verbose)
except LoadError as e:
self.error(str(e))
return e.code
return CMD_SUCCESS | [
"def",
"import_identities",
"(",
"self",
",",
"parser",
",",
"matching",
"=",
"None",
",",
"match_new",
"=",
"False",
",",
"no_strict_matching",
"=",
"False",
",",
"reset",
"=",
"False",
",",
"verbose",
"=",
"False",
")",
":",
"matcher",
"=",
"None",
"if... | Import identities information on the registry.
New unique identities, organizations and enrollment data parsed
by 'parser' will be added to the registry.
Optionally, this method can look for possible identities that match with
the new one to insert using 'matching' method. If a match is found,
that means both identities are likely the same. Therefore, both identities
would be merged into one. The 'match_new' parameter can be set to match
and merge only new loaded identities. Rigorous validation of mathching
values (i.e, well formed email addresses) will be disabled when
<no_strict_matching> is set to to `True`.
When `reset` is set, relationships and enrollments will be removed
before loading any data.
:param parser: sorting hat parser
:param matching: type of matching used to merge existing identities
:param match_new: match and merge only the new loaded identities
:param no_strict_matching: disable strict matching (i.e, well-formed email addresses)
:param reset: remove relationships and enrollments before loading data
:param verbose: run in verbose mode when matching is set | [
"Import",
"identities",
"information",
"on",
"the",
"registry",
"."
] | 391cd37a75fea26311dc6908bc1c953c540a8e04 | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/cmd/load.py#L229-L276 |
27,079 | chaoss/grimoirelab-sortinghat | sortinghat/cmd/load.py | Load.__load_unique_identities | def __load_unique_identities(self, uidentities, matcher, match_new,
reset, verbose):
"""Load unique identities"""
self.new_uids.clear()
n = 0
if reset:
self.__reset_unique_identities()
self.log("Loading unique identities...")
for uidentity in uidentities:
self.log("\n=====", verbose)
self.log("+ Processing %s" % uidentity.uuid, verbose)
try:
stored_uuid = self.__load_unique_identity(uidentity, verbose)
except LoadError as e:
self.error("%s Skipping." % str(e))
self.log("=====", verbose)
continue
stored_uuid = self.__load_identities(uidentity.identities, stored_uuid,
verbose)
try:
self.__load_profile(uidentity.profile, stored_uuid, verbose)
except Exception as e:
self.error("%s. Loading %s profile. Skipping profile." %
(str(e), stored_uuid))
self.__load_enrollments(uidentity.enrollments, stored_uuid,
verbose)
if matcher and (not match_new or stored_uuid in self.new_uids):
stored_uuid = self._merge_on_matching(stored_uuid, matcher,
verbose)
self.log("+ %s (old %s) loaded" % (stored_uuid, uidentity.uuid),
verbose)
self.log("=====", verbose)
n += 1
self.log("%d/%d unique identities loaded" % (n, len(uidentities))) | python | def __load_unique_identities(self, uidentities, matcher, match_new,
reset, verbose):
self.new_uids.clear()
n = 0
if reset:
self.__reset_unique_identities()
self.log("Loading unique identities...")
for uidentity in uidentities:
self.log("\n=====", verbose)
self.log("+ Processing %s" % uidentity.uuid, verbose)
try:
stored_uuid = self.__load_unique_identity(uidentity, verbose)
except LoadError as e:
self.error("%s Skipping." % str(e))
self.log("=====", verbose)
continue
stored_uuid = self.__load_identities(uidentity.identities, stored_uuid,
verbose)
try:
self.__load_profile(uidentity.profile, stored_uuid, verbose)
except Exception as e:
self.error("%s. Loading %s profile. Skipping profile." %
(str(e), stored_uuid))
self.__load_enrollments(uidentity.enrollments, stored_uuid,
verbose)
if matcher and (not match_new or stored_uuid in self.new_uids):
stored_uuid = self._merge_on_matching(stored_uuid, matcher,
verbose)
self.log("+ %s (old %s) loaded" % (stored_uuid, uidentity.uuid),
verbose)
self.log("=====", verbose)
n += 1
self.log("%d/%d unique identities loaded" % (n, len(uidentities))) | [
"def",
"__load_unique_identities",
"(",
"self",
",",
"uidentities",
",",
"matcher",
",",
"match_new",
",",
"reset",
",",
"verbose",
")",
":",
"self",
".",
"new_uids",
".",
"clear",
"(",
")",
"n",
"=",
"0",
"if",
"reset",
":",
"self",
".",
"__reset_unique... | Load unique identities | [
"Load",
"unique",
"identities"
] | 391cd37a75fea26311dc6908bc1c953c540a8e04 | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/cmd/load.py#L278-L323 |
27,080 | chaoss/grimoirelab-sortinghat | sortinghat/cmd/load.py | Load.__reset_unique_identities | def __reset_unique_identities(self):
"""Clear identities relationships and enrollments data"""
self.log("Reseting unique identities...")
self.log("Clearing identities relationships")
nids = 0
uidentities = api.unique_identities(self.db)
for uidentity in uidentities:
for identity in uidentity.identities:
api.move_identity(self.db, identity.id, identity.id)
nids += 1
self.log("Relationships cleared for %s identities" % nids)
self.log("Clearing enrollments")
with self.db.connect() as session:
enrollments = session.query(Enrollment).all()
for enr in enrollments:
session.delete(enr)
self.log("Enrollments cleared") | python | def __reset_unique_identities(self):
self.log("Reseting unique identities...")
self.log("Clearing identities relationships")
nids = 0
uidentities = api.unique_identities(self.db)
for uidentity in uidentities:
for identity in uidentity.identities:
api.move_identity(self.db, identity.id, identity.id)
nids += 1
self.log("Relationships cleared for %s identities" % nids)
self.log("Clearing enrollments")
with self.db.connect() as session:
enrollments = session.query(Enrollment).all()
for enr in enrollments:
session.delete(enr)
self.log("Enrollments cleared") | [
"def",
"__reset_unique_identities",
"(",
"self",
")",
":",
"self",
".",
"log",
"(",
"\"Reseting unique identities...\"",
")",
"self",
".",
"log",
"(",
"\"Clearing identities relationships\"",
")",
"nids",
"=",
"0",
"uidentities",
"=",
"api",
".",
"unique_identities"... | Clear identities relationships and enrollments data | [
"Clear",
"identities",
"relationships",
"and",
"enrollments",
"data"
] | 391cd37a75fea26311dc6908bc1c953c540a8e04 | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/cmd/load.py#L325-L350 |
27,081 | chaoss/grimoirelab-sortinghat | sortinghat/cmd/load.py | Load.__load_unique_identity | def __load_unique_identity(self, uidentity, verbose):
"""Seek or store unique identity"""
uuid = uidentity.uuid
if uuid:
try:
api.unique_identities(self.db, uuid)
self.log("-- %s already exists." % uuid, verbose)
return uuid
except NotFoundError as e:
self.log("-- %s not found. Generating a new UUID." % uuid,
debug=verbose)
# We don't have a unique identity, so we have to create
# a new one.
if len(uidentity.identities) == 0:
msg = "not enough info to load %s unique identity." % uidentity.uuid
raise LoadError(cause=msg)
identity = uidentity.identities.pop(0)
try:
stored_uuid = api.add_identity(self.db, identity.source,
identity.email,
identity.name,
identity.username)
self.new_uids.add(stored_uuid)
except AlreadyExistsError as e:
with self.db.connect() as session:
stored_identity = find_identity(session, e.eid)
stored_uuid = stored_identity.uuid
self.warning("-- " + str(e), debug=verbose)
except ValueError as e:
raise LoadError(cause=str(e))
self.log("-- using %s for %s unique identity." % (stored_uuid, uuid), verbose)
return stored_uuid | python | def __load_unique_identity(self, uidentity, verbose):
uuid = uidentity.uuid
if uuid:
try:
api.unique_identities(self.db, uuid)
self.log("-- %s already exists." % uuid, verbose)
return uuid
except NotFoundError as e:
self.log("-- %s not found. Generating a new UUID." % uuid,
debug=verbose)
# We don't have a unique identity, so we have to create
# a new one.
if len(uidentity.identities) == 0:
msg = "not enough info to load %s unique identity." % uidentity.uuid
raise LoadError(cause=msg)
identity = uidentity.identities.pop(0)
try:
stored_uuid = api.add_identity(self.db, identity.source,
identity.email,
identity.name,
identity.username)
self.new_uids.add(stored_uuid)
except AlreadyExistsError as e:
with self.db.connect() as session:
stored_identity = find_identity(session, e.eid)
stored_uuid = stored_identity.uuid
self.warning("-- " + str(e), debug=verbose)
except ValueError as e:
raise LoadError(cause=str(e))
self.log("-- using %s for %s unique identity." % (stored_uuid, uuid), verbose)
return stored_uuid | [
"def",
"__load_unique_identity",
"(",
"self",
",",
"uidentity",
",",
"verbose",
")",
":",
"uuid",
"=",
"uidentity",
".",
"uuid",
"if",
"uuid",
":",
"try",
":",
"api",
".",
"unique_identities",
"(",
"self",
".",
"db",
",",
"uuid",
")",
"self",
".",
"log... | Seek or store unique identity | [
"Seek",
"or",
"store",
"unique",
"identity"
] | 391cd37a75fea26311dc6908bc1c953c540a8e04 | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/cmd/load.py#L352-L390 |
27,082 | chaoss/grimoirelab-sortinghat | sortinghat/cmd/load.py | Load.__load_profile | def __load_profile(self, profile, uuid, verbose):
"""Create a new profile when the unique identity does not have any."""
def is_empty_profile(prf):
return not (prf.name or prf.email or
prf.gender or prf.gender_acc or
prf.is_bot or prf.country_code)
uid = api.unique_identities(self.db, uuid)[0]
if profile:
self.__create_profile(profile, uuid, verbose)
elif is_empty_profile(uid.profile):
self.__create_profile_from_identities(uid.identities, uuid, verbose)
else:
self.log("-- empty profile given for %s. Not updated" % uuid, verbose) | python | def __load_profile(self, profile, uuid, verbose):
def is_empty_profile(prf):
return not (prf.name or prf.email or
prf.gender or prf.gender_acc or
prf.is_bot or prf.country_code)
uid = api.unique_identities(self.db, uuid)[0]
if profile:
self.__create_profile(profile, uuid, verbose)
elif is_empty_profile(uid.profile):
self.__create_profile_from_identities(uid.identities, uuid, verbose)
else:
self.log("-- empty profile given for %s. Not updated" % uuid, verbose) | [
"def",
"__load_profile",
"(",
"self",
",",
"profile",
",",
"uuid",
",",
"verbose",
")",
":",
"def",
"is_empty_profile",
"(",
"prf",
")",
":",
"return",
"not",
"(",
"prf",
".",
"name",
"or",
"prf",
".",
"email",
"or",
"prf",
".",
"gender",
"or",
"prf"... | Create a new profile when the unique identity does not have any. | [
"Create",
"a",
"new",
"profile",
"when",
"the",
"unique",
"identity",
"does",
"not",
"have",
"any",
"."
] | 391cd37a75fea26311dc6908bc1c953c540a8e04 | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/cmd/load.py#L425-L440 |
27,083 | chaoss/grimoirelab-sortinghat | sortinghat/cmd/load.py | Load.__create_profile | def __create_profile(self, profile, uuid, verbose):
"""Create profile information from a profile object"""
# Set parameters to edit
kw = profile.to_dict()
kw['country_code'] = profile.country_code
# Remove unused keywords
kw.pop('uuid')
kw.pop('country')
api.edit_profile(self.db, uuid, **kw)
self.log("-- profile %s updated" % uuid, verbose) | python | def __create_profile(self, profile, uuid, verbose):
# Set parameters to edit
kw = profile.to_dict()
kw['country_code'] = profile.country_code
# Remove unused keywords
kw.pop('uuid')
kw.pop('country')
api.edit_profile(self.db, uuid, **kw)
self.log("-- profile %s updated" % uuid, verbose) | [
"def",
"__create_profile",
"(",
"self",
",",
"profile",
",",
"uuid",
",",
"verbose",
")",
":",
"# Set parameters to edit",
"kw",
"=",
"profile",
".",
"to_dict",
"(",
")",
"kw",
"[",
"'country_code'",
"]",
"=",
"profile",
".",
"country_code",
"# Remove unused k... | Create profile information from a profile object | [
"Create",
"profile",
"information",
"from",
"a",
"profile",
"object"
] | 391cd37a75fea26311dc6908bc1c953c540a8e04 | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/cmd/load.py#L442-L455 |
27,084 | chaoss/grimoirelab-sortinghat | sortinghat/cmd/load.py | Load.__create_profile_from_identities | def __create_profile_from_identities(self, identities, uuid, verbose):
"""Create a profile using the data from the identities"""
import re
EMAIL_ADDRESS_REGEX = r"^(?P<email>[^\s@]+@[^\s@.]+\.[^\s@]+)$"
NAME_REGEX = r"^\w+\s\w+"
name = None
email = None
username = None
for identity in identities:
if not name and identity.name:
m = re.match(NAME_REGEX, identity.name)
if m:
name = identity.name
if not email and identity.email:
m = re.match(EMAIL_ADDRESS_REGEX, identity.email)
if m:
email = identity.email
if not username:
if identity.username and identity.username != 'None':
username = identity.username
# We need a name for each profile, so if no one was defined,
# use email or username to complete it.
if not name:
if email:
name = email.split('@')[0]
elif username:
# filter email addresses on username fields
name = username.split('@')[0]
else:
name = None
kw = {'name': name,
'email': email}
api.edit_profile(self.db, uuid, **kw)
self.log("-- profile %s updated" % uuid, verbose) | python | def __create_profile_from_identities(self, identities, uuid, verbose):
import re
EMAIL_ADDRESS_REGEX = r"^(?P<email>[^\s@]+@[^\s@.]+\.[^\s@]+)$"
NAME_REGEX = r"^\w+\s\w+"
name = None
email = None
username = None
for identity in identities:
if not name and identity.name:
m = re.match(NAME_REGEX, identity.name)
if m:
name = identity.name
if not email and identity.email:
m = re.match(EMAIL_ADDRESS_REGEX, identity.email)
if m:
email = identity.email
if not username:
if identity.username and identity.username != 'None':
username = identity.username
# We need a name for each profile, so if no one was defined,
# use email or username to complete it.
if not name:
if email:
name = email.split('@')[0]
elif username:
# filter email addresses on username fields
name = username.split('@')[0]
else:
name = None
kw = {'name': name,
'email': email}
api.edit_profile(self.db, uuid, **kw)
self.log("-- profile %s updated" % uuid, verbose) | [
"def",
"__create_profile_from_identities",
"(",
"self",
",",
"identities",
",",
"uuid",
",",
"verbose",
")",
":",
"import",
"re",
"EMAIL_ADDRESS_REGEX",
"=",
"r\"^(?P<email>[^\\s@]+@[^\\s@.]+\\.[^\\s@]+)$\"",
"NAME_REGEX",
"=",
"r\"^\\w+\\s\\w+\"",
"name",
"=",
"None",
... | Create a profile using the data from the identities | [
"Create",
"a",
"profile",
"using",
"the",
"data",
"from",
"the",
"identities"
] | 391cd37a75fea26311dc6908bc1c953c540a8e04 | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/cmd/load.py#L457-L502 |
27,085 | chaoss/grimoirelab-sortinghat | sortinghat/cmd/load.py | Load._merge_on_matching | def _merge_on_matching(self, uuid, matcher, verbose):
"""Merge unique identity with uuid when a match is found"""
matches = api.match_identities(self.db, uuid, matcher)
new_uuid = uuid
u = api.unique_identities(self.db, uuid)[0]
for m in matches:
if m.uuid == uuid:
continue
self._merge(u, m, verbose)
new_uuid = m.uuid
# Swap uids to merge with those that could
# remain on the list with updated info
u = api.unique_identities(self.db, m.uuid)[0]
return new_uuid | python | def _merge_on_matching(self, uuid, matcher, verbose):
matches = api.match_identities(self.db, uuid, matcher)
new_uuid = uuid
u = api.unique_identities(self.db, uuid)[0]
for m in matches:
if m.uuid == uuid:
continue
self._merge(u, m, verbose)
new_uuid = m.uuid
# Swap uids to merge with those that could
# remain on the list with updated info
u = api.unique_identities(self.db, m.uuid)[0]
return new_uuid | [
"def",
"_merge_on_matching",
"(",
"self",
",",
"uuid",
",",
"matcher",
",",
"verbose",
")",
":",
"matches",
"=",
"api",
".",
"match_identities",
"(",
"self",
".",
"db",
",",
"uuid",
",",
"matcher",
")",
"new_uuid",
"=",
"uuid",
"u",
"=",
"api",
".",
... | Merge unique identity with uuid when a match is found | [
"Merge",
"unique",
"identity",
"with",
"uuid",
"when",
"a",
"match",
"is",
"found"
] | 391cd37a75fea26311dc6908bc1c953c540a8e04 | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/cmd/load.py#L544-L565 |
27,086 | chaoss/grimoirelab-sortinghat | sortinghat/cmd/load.py | Load._merge | def _merge(self, from_uid, to_uid, verbose):
"""Merge unique identity uid on match"""
if verbose:
self.display('match.tmpl', uid=from_uid, match=to_uid)
api.merge_unique_identities(self.db, from_uid.uuid, to_uid.uuid)
if verbose:
self.display('merge.tmpl', from_uuid=from_uid.uuid, to_uuid=to_uid.uuid) | python | def _merge(self, from_uid, to_uid, verbose):
if verbose:
self.display('match.tmpl', uid=from_uid, match=to_uid)
api.merge_unique_identities(self.db, from_uid.uuid, to_uid.uuid)
if verbose:
self.display('merge.tmpl', from_uuid=from_uid.uuid, to_uuid=to_uid.uuid) | [
"def",
"_merge",
"(",
"self",
",",
"from_uid",
",",
"to_uid",
",",
"verbose",
")",
":",
"if",
"verbose",
":",
"self",
".",
"display",
"(",
"'match.tmpl'",
",",
"uid",
"=",
"from_uid",
",",
"match",
"=",
"to_uid",
")",
"api",
".",
"merge_unique_identities... | Merge unique identity uid on match | [
"Merge",
"unique",
"identity",
"uid",
"on",
"match"
] | 391cd37a75fea26311dc6908bc1c953c540a8e04 | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/cmd/load.py#L567-L576 |
27,087 | chaoss/grimoirelab-sortinghat | sortinghat/parsing/gitdm.py | GitdmParser.__parse | def __parse(self, aliases, email_to_employer, domain_to_employer):
"""Parse Gitdm streams"""
self.__parse_organizations(domain_to_employer)
self.__parse_identities(aliases, email_to_employer) | python | def __parse(self, aliases, email_to_employer, domain_to_employer):
self.__parse_organizations(domain_to_employer)
self.__parse_identities(aliases, email_to_employer) | [
"def",
"__parse",
"(",
"self",
",",
"aliases",
",",
"email_to_employer",
",",
"domain_to_employer",
")",
":",
"self",
".",
"__parse_organizations",
"(",
"domain_to_employer",
")",
"self",
".",
"__parse_identities",
"(",
"aliases",
",",
"email_to_employer",
")"
] | Parse Gitdm streams | [
"Parse",
"Gitdm",
"streams"
] | 391cd37a75fea26311dc6908bc1c953c540a8e04 | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/parsing/gitdm.py#L96-L100 |
27,088 | chaoss/grimoirelab-sortinghat | sortinghat/parsing/gitdm.py | GitdmParser.__parse_identities | def __parse_identities(self, aliases, email_to_employer):
"""Parse Gitdm identities"""
# Parse streams
self.__parse_aliases_stream(aliases)
self.__parse_email_to_employer_stream(email_to_employer)
# Create unique identities from aliases list
for alias, email in self.__raw_aliases.items():
uid = self._identities.get(email, None)
if not uid:
uid = UniqueIdentity(uuid=email)
e = re.match(self.EMAIL_ADDRESS_REGEX, email, re.UNICODE)
if e:
identity = Identity(email=email, source=self.source)
else:
identity = Identity(username=email, source=self.source)
uid.identities.append(identity)
self._identities[email] = uid
e = re.match(self.EMAIL_ADDRESS_REGEX, alias, re.UNICODE)
if e:
identity = Identity(email=alias, source=self.source)
else:
identity = Identity(username=alias, source=self.source)
uid.identities.append(identity)
# Create unique identities from enrollments list
for email in self.__raw_identities:
# Do we have it from aliases?
if email in self._identities:
uid = self._identities[email]
elif email in self.__raw_aliases:
canonical = self.__raw_aliases[email]
uid = self._identities[canonical]
else:
uid = UniqueIdentity(uuid=email)
identity = Identity(email=email, source=self.source)
uid.identities.append(identity)
self._identities[email] = uid
# Assign enrollments
enrs = self.__raw_identities[email]
enrs.sort(key=lambda r: r[1])
start_date = MIN_PERIOD_DATE
for rol in enrs:
name = rol[0]
org = self._organizations.get(name, None)
if not org:
org = Organization(name=name)
self._organizations[name] = org
end_date = rol[1]
enrollment = Enrollment(start=start_date, end=end_date,
organization=org)
uid.enrollments.append(enrollment)
if end_date != MAX_PERIOD_DATE:
start_date = end_date | python | def __parse_identities(self, aliases, email_to_employer):
# Parse streams
self.__parse_aliases_stream(aliases)
self.__parse_email_to_employer_stream(email_to_employer)
# Create unique identities from aliases list
for alias, email in self.__raw_aliases.items():
uid = self._identities.get(email, None)
if not uid:
uid = UniqueIdentity(uuid=email)
e = re.match(self.EMAIL_ADDRESS_REGEX, email, re.UNICODE)
if e:
identity = Identity(email=email, source=self.source)
else:
identity = Identity(username=email, source=self.source)
uid.identities.append(identity)
self._identities[email] = uid
e = re.match(self.EMAIL_ADDRESS_REGEX, alias, re.UNICODE)
if e:
identity = Identity(email=alias, source=self.source)
else:
identity = Identity(username=alias, source=self.source)
uid.identities.append(identity)
# Create unique identities from enrollments list
for email in self.__raw_identities:
# Do we have it from aliases?
if email in self._identities:
uid = self._identities[email]
elif email in self.__raw_aliases:
canonical = self.__raw_aliases[email]
uid = self._identities[canonical]
else:
uid = UniqueIdentity(uuid=email)
identity = Identity(email=email, source=self.source)
uid.identities.append(identity)
self._identities[email] = uid
# Assign enrollments
enrs = self.__raw_identities[email]
enrs.sort(key=lambda r: r[1])
start_date = MIN_PERIOD_DATE
for rol in enrs:
name = rol[0]
org = self._organizations.get(name, None)
if not org:
org = Organization(name=name)
self._organizations[name] = org
end_date = rol[1]
enrollment = Enrollment(start=start_date, end=end_date,
organization=org)
uid.enrollments.append(enrollment)
if end_date != MAX_PERIOD_DATE:
start_date = end_date | [
"def",
"__parse_identities",
"(",
"self",
",",
"aliases",
",",
"email_to_employer",
")",
":",
"# Parse streams",
"self",
".",
"__parse_aliases_stream",
"(",
"aliases",
")",
"self",
".",
"__parse_email_to_employer_stream",
"(",
"email_to_employer",
")",
"# Create unique ... | Parse Gitdm identities | [
"Parse",
"Gitdm",
"identities"
] | 391cd37a75fea26311dc6908bc1c953c540a8e04 | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/parsing/gitdm.py#L102-L172 |
27,089 | chaoss/grimoirelab-sortinghat | sortinghat/parsing/gitdm.py | GitdmParser.__parse_organizations | def __parse_organizations(self, domain_to_employer):
"""Parse Gitdm organizations"""
# Parse streams
self.__parse_domain_to_employer_stream(domain_to_employer)
for org in self.__raw_orgs:
o = Organization(name=org)
for dom in self.__raw_orgs[org]:
d = Domain(domain=dom, is_top_domain=False)
o.domains.append(d)
self._organizations[org] = o | python | def __parse_organizations(self, domain_to_employer):
# Parse streams
self.__parse_domain_to_employer_stream(domain_to_employer)
for org in self.__raw_orgs:
o = Organization(name=org)
for dom in self.__raw_orgs[org]:
d = Domain(domain=dom, is_top_domain=False)
o.domains.append(d)
self._organizations[org] = o | [
"def",
"__parse_organizations",
"(",
"self",
",",
"domain_to_employer",
")",
":",
"# Parse streams",
"self",
".",
"__parse_domain_to_employer_stream",
"(",
"domain_to_employer",
")",
"for",
"org",
"in",
"self",
".",
"__raw_orgs",
":",
"o",
"=",
"Organization",
"(",
... | Parse Gitdm organizations | [
"Parse",
"Gitdm",
"organizations"
] | 391cd37a75fea26311dc6908bc1c953c540a8e04 | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/parsing/gitdm.py#L174-L187 |
27,090 | chaoss/grimoirelab-sortinghat | sortinghat/parsing/gitdm.py | GitdmParser.__parse_aliases_stream | def __parse_aliases_stream(self, stream):
"""Parse aliases stream.
The stream contains a list of usernames (they can be email addresses
their username aliases. Each line has a username and an alias separated
by tabs. Comment lines start with the hash character (#).
Example:
# List of email aliases
jsmith@example.com jsmith@example.net
jsmith@example.net johnsmith@example.com
jdoe@example.com john_doe@example.com
jdoe@example john_doe@example.com
"""
if not stream:
return
f = self.__parse_aliases_line
for alias_entries in self.__parse_stream(stream, f):
alias = alias_entries[0]
username = alias_entries[1]
self.__raw_aliases[alias] = username | python | def __parse_aliases_stream(self, stream):
if not stream:
return
f = self.__parse_aliases_line
for alias_entries in self.__parse_stream(stream, f):
alias = alias_entries[0]
username = alias_entries[1]
self.__raw_aliases[alias] = username | [
"def",
"__parse_aliases_stream",
"(",
"self",
",",
"stream",
")",
":",
"if",
"not",
"stream",
":",
"return",
"f",
"=",
"self",
".",
"__parse_aliases_line",
"for",
"alias_entries",
"in",
"self",
".",
"__parse_stream",
"(",
"stream",
",",
"f",
")",
":",
"ali... | Parse aliases stream.
The stream contains a list of usernames (they can be email addresses
their username aliases. Each line has a username and an alias separated
by tabs. Comment lines start with the hash character (#).
Example:
# List of email aliases
jsmith@example.com jsmith@example.net
jsmith@example.net johnsmith@example.com
jdoe@example.com john_doe@example.com
jdoe@example john_doe@example.com | [
"Parse",
"aliases",
"stream",
"."
] | 391cd37a75fea26311dc6908bc1c953c540a8e04 | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/parsing/gitdm.py#L189-L213 |
27,091 | chaoss/grimoirelab-sortinghat | sortinghat/parsing/gitdm.py | GitdmParser.__parse_email_to_employer_stream | def __parse_email_to_employer_stream(self, stream):
"""Parse email to employer stream.
The stream contains a list of email addresses and their employers.
Each line has an email address and a organization name separated by
tabs. Optionally, the date when the identity withdrew from the
organization can be included followed by a '<' character. Comment
lines start with the hash character (#).
Example:
# List of enrollments
jsmith@example.com Example Company # John Smith
jdoe@example.com Example Company # John Doe
jsmith@example.com Bitergia < 2015-01-01 # John Smith - Bitergia
"""
if not stream:
return
f = self.__parse_email_to_employer_line
for rol in self.__parse_stream(stream, f):
email = rol[0]
org = rol[1]
rol_date = rol[2]
if org not in self.__raw_orgs:
self.__raw_orgs[org] = []
if email not in self.__raw_identities:
self.__raw_identities[email] = [(org, rol_date)]
else:
self.__raw_identities[email].append((org, rol_date)) | python | def __parse_email_to_employer_stream(self, stream):
if not stream:
return
f = self.__parse_email_to_employer_line
for rol in self.__parse_stream(stream, f):
email = rol[0]
org = rol[1]
rol_date = rol[2]
if org not in self.__raw_orgs:
self.__raw_orgs[org] = []
if email not in self.__raw_identities:
self.__raw_identities[email] = [(org, rol_date)]
else:
self.__raw_identities[email].append((org, rol_date)) | [
"def",
"__parse_email_to_employer_stream",
"(",
"self",
",",
"stream",
")",
":",
"if",
"not",
"stream",
":",
"return",
"f",
"=",
"self",
".",
"__parse_email_to_employer_line",
"for",
"rol",
"in",
"self",
".",
"__parse_stream",
"(",
"stream",
",",
"f",
")",
"... | Parse email to employer stream.
The stream contains a list of email addresses and their employers.
Each line has an email address and a organization name separated by
tabs. Optionally, the date when the identity withdrew from the
organization can be included followed by a '<' character. Comment
lines start with the hash character (#).
Example:
# List of enrollments
jsmith@example.com Example Company # John Smith
jdoe@example.com Example Company # John Doe
jsmith@example.com Bitergia < 2015-01-01 # John Smith - Bitergia | [
"Parse",
"email",
"to",
"employer",
"stream",
"."
] | 391cd37a75fea26311dc6908bc1c953c540a8e04 | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/parsing/gitdm.py#L215-L247 |
27,092 | chaoss/grimoirelab-sortinghat | sortinghat/parsing/gitdm.py | GitdmParser.__parse_domain_to_employer_stream | def __parse_domain_to_employer_stream(self, stream):
"""Parse domain to employer stream.
Each line of the stream has to contain a domain and a organization,
or employer, separated by tabs. Comment lines start with the hash
character (#)
Example:
# Domains from domains.txt
example.org Example
example.com Example
bitergia.com Bitergia
libresoft.es LibreSoft
example.org LibreSoft
"""
if not stream:
return
f = self.__parse_domain_to_employer_line
for o in self.__parse_stream(stream, f):
org = o[0]
dom = o[1]
if org not in self.__raw_orgs:
self.__raw_orgs[org] = []
self.__raw_orgs[org].append(dom) | python | def __parse_domain_to_employer_stream(self, stream):
if not stream:
return
f = self.__parse_domain_to_employer_line
for o in self.__parse_stream(stream, f):
org = o[0]
dom = o[1]
if org not in self.__raw_orgs:
self.__raw_orgs[org] = []
self.__raw_orgs[org].append(dom) | [
"def",
"__parse_domain_to_employer_stream",
"(",
"self",
",",
"stream",
")",
":",
"if",
"not",
"stream",
":",
"return",
"f",
"=",
"self",
".",
"__parse_domain_to_employer_line",
"for",
"o",
"in",
"self",
".",
"__parse_stream",
"(",
"stream",
",",
"f",
")",
"... | Parse domain to employer stream.
Each line of the stream has to contain a domain and a organization,
or employer, separated by tabs. Comment lines start with the hash
character (#)
Example:
# Domains from domains.txt
example.org Example
example.com Example
bitergia.com Bitergia
libresoft.es LibreSoft
example.org LibreSoft | [
"Parse",
"domain",
"to",
"employer",
"stream",
"."
] | 391cd37a75fea26311dc6908bc1c953c540a8e04 | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/parsing/gitdm.py#L249-L277 |
27,093 | chaoss/grimoirelab-sortinghat | sortinghat/parsing/gitdm.py | GitdmParser.__parse_stream | def __parse_stream(self, stream, parse_line):
"""Generic method to parse gitdm streams"""
if not stream:
raise InvalidFormatError(cause='stream cannot be empty or None')
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
m = re.match(self.VALID_LINE_REGEX, line, re.UNICODE)
if not m:
cause = "line %s: invalid format" % str(nline)
raise InvalidFormatError(cause=cause)
try:
result = parse_line(m.group(1), m.group(2))
yield result
except InvalidFormatError as e:
cause = "line %s: %s" % (str(nline), e)
raise InvalidFormatError(cause=cause) | python | def __parse_stream(self, stream, parse_line):
if not stream:
raise InvalidFormatError(cause='stream cannot be empty or None')
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
m = re.match(self.VALID_LINE_REGEX, line, re.UNICODE)
if not m:
cause = "line %s: invalid format" % str(nline)
raise InvalidFormatError(cause=cause)
try:
result = parse_line(m.group(1), m.group(2))
yield result
except InvalidFormatError as e:
cause = "line %s: %s" % (str(nline), e)
raise InvalidFormatError(cause=cause) | [
"def",
"__parse_stream",
"(",
"self",
",",
"stream",
",",
"parse_line",
")",
":",
"if",
"not",
"stream",
":",
"raise",
"InvalidFormatError",
"(",
"cause",
"=",
"'stream cannot be empty or None'",
")",
"nline",
"=",
"0",
"lines",
"=",
"stream",
".",
"split",
... | Generic method to parse gitdm streams | [
"Generic",
"method",
"to",
"parse",
"gitdm",
"streams"
] | 391cd37a75fea26311dc6908bc1c953c540a8e04 | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/parsing/gitdm.py#L279-L306 |
27,094 | chaoss/grimoirelab-sortinghat | sortinghat/parsing/gitdm.py | GitdmParser.__parse_aliases_line | def __parse_aliases_line(self, raw_alias, raw_username):
"""Parse aliases lines"""
alias = self.__encode(raw_alias)
username = self.__encode(raw_username)
return alias, username | python | def __parse_aliases_line(self, raw_alias, raw_username):
alias = self.__encode(raw_alias)
username = self.__encode(raw_username)
return alias, username | [
"def",
"__parse_aliases_line",
"(",
"self",
",",
"raw_alias",
",",
"raw_username",
")",
":",
"alias",
"=",
"self",
".",
"__encode",
"(",
"raw_alias",
")",
"username",
"=",
"self",
".",
"__encode",
"(",
"raw_username",
")",
"return",
"alias",
",",
"username"
... | Parse aliases lines | [
"Parse",
"aliases",
"lines"
] | 391cd37a75fea26311dc6908bc1c953c540a8e04 | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/parsing/gitdm.py#L308-L314 |
27,095 | chaoss/grimoirelab-sortinghat | sortinghat/parsing/gitdm.py | GitdmParser.__parse_email_to_employer_line | def __parse_email_to_employer_line(self, raw_email, raw_enrollment):
"""Parse email to employer lines"""
e = re.match(self.EMAIL_ADDRESS_REGEX, raw_email, re.UNICODE)
if not e and self.email_validation:
cause = "invalid email format: '%s'" % raw_email
raise InvalidFormatError(cause=cause)
if self.email_validation:
email = e.group('email').strip()
else:
email = raw_email
r = re.match(self.ENROLLMENT_REGEX, raw_enrollment, re.UNICODE)
if not r:
cause = "invalid enrollment format: '%s'" % raw_enrollment
raise InvalidFormatError(cause=cause)
org = r.group('organization').strip()
date = r.group('date')
if date:
try:
dt = dateutil.parser.parse(r.group('date'))
except Exception as e:
cause = "invalid date: '%s'" % date
else:
dt = MAX_PERIOD_DATE
email = self.__encode(email)
org = self.__encode(org)
return email, org, dt | python | def __parse_email_to_employer_line(self, raw_email, raw_enrollment):
e = re.match(self.EMAIL_ADDRESS_REGEX, raw_email, re.UNICODE)
if not e and self.email_validation:
cause = "invalid email format: '%s'" % raw_email
raise InvalidFormatError(cause=cause)
if self.email_validation:
email = e.group('email').strip()
else:
email = raw_email
r = re.match(self.ENROLLMENT_REGEX, raw_enrollment, re.UNICODE)
if not r:
cause = "invalid enrollment format: '%s'" % raw_enrollment
raise InvalidFormatError(cause=cause)
org = r.group('organization').strip()
date = r.group('date')
if date:
try:
dt = dateutil.parser.parse(r.group('date'))
except Exception as e:
cause = "invalid date: '%s'" % date
else:
dt = MAX_PERIOD_DATE
email = self.__encode(email)
org = self.__encode(org)
return email, org, dt | [
"def",
"__parse_email_to_employer_line",
"(",
"self",
",",
"raw_email",
",",
"raw_enrollment",
")",
":",
"e",
"=",
"re",
".",
"match",
"(",
"self",
".",
"EMAIL_ADDRESS_REGEX",
",",
"raw_email",
",",
"re",
".",
"UNICODE",
")",
"if",
"not",
"e",
"and",
"self... | Parse email to employer lines | [
"Parse",
"email",
"to",
"employer",
"lines"
] | 391cd37a75fea26311dc6908bc1c953c540a8e04 | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/parsing/gitdm.py#L316-L348 |
27,096 | chaoss/grimoirelab-sortinghat | sortinghat/parsing/gitdm.py | GitdmParser.__parse_domain_to_employer_line | def __parse_domain_to_employer_line(self, raw_domain, raw_org):
"""Parse domain to employer lines"""
d = re.match(self.DOMAIN_REGEX, raw_domain, re.UNICODE)
if not d:
cause = "invalid domain format: '%s'" % raw_domain
raise InvalidFormatError(cause=cause)
dom = d.group('domain').strip()
o = re.match(self.ORGANIZATION_REGEX, raw_org, re.UNICODE)
if not o:
cause = "invalid organization format: '%s'" % raw_org
raise InvalidFormatError(cause=cause)
org = o.group('organization').strip()
org = self.__encode(org)
dom = self.__encode(dom)
return org, dom | python | def __parse_domain_to_employer_line(self, raw_domain, raw_org):
d = re.match(self.DOMAIN_REGEX, raw_domain, re.UNICODE)
if not d:
cause = "invalid domain format: '%s'" % raw_domain
raise InvalidFormatError(cause=cause)
dom = d.group('domain').strip()
o = re.match(self.ORGANIZATION_REGEX, raw_org, re.UNICODE)
if not o:
cause = "invalid organization format: '%s'" % raw_org
raise InvalidFormatError(cause=cause)
org = o.group('organization').strip()
org = self.__encode(org)
dom = self.__encode(dom)
return org, dom | [
"def",
"__parse_domain_to_employer_line",
"(",
"self",
",",
"raw_domain",
",",
"raw_org",
")",
":",
"d",
"=",
"re",
".",
"match",
"(",
"self",
".",
"DOMAIN_REGEX",
",",
"raw_domain",
",",
"re",
".",
"UNICODE",
")",
"if",
"not",
"d",
":",
"cause",
"=",
... | Parse domain to employer lines | [
"Parse",
"domain",
"to",
"employer",
"lines"
] | 391cd37a75fea26311dc6908bc1c953c540a8e04 | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/parsing/gitdm.py#L350-L370 |
27,097 | chaoss/grimoirelab-sortinghat | sortinghat/cmd/log.py | Log.log | def log(self, uuid=None, organization=None, from_date=None, to_date=None):
""""List enrollment information available in the registry.
Method that returns a list of enrollments. If <uuid> parameter is set,
it will return the enrollments related to that unique identity;
if <organization> parameter is given, it will return the enrollments
related to that organization; if both parameters are set, the function
will return the list of enrollments of <uuid> on the <organization>.
Enrollments between a period can also be listed using <from_date> and
<to_date> parameters. When these are set, the method will return
all those enrollments where Enrollment.start >= from_date AND
Enrollment.end <= to_date. Defaults values for these dates are
1900-01-01 and 2100-01-01.
:param db: database manager
:param uuid: unique identifier
:param organization: name of the organization
:param from_date: date when the enrollment starts
:param to_date: date when the enrollment ends
"""
try:
enrollments = api.enrollments(self.db, uuid, organization,
from_date, to_date)
self.display('log.tmpl', enrollments=enrollments)
except (NotFoundError, InvalidValueError) as e:
self.error(str(e))
return e.code
return CMD_SUCCESS | python | def log(self, uuid=None, organization=None, from_date=None, to_date=None):
"try:
enrollments = api.enrollments(self.db, uuid, organization,
from_date, to_date)
self.display('log.tmpl', enrollments=enrollments)
except (NotFoundError, InvalidValueError) as e:
self.error(str(e))
return e.code
return CMD_SUCCESS | [
"def",
"log",
"(",
"self",
",",
"uuid",
"=",
"None",
",",
"organization",
"=",
"None",
",",
"from_date",
"=",
"None",
",",
"to_date",
"=",
"None",
")",
":",
"try",
":",
"enrollments",
"=",
"api",
".",
"enrollments",
"(",
"self",
".",
"db",
",",
"uu... | List enrollment information available in the registry.
Method that returns a list of enrollments. If <uuid> parameter is set,
it will return the enrollments related to that unique identity;
if <organization> parameter is given, it will return the enrollments
related to that organization; if both parameters are set, the function
will return the list of enrollments of <uuid> on the <organization>.
Enrollments between a period can also be listed using <from_date> and
<to_date> parameters. When these are set, the method will return
all those enrollments where Enrollment.start >= from_date AND
Enrollment.end <= to_date. Defaults values for these dates are
1900-01-01 and 2100-01-01.
:param db: database manager
:param uuid: unique identifier
:param organization: name of the organization
:param from_date: date when the enrollment starts
:param to_date: date when the enrollment ends | [
"List",
"enrollment",
"information",
"available",
"in",
"the",
"registry",
"."
] | 391cd37a75fea26311dc6908bc1c953c540a8e04 | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/cmd/log.py#L96-L125 |
27,098 | chaoss/grimoirelab-sortinghat | sortinghat/cmd/init.py | Init.run | def run(self, *args):
"""Initialize a registry.
Create and initialize an empty registry which its name is defined by
<name> parameter. Required tables will be also created.
"""
params = self.parser.parse_args(args)
code = self.initialize(name=params.name, reuse=params.reuse)
return code | python | def run(self, *args):
params = self.parser.parse_args(args)
code = self.initialize(name=params.name, reuse=params.reuse)
return code | [
"def",
"run",
"(",
"self",
",",
"*",
"args",
")",
":",
"params",
"=",
"self",
".",
"parser",
".",
"parse_args",
"(",
"args",
")",
"code",
"=",
"self",
".",
"initialize",
"(",
"name",
"=",
"params",
".",
"name",
",",
"reuse",
"=",
"params",
".",
"... | Initialize a registry.
Create and initialize an empty registry which its name is defined by
<name> parameter. Required tables will be also created. | [
"Initialize",
"a",
"registry",
"."
] | 391cd37a75fea26311dc6908bc1c953c540a8e04 | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/cmd/init.py#L65-L75 |
27,099 | chaoss/grimoirelab-sortinghat | sortinghat/cmd/init.py | Init.initialize | def initialize(self, name, reuse=False):
"""Create an empty Sorting Hat registry.
This method creates a new database including the schema of Sorting Hat.
Any attempt to create a new registry over an existing instance will
produce an error, except if reuse=True. In that case, the
database will be reused, assuming the database schema is correct
(it won't be created in this case).
:param name: name of the database
:param reuse: reuse database if it already exists
"""
user = self._kwargs['user']
password = self._kwargs['password']
host = self._kwargs['host']
port = self._kwargs['port']
if '-' in name:
self.error("dabase name '%s' cannot contain '-' characters" % name)
return CODE_VALUE_ERROR
try:
Database.create(user, password, name, host, port)
# Try to access and create schema
db = Database(user, password, name, host, port)
# Load countries list
self.__load_countries(db)
except DatabaseExists as e:
if not reuse:
self.error(str(e))
return CODE_DATABASE_EXISTS
except DatabaseError as e:
self.error(str(e))
return CODE_DATABASE_ERROR
except LoadError as e:
Database.drop(user, password, name, host, port)
self.error(str(e))
return CODE_LOAD_ERROR
return CMD_SUCCESS | python | def initialize(self, name, reuse=False):
user = self._kwargs['user']
password = self._kwargs['password']
host = self._kwargs['host']
port = self._kwargs['port']
if '-' in name:
self.error("dabase name '%s' cannot contain '-' characters" % name)
return CODE_VALUE_ERROR
try:
Database.create(user, password, name, host, port)
# Try to access and create schema
db = Database(user, password, name, host, port)
# Load countries list
self.__load_countries(db)
except DatabaseExists as e:
if not reuse:
self.error(str(e))
return CODE_DATABASE_EXISTS
except DatabaseError as e:
self.error(str(e))
return CODE_DATABASE_ERROR
except LoadError as e:
Database.drop(user, password, name, host, port)
self.error(str(e))
return CODE_LOAD_ERROR
return CMD_SUCCESS | [
"def",
"initialize",
"(",
"self",
",",
"name",
",",
"reuse",
"=",
"False",
")",
":",
"user",
"=",
"self",
".",
"_kwargs",
"[",
"'user'",
"]",
"password",
"=",
"self",
".",
"_kwargs",
"[",
"'password'",
"]",
"host",
"=",
"self",
".",
"_kwargs",
"[",
... | Create an empty Sorting Hat registry.
This method creates a new database including the schema of Sorting Hat.
Any attempt to create a new registry over an existing instance will
produce an error, except if reuse=True. In that case, the
database will be reused, assuming the database schema is correct
(it won't be created in this case).
:param name: name of the database
:param reuse: reuse database if it already exists | [
"Create",
"an",
"empty",
"Sorting",
"Hat",
"registry",
"."
] | 391cd37a75fea26311dc6908bc1c953c540a8e04 | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/cmd/init.py#L77-L116 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.