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 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1 value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
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):
"""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() | [
"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 | train | 25,600 |
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):
"""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 | [
"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 | train | 25,601 |
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):
"""Display some stats regarding unify process"""
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 | train | 25,602 |
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):
"""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 | [
"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 | train | 25,603 |
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):
"""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 | [
"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 | train | 25,604 |
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):
"""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") | [
"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 | train | 25,605 |
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):
"""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 | [
"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 | train | 25,606 |
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):
"""Parse GrimoireLab 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 | train | 25,607 |
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):
"""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) | [
"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 | train | 25,608 |
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):
"""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) | [
"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 | train | 25,609 |
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):
"""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 | [
"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 | train | 25,610 |
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):
"""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) | [
"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 | train | 25,611 |
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):
"""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) | [
"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 | train | 25,612 |
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):
"""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) | [
"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 | train | 25,613 |
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):
"""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 | [
"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 | train | 25,614 |
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):
"""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) | [
"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 | train | 25,615 |
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):
"""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) | [
"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 | train | 25,616 |
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):
"""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) | [
"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 | train | 25,617 |
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):
"""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 | [
"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 | train | 25,618 |
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):
"""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))) | [
"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 | train | 25,619 |
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):
"""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) | [
"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 | train | 25,620 |
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):
"""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 | [
"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 | train | 25,621 |
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):
"""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))) | [
"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 | train | 25,622 |
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):
"""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") | [
"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 | train | 25,623 |
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):
"""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 | [
"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 | train | 25,624 |
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):
"""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) | [
"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 | train | 25,625 |
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):
"""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) | [
"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 | train | 25,626 |
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):
"""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) | [
"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 | train | 25,627 |
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):
"""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 | [
"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 | train | 25,628 |
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):
"""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) | [
"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 | train | 25,629 |
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):
"""Parse Gitdm streams"""
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 | train | 25,630 |
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 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 | [
"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 | train | 25,631 |
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 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 | [
"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 | train | 25,632 |
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):
"""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 | [
"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 | train | 25,633 |
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):
"""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)) | [
"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 | train | 25,634 |
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):
"""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) | [
"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 | train | 25,635 |
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):
"""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) | [
"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 | train | 25,636 |
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):
"""Parse aliases lines"""
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 | train | 25,637 |
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):
"""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 | [
"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 | train | 25,638 |
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):
"""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 | [
"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 | train | 25,639 |
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):
""""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 | [
"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 | train | 25,640 |
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):
"""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 | [
"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 | train | 25,641 |
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):
"""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 | [
"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 | train | 25,642 |
chaoss/grimoirelab-sortinghat | sortinghat/cmd/init.py | Init.__load_countries | def __load_countries(self, db):
"""Load the list of countries"""
try:
countries = self.__read_countries_file()
except IOError as e:
raise LoadError(str(e))
try:
with db.connect() as session:
for country in countries:
session.add(country)
except Exception as e:
raise LoadError(str(e)) | python | def __load_countries(self, db):
"""Load the list of countries"""
try:
countries = self.__read_countries_file()
except IOError as e:
raise LoadError(str(e))
try:
with db.connect() as session:
for country in countries:
session.add(country)
except Exception as e:
raise LoadError(str(e)) | [
"def",
"__load_countries",
"(",
"self",
",",
"db",
")",
":",
"try",
":",
"countries",
"=",
"self",
".",
"__read_countries_file",
"(",
")",
"except",
"IOError",
"as",
"e",
":",
"raise",
"LoadError",
"(",
"str",
"(",
"e",
")",
")",
"try",
":",
"with",
... | Load the list of countries | [
"Load",
"the",
"list",
"of",
"countries"
] | 391cd37a75fea26311dc6908bc1c953c540a8e04 | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/cmd/init.py#L118-L131 | train | 25,643 |
chaoss/grimoirelab-sortinghat | sortinghat/cmd/init.py | Init.__read_countries_file | def __read_countries_file(self):
"""Read countries from a CSV file"""
import csv
import pkg_resources
filename = pkg_resources.resource_filename('sortinghat', 'data/countries.csv')
with open(filename, 'r') as f:
reader = csv.DictReader(f, fieldnames=['name', 'code', 'alpha3'])
countries = [Country(**c) for c in reader]
return countries | python | def __read_countries_file(self):
"""Read countries from a CSV file"""
import csv
import pkg_resources
filename = pkg_resources.resource_filename('sortinghat', 'data/countries.csv')
with open(filename, 'r') as f:
reader = csv.DictReader(f, fieldnames=['name', 'code', 'alpha3'])
countries = [Country(**c) for c in reader]
return countries | [
"def",
"__read_countries_file",
"(",
"self",
")",
":",
"import",
"csv",
"import",
"pkg_resources",
"filename",
"=",
"pkg_resources",
".",
"resource_filename",
"(",
"'sortinghat'",
",",
"'data/countries.csv'",
")",
"with",
"open",
"(",
"filename",
",",
"'r'",
")",
... | Read countries from a CSV file | [
"Read",
"countries",
"from",
"a",
"CSV",
"file"
] | 391cd37a75fea26311dc6908bc1c953c540a8e04 | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/cmd/init.py#L133-L144 | train | 25,644 |
chaoss/grimoirelab-sortinghat | sortinghat/cmd/remove.py | Remove.run | def run(self, *args):
"""Remove unique identities or identities from the registry.
By default, it removes the unique identity identified by <identifier>.
To remove an identity, set <identity> parameter.
"""
params = self.parser.parse_args(args)
identifier = params.identifier
identity = params.identity
code = self.remove(identifier, identity)
return code | python | def run(self, *args):
"""Remove unique identities or identities from the registry.
By default, it removes the unique identity identified by <identifier>.
To remove an identity, set <identity> parameter.
"""
params = self.parser.parse_args(args)
identifier = params.identifier
identity = params.identity
code = self.remove(identifier, identity)
return code | [
"def",
"run",
"(",
"self",
",",
"*",
"args",
")",
":",
"params",
"=",
"self",
".",
"parser",
".",
"parse_args",
"(",
"args",
")",
"identifier",
"=",
"params",
".",
"identifier",
"identity",
"=",
"params",
".",
"identity",
"code",
"=",
"self",
".",
"r... | Remove unique identities or identities from the registry.
By default, it removes the unique identity identified by <identifier>.
To remove an identity, set <identity> parameter. | [
"Remove",
"unique",
"identities",
"or",
"identities",
"from",
"the",
"registry",
"."
] | 391cd37a75fea26311dc6908bc1c953c540a8e04 | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/cmd/remove.py#L71-L84 | train | 25,645 |
chaoss/grimoirelab-sortinghat | sortinghat/utils.py | merge_date_ranges | def merge_date_ranges(dates):
"""Merge date ranges.
Generator that merges ovelaped data ranges.
Default init 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)
The condition MIN_PERIOD_DATE <= dt <= MAX_PERIOD_DATE must be true for each
date. Otherwise, the generator will raise a ValueError exception.
This code is based on samplebias' answer to StackOverflow's question
"Merging a list of time-range tuples that have overlapping time-ranges"
(http://stackoverflow.com/questions/5679638).
:param dates: sequence of date ranges where each range is a
(st_date, en_date) tuple
:raises ValueError: when a value of the data range is out of bounds
"""
if not dates:
return
sorted_dates = sorted([sorted(t) for t in dates])
saved = list(sorted_dates[0])
for st, en in sorted_dates:
if st < MIN_PERIOD_DATE or st > MAX_PERIOD_DATE:
raise ValueError("start date %s is out of bounds" % str(st))
if en < MIN_PERIOD_DATE or en > MAX_PERIOD_DATE:
raise ValueError("end date %s is out of bounds" % str(en))
if st <= saved[1]:
if saved[0] == MIN_PERIOD_DATE:
saved[0] = st
if MAX_PERIOD_DATE in (en, saved[1]):
saved[1] = min(saved[1], en)
else:
saved[1] = max(saved[1], en)
else:
yield tuple(saved)
saved[0] = st
saved[1] = en
yield tuple(saved) | python | def merge_date_ranges(dates):
"""Merge date ranges.
Generator that merges ovelaped data ranges.
Default init 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)
The condition MIN_PERIOD_DATE <= dt <= MAX_PERIOD_DATE must be true for each
date. Otherwise, the generator will raise a ValueError exception.
This code is based on samplebias' answer to StackOverflow's question
"Merging a list of time-range tuples that have overlapping time-ranges"
(http://stackoverflow.com/questions/5679638).
:param dates: sequence of date ranges where each range is a
(st_date, en_date) tuple
:raises ValueError: when a value of the data range is out of bounds
"""
if not dates:
return
sorted_dates = sorted([sorted(t) for t in dates])
saved = list(sorted_dates[0])
for st, en in sorted_dates:
if st < MIN_PERIOD_DATE or st > MAX_PERIOD_DATE:
raise ValueError("start date %s is out of bounds" % str(st))
if en < MIN_PERIOD_DATE or en > MAX_PERIOD_DATE:
raise ValueError("end date %s is out of bounds" % str(en))
if st <= saved[1]:
if saved[0] == MIN_PERIOD_DATE:
saved[0] = st
if MAX_PERIOD_DATE in (en, saved[1]):
saved[1] = min(saved[1], en)
else:
saved[1] = max(saved[1], en)
else:
yield tuple(saved)
saved[0] = st
saved[1] = en
yield tuple(saved) | [
"def",
"merge_date_ranges",
"(",
"dates",
")",
":",
"if",
"not",
"dates",
":",
"return",
"sorted_dates",
"=",
"sorted",
"(",
"[",
"sorted",
"(",
"t",
")",
"for",
"t",
"in",
"dates",
"]",
")",
"saved",
"=",
"list",
"(",
"sorted_dates",
"[",
"0",
"]",
... | Merge date ranges.
Generator that merges ovelaped data ranges.
Default init 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)
The condition MIN_PERIOD_DATE <= dt <= MAX_PERIOD_DATE must be true for each
date. Otherwise, the generator will raise a ValueError exception.
This code is based on samplebias' answer to StackOverflow's question
"Merging a list of time-range tuples that have overlapping time-ranges"
(http://stackoverflow.com/questions/5679638).
:param dates: sequence of date ranges where each range is a
(st_date, en_date) tuple
:raises ValueError: when a value of the data range is out of bounds | [
"Merge",
"date",
"ranges",
"."
] | 391cd37a75fea26311dc6908bc1c953c540a8e04 | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/utils.py#L33-L84 | train | 25,646 |
chaoss/grimoirelab-sortinghat | sortinghat/utils.py | uuid | def uuid(source, email=None, name=None, username=None):
"""Get the UUID related to the identity data.
Based on the input data, the function will return the UUID associated
to an identity. On this version, the UUID will be the SHA1 of
"source:email:name:username" string. This string is case insensitive,
which means same values for the input parameters in upper
or lower case will produce the same UUID.
The value of 'name' will converted to its unaccent form which means
same values with accent or unnacent chars (i.e 'ö and o') will
generate the same UUID.
For instance, these combinations will produce the same UUID:
('scm', 'jsmith@example.com', 'John Smith', 'jsmith'),
('scm', 'jsmith@example,com', 'Jöhn Smith', 'jsmith'),
('scm', 'jsmith@example.com', 'John Smith', 'JSMITH'),
('scm', 'jsmith@example.com', 'john Smith', 'jsmith')
:param source: data source
:param email: email of the identity
:param name: full name of the identity
:param username: user name used by the identity
:returns: a universal unique identifier for Sorting Hat
:raises ValueError: when source is None or empty; each one of the
parameters is None; parameters are empty.
"""
if source is None:
raise ValueError("source cannot be None")
if source == '':
raise ValueError("source cannot be an empty string")
if not (email or name or username):
raise ValueError("identity data cannot be None or empty")
s = ':'.join((to_unicode(source),
to_unicode(email),
to_unicode(name, unaccent=True),
to_unicode(username))).lower()
sha1 = hashlib.sha1(s.encode('UTF-8', errors="surrogateescape"))
uuid_ = sha1.hexdigest()
return uuid_ | python | def uuid(source, email=None, name=None, username=None):
"""Get the UUID related to the identity data.
Based on the input data, the function will return the UUID associated
to an identity. On this version, the UUID will be the SHA1 of
"source:email:name:username" string. This string is case insensitive,
which means same values for the input parameters in upper
or lower case will produce the same UUID.
The value of 'name' will converted to its unaccent form which means
same values with accent or unnacent chars (i.e 'ö and o') will
generate the same UUID.
For instance, these combinations will produce the same UUID:
('scm', 'jsmith@example.com', 'John Smith', 'jsmith'),
('scm', 'jsmith@example,com', 'Jöhn Smith', 'jsmith'),
('scm', 'jsmith@example.com', 'John Smith', 'JSMITH'),
('scm', 'jsmith@example.com', 'john Smith', 'jsmith')
:param source: data source
:param email: email of the identity
:param name: full name of the identity
:param username: user name used by the identity
:returns: a universal unique identifier for Sorting Hat
:raises ValueError: when source is None or empty; each one of the
parameters is None; parameters are empty.
"""
if source is None:
raise ValueError("source cannot be None")
if source == '':
raise ValueError("source cannot be an empty string")
if not (email or name or username):
raise ValueError("identity data cannot be None or empty")
s = ':'.join((to_unicode(source),
to_unicode(email),
to_unicode(name, unaccent=True),
to_unicode(username))).lower()
sha1 = hashlib.sha1(s.encode('UTF-8', errors="surrogateescape"))
uuid_ = sha1.hexdigest()
return uuid_ | [
"def",
"uuid",
"(",
"source",
",",
"email",
"=",
"None",
",",
"name",
"=",
"None",
",",
"username",
"=",
"None",
")",
":",
"if",
"source",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"source cannot be None\"",
")",
"if",
"source",
"==",
"''",
":",... | Get the UUID related to the identity data.
Based on the input data, the function will return the UUID associated
to an identity. On this version, the UUID will be the SHA1 of
"source:email:name:username" string. This string is case insensitive,
which means same values for the input parameters in upper
or lower case will produce the same UUID.
The value of 'name' will converted to its unaccent form which means
same values with accent or unnacent chars (i.e 'ö and o') will
generate the same UUID.
For instance, these combinations will produce the same UUID:
('scm', 'jsmith@example.com', 'John Smith', 'jsmith'),
('scm', 'jsmith@example,com', 'Jöhn Smith', 'jsmith'),
('scm', 'jsmith@example.com', 'John Smith', 'JSMITH'),
('scm', 'jsmith@example.com', 'john Smith', 'jsmith')
:param source: data source
:param email: email of the identity
:param name: full name of the identity
:param username: user name used by the identity
:returns: a universal unique identifier for Sorting Hat
:raises ValueError: when source is None or empty; each one of the
parameters is None; parameters are empty. | [
"Get",
"the",
"UUID",
"related",
"to",
"the",
"identity",
"data",
"."
] | 391cd37a75fea26311dc6908bc1c953c540a8e04 | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/utils.py#L122-L167 | train | 25,647 |
chaoss/grimoirelab-sortinghat | sortinghat/db/database.py | create_database_engine | def create_database_engine(user, password, database, host, port):
"""Create a database engine"""
driver = 'mysql+pymysql'
url = URL(driver, user, password, host, port, database,
query={'charset': 'utf8mb4'})
return create_engine(url, poolclass=QueuePool,
pool_size=25, pool_pre_ping=True,
echo=False) | python | def create_database_engine(user, password, database, host, port):
"""Create a database engine"""
driver = 'mysql+pymysql'
url = URL(driver, user, password, host, port, database,
query={'charset': 'utf8mb4'})
return create_engine(url, poolclass=QueuePool,
pool_size=25, pool_pre_ping=True,
echo=False) | [
"def",
"create_database_engine",
"(",
"user",
",",
"password",
",",
"database",
",",
"host",
",",
"port",
")",
":",
"driver",
"=",
"'mysql+pymysql'",
"url",
"=",
"URL",
"(",
"driver",
",",
"user",
",",
"password",
",",
"host",
",",
"port",
",",
"database... | Create a database engine | [
"Create",
"a",
"database",
"engine"
] | 391cd37a75fea26311dc6908bc1c953c540a8e04 | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/db/database.py#L170-L178 | train | 25,648 |
chaoss/grimoirelab-sortinghat | sortinghat/db/database.py | create_database_session | def create_database_session(engine):
"""Connect to the database"""
try:
Session = sessionmaker(bind=engine)
return Session()
except OperationalError as e:
raise DatabaseError(error=e.orig.args[1], code=e.orig.args[0]) | python | def create_database_session(engine):
"""Connect to the database"""
try:
Session = sessionmaker(bind=engine)
return Session()
except OperationalError as e:
raise DatabaseError(error=e.orig.args[1], code=e.orig.args[0]) | [
"def",
"create_database_session",
"(",
"engine",
")",
":",
"try",
":",
"Session",
"=",
"sessionmaker",
"(",
"bind",
"=",
"engine",
")",
"return",
"Session",
"(",
")",
"except",
"OperationalError",
"as",
"e",
":",
"raise",
"DatabaseError",
"(",
"error",
"=",
... | Connect to the database | [
"Connect",
"to",
"the",
"database"
] | 391cd37a75fea26311dc6908bc1c953c540a8e04 | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/db/database.py#L181-L188 | train | 25,649 |
chaoss/grimoirelab-sortinghat | sortinghat/db/database.py | close_database_session | def close_database_session(session):
"""Close connection with the database"""
try:
session.close()
except OperationalError as e:
raise DatabaseError(error=e.orig.args[1], code=e.orig.args[0]) | python | def close_database_session(session):
"""Close connection with the database"""
try:
session.close()
except OperationalError as e:
raise DatabaseError(error=e.orig.args[1], code=e.orig.args[0]) | [
"def",
"close_database_session",
"(",
"session",
")",
":",
"try",
":",
"session",
".",
"close",
"(",
")",
"except",
"OperationalError",
"as",
"e",
":",
"raise",
"DatabaseError",
"(",
"error",
"=",
"e",
".",
"orig",
".",
"args",
"[",
"1",
"]",
",",
"cod... | Close connection with the database | [
"Close",
"connection",
"with",
"the",
"database"
] | 391cd37a75fea26311dc6908bc1c953c540a8e04 | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/db/database.py#L191-L197 | train | 25,650 |
chaoss/grimoirelab-sortinghat | sortinghat/db/database.py | reflect_table | def reflect_table(engine, klass):
"""Inspect and reflect objects"""
try:
meta = MetaData()
meta.reflect(bind=engine)
except OperationalError as e:
raise DatabaseError(error=e.orig.args[1], code=e.orig.args[0])
# Try to reflect from any of the supported tables
table = None
for tb in klass.tables():
if tb in meta.tables:
table = meta.tables[tb]
break
if table is None:
raise DatabaseError(error="Invalid schema. Table not found",
code="-1")
# Map table schema into klass
mapper(klass, table,
column_prefix=klass.column_prefix())
return table | python | def reflect_table(engine, klass):
"""Inspect and reflect objects"""
try:
meta = MetaData()
meta.reflect(bind=engine)
except OperationalError as e:
raise DatabaseError(error=e.orig.args[1], code=e.orig.args[0])
# Try to reflect from any of the supported tables
table = None
for tb in klass.tables():
if tb in meta.tables:
table = meta.tables[tb]
break
if table is None:
raise DatabaseError(error="Invalid schema. Table not found",
code="-1")
# Map table schema into klass
mapper(klass, table,
column_prefix=klass.column_prefix())
return table | [
"def",
"reflect_table",
"(",
"engine",
",",
"klass",
")",
":",
"try",
":",
"meta",
"=",
"MetaData",
"(",
")",
"meta",
".",
"reflect",
"(",
"bind",
"=",
"engine",
")",
"except",
"OperationalError",
"as",
"e",
":",
"raise",
"DatabaseError",
"(",
"error",
... | Inspect and reflect objects | [
"Inspect",
"and",
"reflect",
"objects"
] | 391cd37a75fea26311dc6908bc1c953c540a8e04 | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/db/database.py#L200-L225 | train | 25,651 |
chaoss/grimoirelab-sortinghat | sortinghat/db/database.py | find_model_by_table_name | def find_model_by_table_name(name):
"""Find a model reference by its table name"""
for model in ModelBase._decl_class_registry.values():
if hasattr(model, '__table__') and model.__table__.fullname == name:
return model
return None | python | def find_model_by_table_name(name):
"""Find a model reference by its table name"""
for model in ModelBase._decl_class_registry.values():
if hasattr(model, '__table__') and model.__table__.fullname == name:
return model
return None | [
"def",
"find_model_by_table_name",
"(",
"name",
")",
":",
"for",
"model",
"in",
"ModelBase",
".",
"_decl_class_registry",
".",
"values",
"(",
")",
":",
"if",
"hasattr",
"(",
"model",
",",
"'__table__'",
")",
"and",
"model",
".",
"__table__",
".",
"fullname",... | Find a model reference by its table name | [
"Find",
"a",
"model",
"reference",
"by",
"its",
"table",
"name"
] | 391cd37a75fea26311dc6908bc1c953c540a8e04 | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/db/database.py#L228-L234 | train | 25,652 |
chaoss/grimoirelab-sortinghat | sortinghat/db/database.py | Database.handle_database_error | def handle_database_error(cls, session, exception):
"""Rollback changes made and handle any type of error raised by the DBMS."""
session.rollback()
if isinstance(exception, IntegrityError):
cls.handle_integrity_error(exception)
elif isinstance(exception, FlushError):
cls.handle_flush_error(exception)
else:
raise exception | python | def handle_database_error(cls, session, exception):
"""Rollback changes made and handle any type of error raised by the DBMS."""
session.rollback()
if isinstance(exception, IntegrityError):
cls.handle_integrity_error(exception)
elif isinstance(exception, FlushError):
cls.handle_flush_error(exception)
else:
raise exception | [
"def",
"handle_database_error",
"(",
"cls",
",",
"session",
",",
"exception",
")",
":",
"session",
".",
"rollback",
"(",
")",
"if",
"isinstance",
"(",
"exception",
",",
"IntegrityError",
")",
":",
"cls",
".",
"handle_integrity_error",
"(",
"exception",
")",
... | Rollback changes made and handle any type of error raised by the DBMS. | [
"Rollback",
"changes",
"made",
"and",
"handle",
"any",
"type",
"of",
"error",
"raised",
"by",
"the",
"DBMS",
"."
] | 391cd37a75fea26311dc6908bc1c953c540a8e04 | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/db/database.py#L113-L123 | train | 25,653 |
chaoss/grimoirelab-sortinghat | sortinghat/db/database.py | Database.handle_integrity_error | def handle_integrity_error(cls, exception):
"""Handle integrity error exceptions."""
m = re.match(cls.MYSQL_INSERT_ERROR_REGEX,
exception.statement)
if not m:
raise exception
model = find_model_by_table_name(m.group('table'))
if not model:
raise exception
m = re.match(cls.MYSQL_DUPLICATE_ENTRY_ERROR_REGEX,
exception.orig.args[1])
if not m:
raise exception
entity = model.__name__
eid = m.group('value')
raise AlreadyExistsError(entity=entity, eid=eid) | python | def handle_integrity_error(cls, exception):
"""Handle integrity error exceptions."""
m = re.match(cls.MYSQL_INSERT_ERROR_REGEX,
exception.statement)
if not m:
raise exception
model = find_model_by_table_name(m.group('table'))
if not model:
raise exception
m = re.match(cls.MYSQL_DUPLICATE_ENTRY_ERROR_REGEX,
exception.orig.args[1])
if not m:
raise exception
entity = model.__name__
eid = m.group('value')
raise AlreadyExistsError(entity=entity, eid=eid) | [
"def",
"handle_integrity_error",
"(",
"cls",
",",
"exception",
")",
":",
"m",
"=",
"re",
".",
"match",
"(",
"cls",
".",
"MYSQL_INSERT_ERROR_REGEX",
",",
"exception",
".",
"statement",
")",
"if",
"not",
"m",
":",
"raise",
"exception",
"model",
"=",
"find_mo... | Handle integrity error exceptions. | [
"Handle",
"integrity",
"error",
"exceptions",
"."
] | 391cd37a75fea26311dc6908bc1c953c540a8e04 | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/db/database.py#L126-L149 | train | 25,654 |
chaoss/grimoirelab-sortinghat | sortinghat/db/database.py | Database.handle_flush_error | def handle_flush_error(cls, exception):
"""Handle flush error exceptions."""
trace = exception.args[0]
m = re.match(cls.MYSQL_FLUSH_ERROR_REGEX, trace)
if not m:
raise exception
entity = m.group('entity')
eid = m.group('eid')
raise AlreadyExistsError(entity=entity, eid=eid) | python | def handle_flush_error(cls, exception):
"""Handle flush error exceptions."""
trace = exception.args[0]
m = re.match(cls.MYSQL_FLUSH_ERROR_REGEX, trace)
if not m:
raise exception
entity = m.group('entity')
eid = m.group('eid')
raise AlreadyExistsError(entity=entity, eid=eid) | [
"def",
"handle_flush_error",
"(",
"cls",
",",
"exception",
")",
":",
"trace",
"=",
"exception",
".",
"args",
"[",
"0",
"]",
"m",
"=",
"re",
".",
"match",
"(",
"cls",
".",
"MYSQL_FLUSH_ERROR_REGEX",
",",
"trace",
")",
"if",
"not",
"m",
":",
"raise",
"... | Handle flush error exceptions. | [
"Handle",
"flush",
"error",
"exceptions",
"."
] | 391cd37a75fea26311dc6908bc1c953c540a8e04 | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/db/database.py#L152-L164 | train | 25,655 |
chaoss/grimoirelab-sortinghat | sortinghat/cmd/affiliate.py | Affiliate.run | def run(self, *args):
"""Affiliate unique identities to organizations."""
self.parser.parse_args(args)
code = self.affiliate()
return code | python | def run(self, *args):
"""Affiliate unique identities to organizations."""
self.parser.parse_args(args)
code = self.affiliate()
return code | [
"def",
"run",
"(",
"self",
",",
"*",
"args",
")",
":",
"self",
".",
"parser",
".",
"parse_args",
"(",
"args",
")",
"code",
"=",
"self",
".",
"affiliate",
"(",
")",
"return",
"code"
] | Affiliate unique identities to organizations. | [
"Affiliate",
"unique",
"identities",
"to",
"organizations",
"."
] | 391cd37a75fea26311dc6908bc1c953c540a8e04 | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/cmd/affiliate.py#L62-L69 | train | 25,656 |
chaoss/grimoirelab-sortinghat | sortinghat/cmd/affiliate.py | Affiliate.affiliate | def affiliate(self):
"""Affiliate unique identities.
This method enrolls unique identities to organizations using email
addresses and top/sub domains data. Only new enrollments will be created.
"""
try:
uidentities = api.unique_identities(self.db)
for uid in uidentities:
uid.identities.sort(key=lambda x: x.id)
for identity in uid.identities:
# Only check email address to find new affiliations
if not identity.email:
continue
if not EMAIL_ADDRESS_PATTERN.match(identity.email):
continue
domain = identity.email.split('@')[-1]
try:
doms = api.domains(self.db, domain=domain, top=True)
except NotFoundError as e:
continue
if len(doms) > 1:
doms.sort(key=lambda d: len(d.domain), reverse=True)
msg = "multiple top domains for %s sub-domain. Domain %s selected."
msg = msg % (domain, doms[0].domain)
self.warning(msg)
organization = doms[0].organization.name
# Check enrollments to avoid insert affiliation twice
enrollments = api.enrollments(self.db, uid.uuid,
organization)
if enrollments:
continue
api.add_enrollment(self.db, uid.uuid, organization)
self.display('affiliate.tmpl', id=uid.uuid,
email=identity.email, organization=organization)
except (NotFoundError, InvalidValueError) as e:
self.error(str(e))
return e.code
return CMD_SUCCESS | python | def affiliate(self):
"""Affiliate unique identities.
This method enrolls unique identities to organizations using email
addresses and top/sub domains data. Only new enrollments will be created.
"""
try:
uidentities = api.unique_identities(self.db)
for uid in uidentities:
uid.identities.sort(key=lambda x: x.id)
for identity in uid.identities:
# Only check email address to find new affiliations
if not identity.email:
continue
if not EMAIL_ADDRESS_PATTERN.match(identity.email):
continue
domain = identity.email.split('@')[-1]
try:
doms = api.domains(self.db, domain=domain, top=True)
except NotFoundError as e:
continue
if len(doms) > 1:
doms.sort(key=lambda d: len(d.domain), reverse=True)
msg = "multiple top domains for %s sub-domain. Domain %s selected."
msg = msg % (domain, doms[0].domain)
self.warning(msg)
organization = doms[0].organization.name
# Check enrollments to avoid insert affiliation twice
enrollments = api.enrollments(self.db, uid.uuid,
organization)
if enrollments:
continue
api.add_enrollment(self.db, uid.uuid, organization)
self.display('affiliate.tmpl', id=uid.uuid,
email=identity.email, organization=organization)
except (NotFoundError, InvalidValueError) as e:
self.error(str(e))
return e.code
return CMD_SUCCESS | [
"def",
"affiliate",
"(",
"self",
")",
":",
"try",
":",
"uidentities",
"=",
"api",
".",
"unique_identities",
"(",
"self",
".",
"db",
")",
"for",
"uid",
"in",
"uidentities",
":",
"uid",
".",
"identities",
".",
"sort",
"(",
"key",
"=",
"lambda",
"x",
":... | Affiliate unique identities.
This method enrolls unique identities to organizations using email
addresses and top/sub domains data. Only new enrollments will be created. | [
"Affiliate",
"unique",
"identities",
"."
] | 391cd37a75fea26311dc6908bc1c953c540a8e04 | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/cmd/affiliate.py#L71-L121 | train | 25,657 |
chaoss/grimoirelab-sortinghat | sortinghat/cmd/countries.py | Countries.run | def run(self, *args):
"""Show information about countries."""
params = self.parser.parse_args(args)
ct = params.code_or_term
if ct and len(ct) < 2:
self.error('Code country or term must have 2 or more characters length')
return CODE_INVALID_FORMAT_ERROR
code = ct if ct and len(ct) == 2 else None
term = ct if ct and len(ct) > 2 else None
try:
countries = api.countries(self.db, code=code, term=term)
self.display('countries.tmpl', countries=countries)
except (NotFoundError, InvalidValueError) as e:
self.error(str(e))
return e.code
return CMD_SUCCESS | python | def run(self, *args):
"""Show information about countries."""
params = self.parser.parse_args(args)
ct = params.code_or_term
if ct and len(ct) < 2:
self.error('Code country or term must have 2 or more characters length')
return CODE_INVALID_FORMAT_ERROR
code = ct if ct and len(ct) == 2 else None
term = ct if ct and len(ct) > 2 else None
try:
countries = api.countries(self.db, code=code, term=term)
self.display('countries.tmpl', countries=countries)
except (NotFoundError, InvalidValueError) as e:
self.error(str(e))
return e.code
return CMD_SUCCESS | [
"def",
"run",
"(",
"self",
",",
"*",
"args",
")",
":",
"params",
"=",
"self",
".",
"parser",
".",
"parse_args",
"(",
"args",
")",
"ct",
"=",
"params",
".",
"code_or_term",
"if",
"ct",
"and",
"len",
"(",
"ct",
")",
"<",
"2",
":",
"self",
".",
"e... | Show information about countries. | [
"Show",
"information",
"about",
"countries",
"."
] | 391cd37a75fea26311dc6908bc1c953c540a8e04 | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/cmd/countries.py#L64-L85 | train | 25,658 |
rigetti/rpcq | rpcq/_client.py | Client._call_async | async def _call_async(self, method_name: str, *args, **kwargs):
"""
Sends a request to the socket and then wait for the reply.
To deal with multiple, asynchronous requests we do not expect that the receive reply task
scheduled from this call is the one that receives this call's reply and instead rely on
Events to signal across multiple _async_call/_recv_reply tasks.
"""
request = utils.rpc_request(method_name, *args, **kwargs)
_log.debug("Sending request: %s", request)
# setup an event to notify us when the reply is received (potentially by a task scheduled by
# another call to _async_call). we do this before we send the request to catch the case
# where the reply comes back before we re-enter this thread
self._events[request.id] = asyncio.Event()
# schedule a task to receive the reply to ensure we have a task to receive the reply
asyncio.ensure_future(self._recv_reply())
await self._async_socket.send_multipart([to_msgpack(request)])
await self._events[request.id].wait()
reply = self._replies.pop(request.id)
if isinstance(reply, RPCError):
raise utils.RPCError(reply.error)
else:
return reply.result | python | async def _call_async(self, method_name: str, *args, **kwargs):
"""
Sends a request to the socket and then wait for the reply.
To deal with multiple, asynchronous requests we do not expect that the receive reply task
scheduled from this call is the one that receives this call's reply and instead rely on
Events to signal across multiple _async_call/_recv_reply tasks.
"""
request = utils.rpc_request(method_name, *args, **kwargs)
_log.debug("Sending request: %s", request)
# setup an event to notify us when the reply is received (potentially by a task scheduled by
# another call to _async_call). we do this before we send the request to catch the case
# where the reply comes back before we re-enter this thread
self._events[request.id] = asyncio.Event()
# schedule a task to receive the reply to ensure we have a task to receive the reply
asyncio.ensure_future(self._recv_reply())
await self._async_socket.send_multipart([to_msgpack(request)])
await self._events[request.id].wait()
reply = self._replies.pop(request.id)
if isinstance(reply, RPCError):
raise utils.RPCError(reply.error)
else:
return reply.result | [
"async",
"def",
"_call_async",
"(",
"self",
",",
"method_name",
":",
"str",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"request",
"=",
"utils",
".",
"rpc_request",
"(",
"method_name",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"_log",
... | Sends a request to the socket and then wait for the reply.
To deal with multiple, asynchronous requests we do not expect that the receive reply task
scheduled from this call is the one that receives this call's reply and instead rely on
Events to signal across multiple _async_call/_recv_reply tasks. | [
"Sends",
"a",
"request",
"to",
"the",
"socket",
"and",
"then",
"wait",
"for",
"the",
"reply",
"."
] | 9091e3541c4419d7ab882bb32a8b86aa85cedb6f | https://github.com/rigetti/rpcq/blob/9091e3541c4419d7ab882bb32a8b86aa85cedb6f/rpcq/_client.py#L97-L123 | train | 25,659 |
rigetti/rpcq | rpcq/_client.py | Client._recv_reply | async def _recv_reply(self):
"""
Helper task to recieve a reply store the result and trigger the associated event.
"""
raw_reply, = await self._async_socket.recv_multipart()
reply = from_msgpack(raw_reply)
_log.debug("Received reply: %s", reply)
self._replies[reply.id] = reply
self._events.pop(reply.id).set() | python | async def _recv_reply(self):
"""
Helper task to recieve a reply store the result and trigger the associated event.
"""
raw_reply, = await self._async_socket.recv_multipart()
reply = from_msgpack(raw_reply)
_log.debug("Received reply: %s", reply)
self._replies[reply.id] = reply
self._events.pop(reply.id).set() | [
"async",
"def",
"_recv_reply",
"(",
"self",
")",
":",
"raw_reply",
",",
"=",
"await",
"self",
".",
"_async_socket",
".",
"recv_multipart",
"(",
")",
"reply",
"=",
"from_msgpack",
"(",
"raw_reply",
")",
"_log",
".",
"debug",
"(",
"\"Received reply: %s\"",
","... | Helper task to recieve a reply store the result and trigger the associated event. | [
"Helper",
"task",
"to",
"recieve",
"a",
"reply",
"store",
"the",
"result",
"and",
"trigger",
"the",
"associated",
"event",
"."
] | 9091e3541c4419d7ab882bb32a8b86aa85cedb6f | https://github.com/rigetti/rpcq/blob/9091e3541c4419d7ab882bb32a8b86aa85cedb6f/rpcq/_client.py#L125-L133 | train | 25,660 |
rigetti/rpcq | rpcq/_client.py | Client.call | def call(self, method_name: str, *args, rpc_timeout: float = None, **kwargs):
"""
Send JSON RPC request to a backend socket and receive reply
Note that this uses the default event loop to run in a blocking manner. If you would rather run in an async
fashion or provide your own event loop then use .async_call instead
:param method_name: Method name
:param args: Args that will be passed to the remote function
:param float rpc_timeout: Timeout in seconds for Server response, set to None to disable the timeout
:param kwargs: Keyword args that will be passed to the remote function
"""
request = utils.rpc_request(method_name, *args, **kwargs)
_log.debug("Sending request: %s", request)
self._socket.send_multipart([to_msgpack(request)])
# if an rpc_timeout override is not specified, use the one set in the Client attributes
if rpc_timeout is None:
rpc_timeout = self.rpc_timeout
start_time = time.time()
while True:
# Need to keep track of timeout manually in case this loop runs more than once. We subtract off already
# elapsed time from the timeout. The call to max is to make sure we don't send a negative value
# which would throw an error.
timeout = max((start_time + rpc_timeout - time.time()) * 1000, 0) if rpc_timeout is not None else None
if self._socket.poll(timeout) == 0:
raise TimeoutError(f"Timeout on client {self.endpoint}, method name {method_name}, class info: {self}")
raw_reply, = self._socket.recv_multipart()
reply = from_msgpack(raw_reply)
_log.debug("Received reply: %s", reply)
# there's a possibility that the socket will have some leftover replies from a previous
# request on it if that .call() was cancelled or timed out. Therefore, we need to discard replies that
# don't match the request just like in the call_async case.
if reply.id == request.id:
break
else:
_log.debug('Discarding reply: %s', reply)
for warning in reply.warnings:
warn(f"{warning.kind}: {warning.body}")
if isinstance(reply, RPCError):
raise utils.RPCError(reply.error)
else:
return reply.result | python | def call(self, method_name: str, *args, rpc_timeout: float = None, **kwargs):
"""
Send JSON RPC request to a backend socket and receive reply
Note that this uses the default event loop to run in a blocking manner. If you would rather run in an async
fashion or provide your own event loop then use .async_call instead
:param method_name: Method name
:param args: Args that will be passed to the remote function
:param float rpc_timeout: Timeout in seconds for Server response, set to None to disable the timeout
:param kwargs: Keyword args that will be passed to the remote function
"""
request = utils.rpc_request(method_name, *args, **kwargs)
_log.debug("Sending request: %s", request)
self._socket.send_multipart([to_msgpack(request)])
# if an rpc_timeout override is not specified, use the one set in the Client attributes
if rpc_timeout is None:
rpc_timeout = self.rpc_timeout
start_time = time.time()
while True:
# Need to keep track of timeout manually in case this loop runs more than once. We subtract off already
# elapsed time from the timeout. The call to max is to make sure we don't send a negative value
# which would throw an error.
timeout = max((start_time + rpc_timeout - time.time()) * 1000, 0) if rpc_timeout is not None else None
if self._socket.poll(timeout) == 0:
raise TimeoutError(f"Timeout on client {self.endpoint}, method name {method_name}, class info: {self}")
raw_reply, = self._socket.recv_multipart()
reply = from_msgpack(raw_reply)
_log.debug("Received reply: %s", reply)
# there's a possibility that the socket will have some leftover replies from a previous
# request on it if that .call() was cancelled or timed out. Therefore, we need to discard replies that
# don't match the request just like in the call_async case.
if reply.id == request.id:
break
else:
_log.debug('Discarding reply: %s', reply)
for warning in reply.warnings:
warn(f"{warning.kind}: {warning.body}")
if isinstance(reply, RPCError):
raise utils.RPCError(reply.error)
else:
return reply.result | [
"def",
"call",
"(",
"self",
",",
"method_name",
":",
"str",
",",
"*",
"args",
",",
"rpc_timeout",
":",
"float",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"request",
"=",
"utils",
".",
"rpc_request",
"(",
"method_name",
",",
"*",
"args",
",",
... | Send JSON RPC request to a backend socket and receive reply
Note that this uses the default event loop to run in a blocking manner. If you would rather run in an async
fashion or provide your own event loop then use .async_call instead
:param method_name: Method name
:param args: Args that will be passed to the remote function
:param float rpc_timeout: Timeout in seconds for Server response, set to None to disable the timeout
:param kwargs: Keyword args that will be passed to the remote function | [
"Send",
"JSON",
"RPC",
"request",
"to",
"a",
"backend",
"socket",
"and",
"receive",
"reply",
"Note",
"that",
"this",
"uses",
"the",
"default",
"event",
"loop",
"to",
"run",
"in",
"a",
"blocking",
"manner",
".",
"If",
"you",
"would",
"rather",
"run",
"in"... | 9091e3541c4419d7ab882bb32a8b86aa85cedb6f | https://github.com/rigetti/rpcq/blob/9091e3541c4419d7ab882bb32a8b86aa85cedb6f/rpcq/_client.py#L135-L182 | train | 25,661 |
rigetti/rpcq | rpcq/_client.py | Client.close | def close(self):
"""
Close the sockets
"""
self._socket.close()
if self._async_socket_cache:
self._async_socket_cache.close()
self._async_socket_cache = None | python | def close(self):
"""
Close the sockets
"""
self._socket.close()
if self._async_socket_cache:
self._async_socket_cache.close()
self._async_socket_cache = None | [
"def",
"close",
"(",
"self",
")",
":",
"self",
".",
"_socket",
".",
"close",
"(",
")",
"if",
"self",
".",
"_async_socket_cache",
":",
"self",
".",
"_async_socket_cache",
".",
"close",
"(",
")",
"self",
".",
"_async_socket_cache",
"=",
"None"
] | Close the sockets | [
"Close",
"the",
"sockets"
] | 9091e3541c4419d7ab882bb32a8b86aa85cedb6f | https://github.com/rigetti/rpcq/blob/9091e3541c4419d7ab882bb32a8b86aa85cedb6f/rpcq/_client.py#L184-L191 | train | 25,662 |
rigetti/rpcq | rpcq/_client.py | Client._connect_to_socket | def _connect_to_socket(self, context: zmq.Context, endpoint: str):
"""
Connect to a DEALER socket at endpoint and turn off lingering.
:param context: ZMQ Context to use (potentially async)
:param endpoint: Endpoint
:return: Connected socket
"""
socket = context.socket(zmq.DEALER)
socket.connect(endpoint)
socket.setsockopt(zmq.LINGER, 0)
_log.debug("Client connected to endpoint %s", self.endpoint)
return socket | python | def _connect_to_socket(self, context: zmq.Context, endpoint: str):
"""
Connect to a DEALER socket at endpoint and turn off lingering.
:param context: ZMQ Context to use (potentially async)
:param endpoint: Endpoint
:return: Connected socket
"""
socket = context.socket(zmq.DEALER)
socket.connect(endpoint)
socket.setsockopt(zmq.LINGER, 0)
_log.debug("Client connected to endpoint %s", self.endpoint)
return socket | [
"def",
"_connect_to_socket",
"(",
"self",
",",
"context",
":",
"zmq",
".",
"Context",
",",
"endpoint",
":",
"str",
")",
":",
"socket",
"=",
"context",
".",
"socket",
"(",
"zmq",
".",
"DEALER",
")",
"socket",
".",
"connect",
"(",
"endpoint",
")",
"socke... | Connect to a DEALER socket at endpoint and turn off lingering.
:param context: ZMQ Context to use (potentially async)
:param endpoint: Endpoint
:return: Connected socket | [
"Connect",
"to",
"a",
"DEALER",
"socket",
"at",
"endpoint",
"and",
"turn",
"off",
"lingering",
"."
] | 9091e3541c4419d7ab882bb32a8b86aa85cedb6f | https://github.com/rigetti/rpcq/blob/9091e3541c4419d7ab882bb32a8b86aa85cedb6f/rpcq/_client.py#L193-L205 | train | 25,663 |
rigetti/rpcq | rpcq/_client.py | Client._async_socket | def _async_socket(self):
"""
Creates a new async socket if one doesn't already exist for this Client
"""
if not self._async_socket_cache:
self._async_socket_cache = self._connect_to_socket(zmq.asyncio.Context(), self.endpoint)
return self._async_socket_cache | python | def _async_socket(self):
"""
Creates a new async socket if one doesn't already exist for this Client
"""
if not self._async_socket_cache:
self._async_socket_cache = self._connect_to_socket(zmq.asyncio.Context(), self.endpoint)
return self._async_socket_cache | [
"def",
"_async_socket",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_async_socket_cache",
":",
"self",
".",
"_async_socket_cache",
"=",
"self",
".",
"_connect_to_socket",
"(",
"zmq",
".",
"asyncio",
".",
"Context",
"(",
")",
",",
"self",
".",
"endpoi... | Creates a new async socket if one doesn't already exist for this Client | [
"Creates",
"a",
"new",
"async",
"socket",
"if",
"one",
"doesn",
"t",
"already",
"exist",
"for",
"this",
"Client"
] | 9091e3541c4419d7ab882bb32a8b86aa85cedb6f | https://github.com/rigetti/rpcq/blob/9091e3541c4419d7ab882bb32a8b86aa85cedb6f/rpcq/_client.py#L208-L215 | train | 25,664 |
rigetti/rpcq | rpcq/_server.py | Server.run | def run(self, endpoint: str, loop: AbstractEventLoop = None):
"""
Run server main task.
:param endpoint: Socket endpoint to listen to, e.g. "tcp://*:1234"
:param loop: Event loop to run server in (alternatively just use run_async method)
"""
if not loop:
loop = asyncio.get_event_loop()
try:
loop.run_until_complete(self.run_async(endpoint))
except KeyboardInterrupt:
self._shutdown() | python | def run(self, endpoint: str, loop: AbstractEventLoop = None):
"""
Run server main task.
:param endpoint: Socket endpoint to listen to, e.g. "tcp://*:1234"
:param loop: Event loop to run server in (alternatively just use run_async method)
"""
if not loop:
loop = asyncio.get_event_loop()
try:
loop.run_until_complete(self.run_async(endpoint))
except KeyboardInterrupt:
self._shutdown() | [
"def",
"run",
"(",
"self",
",",
"endpoint",
":",
"str",
",",
"loop",
":",
"AbstractEventLoop",
"=",
"None",
")",
":",
"if",
"not",
"loop",
":",
"loop",
"=",
"asyncio",
".",
"get_event_loop",
"(",
")",
"try",
":",
"loop",
".",
"run_until_complete",
"(",... | Run server main task.
:param endpoint: Socket endpoint to listen to, e.g. "tcp://*:1234"
:param loop: Event loop to run server in (alternatively just use run_async method) | [
"Run",
"server",
"main",
"task",
"."
] | 9091e3541c4419d7ab882bb32a8b86aa85cedb6f | https://github.com/rigetti/rpcq/blob/9091e3541c4419d7ab882bb32a8b86aa85cedb6f/rpcq/_server.py#L132-L145 | train | 25,665 |
rigetti/rpcq | rpcq/_server.py | Server._shutdown | def _shutdown(self):
"""
Shut down the server.
"""
for exit_handler in self._exit_handlers:
exit_handler()
if self._socket:
self._socket.close()
self._socket = None | python | def _shutdown(self):
"""
Shut down the server.
"""
for exit_handler in self._exit_handlers:
exit_handler()
if self._socket:
self._socket.close()
self._socket = None | [
"def",
"_shutdown",
"(",
"self",
")",
":",
"for",
"exit_handler",
"in",
"self",
".",
"_exit_handlers",
":",
"exit_handler",
"(",
")",
"if",
"self",
".",
"_socket",
":",
"self",
".",
"_socket",
".",
"close",
"(",
")",
"self",
".",
"_socket",
"=",
"None"... | Shut down the server. | [
"Shut",
"down",
"the",
"server",
"."
] | 9091e3541c4419d7ab882bb32a8b86aa85cedb6f | https://github.com/rigetti/rpcq/blob/9091e3541c4419d7ab882bb32a8b86aa85cedb6f/rpcq/_server.py#L153-L162 | train | 25,666 |
rigetti/rpcq | rpcq/_server.py | Server._connect | def _connect(self, endpoint: str):
"""
Connect the server to an endpoint. Creates a ZMQ ROUTER socket for the given endpoint.
:param endpoint: Socket endpoint, e.g. "tcp://*:1234"
"""
if self._socket:
raise RuntimeError('Cannot run multiple Servers on the same socket')
context = zmq.asyncio.Context()
self._socket = context.socket(zmq.ROUTER)
self._socket.bind(endpoint)
_log.info("Starting server, listening on endpoint {}".format(endpoint)) | python | def _connect(self, endpoint: str):
"""
Connect the server to an endpoint. Creates a ZMQ ROUTER socket for the given endpoint.
:param endpoint: Socket endpoint, e.g. "tcp://*:1234"
"""
if self._socket:
raise RuntimeError('Cannot run multiple Servers on the same socket')
context = zmq.asyncio.Context()
self._socket = context.socket(zmq.ROUTER)
self._socket.bind(endpoint)
_log.info("Starting server, listening on endpoint {}".format(endpoint)) | [
"def",
"_connect",
"(",
"self",
",",
"endpoint",
":",
"str",
")",
":",
"if",
"self",
".",
"_socket",
":",
"raise",
"RuntimeError",
"(",
"'Cannot run multiple Servers on the same socket'",
")",
"context",
"=",
"zmq",
".",
"asyncio",
".",
"Context",
"(",
")",
... | Connect the server to an endpoint. Creates a ZMQ ROUTER socket for the given endpoint.
:param endpoint: Socket endpoint, e.g. "tcp://*:1234" | [
"Connect",
"the",
"server",
"to",
"an",
"endpoint",
".",
"Creates",
"a",
"ZMQ",
"ROUTER",
"socket",
"for",
"the",
"given",
"endpoint",
"."
] | 9091e3541c4419d7ab882bb32a8b86aa85cedb6f | https://github.com/rigetti/rpcq/blob/9091e3541c4419d7ab882bb32a8b86aa85cedb6f/rpcq/_server.py#L164-L177 | train | 25,667 |
rigetti/rpcq | rpcq/_server.py | Server._process_request | async def _process_request(self, identity: bytes, empty_frame: list, request: RPCRequest):
"""
Executes the method specified in a JSON RPC request and then sends the reply to the socket.
:param identity: Client identity provided by ZeroMQ
:param empty_frame: Either an empty list or a single null frame depending on the client type
:param request: JSON RPC request
"""
try:
_log.debug("Client %s sent request: %s", identity, request)
start_time = datetime.now()
reply = await self.rpc_spec.run_handler(request)
if self.announce_timing:
_log.info("Request {} for {} lasted {} seconds".format(
request.id, request.method, (datetime.now() - start_time).total_seconds()))
_log.debug("Sending client %s reply: %s", identity, reply)
await self._socket.send_multipart([identity, *empty_frame, to_msgpack(reply)])
except Exception as e:
if self.serialize_exceptions:
_log.exception('Exception thrown in _process_request')
else:
raise e | python | async def _process_request(self, identity: bytes, empty_frame: list, request: RPCRequest):
"""
Executes the method specified in a JSON RPC request and then sends the reply to the socket.
:param identity: Client identity provided by ZeroMQ
:param empty_frame: Either an empty list or a single null frame depending on the client type
:param request: JSON RPC request
"""
try:
_log.debug("Client %s sent request: %s", identity, request)
start_time = datetime.now()
reply = await self.rpc_spec.run_handler(request)
if self.announce_timing:
_log.info("Request {} for {} lasted {} seconds".format(
request.id, request.method, (datetime.now() - start_time).total_seconds()))
_log.debug("Sending client %s reply: %s", identity, reply)
await self._socket.send_multipart([identity, *empty_frame, to_msgpack(reply)])
except Exception as e:
if self.serialize_exceptions:
_log.exception('Exception thrown in _process_request')
else:
raise e | [
"async",
"def",
"_process_request",
"(",
"self",
",",
"identity",
":",
"bytes",
",",
"empty_frame",
":",
"list",
",",
"request",
":",
"RPCRequest",
")",
":",
"try",
":",
"_log",
".",
"debug",
"(",
"\"Client %s sent request: %s\"",
",",
"identity",
",",
"requ... | Executes the method specified in a JSON RPC request and then sends the reply to the socket.
:param identity: Client identity provided by ZeroMQ
:param empty_frame: Either an empty list or a single null frame depending on the client type
:param request: JSON RPC request | [
"Executes",
"the",
"method",
"specified",
"in",
"a",
"JSON",
"RPC",
"request",
"and",
"then",
"sends",
"the",
"reply",
"to",
"the",
"socket",
"."
] | 9091e3541c4419d7ab882bb32a8b86aa85cedb6f | https://github.com/rigetti/rpcq/blob/9091e3541c4419d7ab882bb32a8b86aa85cedb6f/rpcq/_server.py#L179-L201 | train | 25,668 |
rigetti/rpcq | rpcq/_spec.py | RPCSpec.add_handler | def add_handler(self, f):
"""
Adds the function f to a dictionary of JSON RPC methods.
:param callable f: Method to be exposed
:return:
"""
if f.__name__.startswith('rpc_'):
raise ValueError("Server method names cannot start with rpc_.")
self._json_rpc_methods[f.__name__] = f
return f | python | def add_handler(self, f):
"""
Adds the function f to a dictionary of JSON RPC methods.
:param callable f: Method to be exposed
:return:
"""
if f.__name__.startswith('rpc_'):
raise ValueError("Server method names cannot start with rpc_.")
self._json_rpc_methods[f.__name__] = f
return f | [
"def",
"add_handler",
"(",
"self",
",",
"f",
")",
":",
"if",
"f",
".",
"__name__",
".",
"startswith",
"(",
"'rpc_'",
")",
":",
"raise",
"ValueError",
"(",
"\"Server method names cannot start with rpc_.\"",
")",
"self",
".",
"_json_rpc_methods",
"[",
"f",
".",
... | Adds the function f to a dictionary of JSON RPC methods.
:param callable f: Method to be exposed
:return: | [
"Adds",
"the",
"function",
"f",
"to",
"a",
"dictionary",
"of",
"JSON",
"RPC",
"methods",
"."
] | 9091e3541c4419d7ab882bb32a8b86aa85cedb6f | https://github.com/rigetti/rpcq/blob/9091e3541c4419d7ab882bb32a8b86aa85cedb6f/rpcq/_spec.py#L74-L84 | train | 25,669 |
rigetti/rpcq | rpcq/_spec.py | RPCSpec.get_handler | def get_handler(self, request):
"""
Get callable from JSON RPC request
:param RPCRequest request: JSON RPC request
:return: Method
:rtype: callable
"""
try:
f = self._json_rpc_methods[request.method]
except (AttributeError, KeyError): # pragma no coverage
raise RPCMethodError("Received invalid method '{}'".format(request.method))
return f | python | def get_handler(self, request):
"""
Get callable from JSON RPC request
:param RPCRequest request: JSON RPC request
:return: Method
:rtype: callable
"""
try:
f = self._json_rpc_methods[request.method]
except (AttributeError, KeyError): # pragma no coverage
raise RPCMethodError("Received invalid method '{}'".format(request.method))
return f | [
"def",
"get_handler",
"(",
"self",
",",
"request",
")",
":",
"try",
":",
"f",
"=",
"self",
".",
"_json_rpc_methods",
"[",
"request",
".",
"method",
"]",
"except",
"(",
"AttributeError",
",",
"KeyError",
")",
":",
"# pragma no coverage",
"raise",
"RPCMethodEr... | Get callable from JSON RPC request
:param RPCRequest request: JSON RPC request
:return: Method
:rtype: callable | [
"Get",
"callable",
"from",
"JSON",
"RPC",
"request"
] | 9091e3541c4419d7ab882bb32a8b86aa85cedb6f | https://github.com/rigetti/rpcq/blob/9091e3541c4419d7ab882bb32a8b86aa85cedb6f/rpcq/_spec.py#L86-L100 | train | 25,670 |
rigetti/rpcq | rpcq/_spec.py | RPCSpec.run_handler | async def run_handler(self, request: RPCRequest) -> Union[RPCReply, RPCError]:
"""
Process a JSON RPC request
:param RPCRequest request: JSON RPC request
:return: JSON RPC reply
"""
with catch_warnings(record=True) as warnings:
try:
rpc_handler = self.get_handler(request)
except RPCMethodError as e:
return rpc_error(request.id, str(e), warnings=warnings)
try:
# Run RPC and get result
args, kwargs = get_input(request.params)
result = rpc_handler(*args, **kwargs)
if asyncio.iscoroutine(result):
result = await result
except Exception as e:
if self.serialize_exceptions:
_traceback = traceback.format_exc()
_log.error(_traceback)
if self.provide_tracebacks:
return rpc_error(request.id, "{}\n{}".format(str(e), _traceback),
warnings=warnings)
else:
return rpc_error(request.id, str(e), warnings=warnings)
else:
raise e
return rpc_reply(request.id, result, warnings=warnings) | python | async def run_handler(self, request: RPCRequest) -> Union[RPCReply, RPCError]:
"""
Process a JSON RPC request
:param RPCRequest request: JSON RPC request
:return: JSON RPC reply
"""
with catch_warnings(record=True) as warnings:
try:
rpc_handler = self.get_handler(request)
except RPCMethodError as e:
return rpc_error(request.id, str(e), warnings=warnings)
try:
# Run RPC and get result
args, kwargs = get_input(request.params)
result = rpc_handler(*args, **kwargs)
if asyncio.iscoroutine(result):
result = await result
except Exception as e:
if self.serialize_exceptions:
_traceback = traceback.format_exc()
_log.error(_traceback)
if self.provide_tracebacks:
return rpc_error(request.id, "{}\n{}".format(str(e), _traceback),
warnings=warnings)
else:
return rpc_error(request.id, str(e), warnings=warnings)
else:
raise e
return rpc_reply(request.id, result, warnings=warnings) | [
"async",
"def",
"run_handler",
"(",
"self",
",",
"request",
":",
"RPCRequest",
")",
"->",
"Union",
"[",
"RPCReply",
",",
"RPCError",
"]",
":",
"with",
"catch_warnings",
"(",
"record",
"=",
"True",
")",
"as",
"warnings",
":",
"try",
":",
"rpc_handler",
"=... | Process a JSON RPC request
:param RPCRequest request: JSON RPC request
:return: JSON RPC reply | [
"Process",
"a",
"JSON",
"RPC",
"request"
] | 9091e3541c4419d7ab882bb32a8b86aa85cedb6f | https://github.com/rigetti/rpcq/blob/9091e3541c4419d7ab882bb32a8b86aa85cedb6f/rpcq/_spec.py#L102-L135 | train | 25,671 |
rigetti/rpcq | rpcq/_utils.py | rpc_request | def rpc_request(method_name: str, *args, **kwargs) -> rpcq.messages.RPCRequest:
"""
Create RPC request
:param method_name: Method name
:param args: Positional arguments
:param kwargs: Keyword arguments
:return: JSON RPC formatted dict
"""
if args:
kwargs['*args'] = args
return rpcq.messages.RPCRequest(
jsonrpc='2.0',
id=str(uuid.uuid4()),
method=method_name,
params=kwargs
) | python | def rpc_request(method_name: str, *args, **kwargs) -> rpcq.messages.RPCRequest:
"""
Create RPC request
:param method_name: Method name
:param args: Positional arguments
:param kwargs: Keyword arguments
:return: JSON RPC formatted dict
"""
if args:
kwargs['*args'] = args
return rpcq.messages.RPCRequest(
jsonrpc='2.0',
id=str(uuid.uuid4()),
method=method_name,
params=kwargs
) | [
"def",
"rpc_request",
"(",
"method_name",
":",
"str",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"->",
"rpcq",
".",
"messages",
".",
"RPCRequest",
":",
"if",
"args",
":",
"kwargs",
"[",
"'*args'",
"]",
"=",
"args",
"return",
"rpcq",
".",
"messag... | Create RPC request
:param method_name: Method name
:param args: Positional arguments
:param kwargs: Keyword arguments
:return: JSON RPC formatted dict | [
"Create",
"RPC",
"request"
] | 9091e3541c4419d7ab882bb32a8b86aa85cedb6f | https://github.com/rigetti/rpcq/blob/9091e3541c4419d7ab882bb32a8b86aa85cedb6f/rpcq/_utils.py#L28-L45 | train | 25,672 |
rigetti/rpcq | rpcq/_utils.py | rpc_reply | def rpc_reply(id: Union[str, int], result: Optional[object],
warnings: Optional[List[Warning]] = None) -> rpcq.messages.RPCReply:
"""
Create RPC reply
:param str|int id: Request ID
:param result: Result
:param warnings: List of warnings to attach to the message
:return: JSON RPC formatted dict
"""
warnings = warnings or []
return rpcq.messages.RPCReply(
jsonrpc='2.0',
id=id,
result=result,
warnings=[rpc_warning(warning) for warning in warnings]
) | python | def rpc_reply(id: Union[str, int], result: Optional[object],
warnings: Optional[List[Warning]] = None) -> rpcq.messages.RPCReply:
"""
Create RPC reply
:param str|int id: Request ID
:param result: Result
:param warnings: List of warnings to attach to the message
:return: JSON RPC formatted dict
"""
warnings = warnings or []
return rpcq.messages.RPCReply(
jsonrpc='2.0',
id=id,
result=result,
warnings=[rpc_warning(warning) for warning in warnings]
) | [
"def",
"rpc_reply",
"(",
"id",
":",
"Union",
"[",
"str",
",",
"int",
"]",
",",
"result",
":",
"Optional",
"[",
"object",
"]",
",",
"warnings",
":",
"Optional",
"[",
"List",
"[",
"Warning",
"]",
"]",
"=",
"None",
")",
"->",
"rpcq",
".",
"messages",
... | Create RPC reply
:param str|int id: Request ID
:param result: Result
:param warnings: List of warnings to attach to the message
:return: JSON RPC formatted dict | [
"Create",
"RPC",
"reply"
] | 9091e3541c4419d7ab882bb32a8b86aa85cedb6f | https://github.com/rigetti/rpcq/blob/9091e3541c4419d7ab882bb32a8b86aa85cedb6f/rpcq/_utils.py#L48-L65 | train | 25,673 |
rigetti/rpcq | rpcq/_utils.py | rpc_error | def rpc_error(id: Union[str, int], error_msg: str,
warnings: List[Any] = []) -> rpcq.messages.RPCError:
"""
Create RPC error
:param id: Request ID
:param error_msg: Error message
:param warning: List of warnings to attach to the message
:return: JSON RPC formatted dict
"""
return rpcq.messages.RPCError(
jsonrpc='2.0',
id=id,
error=error_msg,
warnings=[rpc_warning(warning) for warning in warnings]) | python | def rpc_error(id: Union[str, int], error_msg: str,
warnings: List[Any] = []) -> rpcq.messages.RPCError:
"""
Create RPC error
:param id: Request ID
:param error_msg: Error message
:param warning: List of warnings to attach to the message
:return: JSON RPC formatted dict
"""
return rpcq.messages.RPCError(
jsonrpc='2.0',
id=id,
error=error_msg,
warnings=[rpc_warning(warning) for warning in warnings]) | [
"def",
"rpc_error",
"(",
"id",
":",
"Union",
"[",
"str",
",",
"int",
"]",
",",
"error_msg",
":",
"str",
",",
"warnings",
":",
"List",
"[",
"Any",
"]",
"=",
"[",
"]",
")",
"->",
"rpcq",
".",
"messages",
".",
"RPCError",
":",
"return",
"rpcq",
".",... | Create RPC error
:param id: Request ID
:param error_msg: Error message
:param warning: List of warnings to attach to the message
:return: JSON RPC formatted dict | [
"Create",
"RPC",
"error"
] | 9091e3541c4419d7ab882bb32a8b86aa85cedb6f | https://github.com/rigetti/rpcq/blob/9091e3541c4419d7ab882bb32a8b86aa85cedb6f/rpcq/_utils.py#L68-L82 | train | 25,674 |
rigetti/rpcq | rpcq/_utils.py | get_input | def get_input(params: Union[dict, list]) -> Tuple[list, dict]:
"""
Get positional or keyword arguments from JSON RPC params
:param params: Parameters passed through JSON RPC
:return: args, kwargs
"""
# Backwards compatibility for old clients that send params as a list
if isinstance(params, list):
args = params
kwargs = {}
elif isinstance(params, dict):
args = params.pop('*args', [])
kwargs = params
else: # pragma no coverage
raise TypeError(
'Unknown type {} of params, must be list or dict'.format(type(params)))
return args, kwargs | python | def get_input(params: Union[dict, list]) -> Tuple[list, dict]:
"""
Get positional or keyword arguments from JSON RPC params
:param params: Parameters passed through JSON RPC
:return: args, kwargs
"""
# Backwards compatibility for old clients that send params as a list
if isinstance(params, list):
args = params
kwargs = {}
elif isinstance(params, dict):
args = params.pop('*args', [])
kwargs = params
else: # pragma no coverage
raise TypeError(
'Unknown type {} of params, must be list or dict'.format(type(params)))
return args, kwargs | [
"def",
"get_input",
"(",
"params",
":",
"Union",
"[",
"dict",
",",
"list",
"]",
")",
"->",
"Tuple",
"[",
"list",
",",
"dict",
"]",
":",
"# Backwards compatibility for old clients that send params as a list",
"if",
"isinstance",
"(",
"params",
",",
"list",
")",
... | Get positional or keyword arguments from JSON RPC params
:param params: Parameters passed through JSON RPC
:return: args, kwargs | [
"Get",
"positional",
"or",
"keyword",
"arguments",
"from",
"JSON",
"RPC",
"params"
] | 9091e3541c4419d7ab882bb32a8b86aa85cedb6f | https://github.com/rigetti/rpcq/blob/9091e3541c4419d7ab882bb32a8b86aa85cedb6f/rpcq/_utils.py#L85-L103 | train | 25,675 |
rigetti/rpcq | rpcq/_base.py | repr_value | def repr_value(value):
"""
Represent a value in human readable form. For long list's this truncates the printed
representation.
:param value: The value to represent.
:return: A string representation.
:rtype: basestring
"""
if isinstance(value, list) and len(value) > REPR_LIST_TRUNCATION:
return "[{},...]".format(", ".join(map(repr, value[:REPR_LIST_TRUNCATION])))
else:
return repr(value) | python | def repr_value(value):
"""
Represent a value in human readable form. For long list's this truncates the printed
representation.
:param value: The value to represent.
:return: A string representation.
:rtype: basestring
"""
if isinstance(value, list) and len(value) > REPR_LIST_TRUNCATION:
return "[{},...]".format(", ".join(map(repr, value[:REPR_LIST_TRUNCATION])))
else:
return repr(value) | [
"def",
"repr_value",
"(",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"list",
")",
"and",
"len",
"(",
"value",
")",
">",
"REPR_LIST_TRUNCATION",
":",
"return",
"\"[{},...]\"",
".",
"format",
"(",
"\", \"",
".",
"join",
"(",
"map",
"(",
"r... | Represent a value in human readable form. For long list's this truncates the printed
representation.
:param value: The value to represent.
:return: A string representation.
:rtype: basestring | [
"Represent",
"a",
"value",
"in",
"human",
"readable",
"form",
".",
"For",
"long",
"list",
"s",
"this",
"truncates",
"the",
"printed",
"representation",
"."
] | 9091e3541c4419d7ab882bb32a8b86aa85cedb6f | https://github.com/rigetti/rpcq/blob/9091e3541c4419d7ab882bb32a8b86aa85cedb6f/rpcq/_base.py#L28-L40 | train | 25,676 |
klen/graphite-beacon | graphite_beacon/alerts.py | AlertFabric.get | def get(cls, reactor, source='graphite', **options):
"""Get Alert Class by source."""
acls = cls.alerts[source]
return acls(reactor, **options) | python | def get(cls, reactor, source='graphite', **options):
"""Get Alert Class by source."""
acls = cls.alerts[source]
return acls(reactor, **options) | [
"def",
"get",
"(",
"cls",
",",
"reactor",
",",
"source",
"=",
"'graphite'",
",",
"*",
"*",
"options",
")",
":",
"acls",
"=",
"cls",
".",
"alerts",
"[",
"source",
"]",
"return",
"acls",
"(",
"reactor",
",",
"*",
"*",
"options",
")"
] | Get Alert Class by source. | [
"Get",
"Alert",
"Class",
"by",
"source",
"."
] | c1f071e9f557693bc90f6acbc314994985dc3b77 | https://github.com/klen/graphite-beacon/blob/c1f071e9f557693bc90f6acbc314994985dc3b77/graphite_beacon/alerts.py#L52-L55 | train | 25,677 |
klen/graphite-beacon | graphite_beacon/alerts.py | BaseAlert.convert | def convert(self, value):
"""Convert self value."""
try:
return convert_to_format(value, self._format)
except (ValueError, TypeError):
return value | python | def convert(self, value):
"""Convert self value."""
try:
return convert_to_format(value, self._format)
except (ValueError, TypeError):
return value | [
"def",
"convert",
"(",
"self",
",",
"value",
")",
":",
"try",
":",
"return",
"convert_to_format",
"(",
"value",
",",
"self",
".",
"_format",
")",
"except",
"(",
"ValueError",
",",
"TypeError",
")",
":",
"return",
"value"
] | Convert self value. | [
"Convert",
"self",
"value",
"."
] | c1f071e9f557693bc90f6acbc314994985dc3b77 | https://github.com/klen/graphite-beacon/blob/c1f071e9f557693bc90f6acbc314994985dc3b77/graphite_beacon/alerts.py#L144-L149 | train | 25,678 |
klen/graphite-beacon | graphite_beacon/alerts.py | BaseAlert.check | def check(self, records):
"""Check current value."""
for value, target in records:
LOGGER.info("%s [%s]: %s", self.name, target, value)
if value is None:
self.notify(self.no_data, value, target)
continue
for rule in self.rules:
if self.evaluate_rule(rule, value, target):
self.notify(rule['level'], value, target, rule=rule)
break
else:
self.notify('normal', value, target, rule=rule)
self.history[target].append(value) | python | def check(self, records):
"""Check current value."""
for value, target in records:
LOGGER.info("%s [%s]: %s", self.name, target, value)
if value is None:
self.notify(self.no_data, value, target)
continue
for rule in self.rules:
if self.evaluate_rule(rule, value, target):
self.notify(rule['level'], value, target, rule=rule)
break
else:
self.notify('normal', value, target, rule=rule)
self.history[target].append(value) | [
"def",
"check",
"(",
"self",
",",
"records",
")",
":",
"for",
"value",
",",
"target",
"in",
"records",
":",
"LOGGER",
".",
"info",
"(",
"\"%s [%s]: %s\"",
",",
"self",
".",
"name",
",",
"target",
",",
"value",
")",
"if",
"value",
"is",
"None",
":",
... | Check current value. | [
"Check",
"current",
"value",
"."
] | c1f071e9f557693bc90f6acbc314994985dc3b77 | https://github.com/klen/graphite-beacon/blob/c1f071e9f557693bc90f6acbc314994985dc3b77/graphite_beacon/alerts.py#L168-L182 | train | 25,679 |
klen/graphite-beacon | graphite_beacon/alerts.py | BaseAlert.evaluate_rule | def evaluate_rule(self, rule, value, target):
"""Calculate the value."""
def evaluate(expr):
if expr in LOGICAL_OPERATORS.values():
return expr
rvalue = self.get_value_for_expr(expr, target)
if rvalue is None:
return False # ignore this result
return expr['op'](value, rvalue)
evaluated = [evaluate(expr) for expr in rule['exprs']]
while len(evaluated) > 1:
lhs, logical_op, rhs = (evaluated.pop(0) for _ in range(3))
evaluated.insert(0, logical_op(lhs, rhs))
return evaluated[0] | python | def evaluate_rule(self, rule, value, target):
"""Calculate the value."""
def evaluate(expr):
if expr in LOGICAL_OPERATORS.values():
return expr
rvalue = self.get_value_for_expr(expr, target)
if rvalue is None:
return False # ignore this result
return expr['op'](value, rvalue)
evaluated = [evaluate(expr) for expr in rule['exprs']]
while len(evaluated) > 1:
lhs, logical_op, rhs = (evaluated.pop(0) for _ in range(3))
evaluated.insert(0, logical_op(lhs, rhs))
return evaluated[0] | [
"def",
"evaluate_rule",
"(",
"self",
",",
"rule",
",",
"value",
",",
"target",
")",
":",
"def",
"evaluate",
"(",
"expr",
")",
":",
"if",
"expr",
"in",
"LOGICAL_OPERATORS",
".",
"values",
"(",
")",
":",
"return",
"expr",
"rvalue",
"=",
"self",
".",
"g... | Calculate the value. | [
"Calculate",
"the",
"value",
"."
] | c1f071e9f557693bc90f6acbc314994985dc3b77 | https://github.com/klen/graphite-beacon/blob/c1f071e9f557693bc90f6acbc314994985dc3b77/graphite_beacon/alerts.py#L184-L199 | train | 25,680 |
klen/graphite-beacon | graphite_beacon/alerts.py | BaseAlert.get_value_for_expr | def get_value_for_expr(self, expr, target):
"""I have no idea."""
if expr in LOGICAL_OPERATORS.values():
return None
rvalue = expr['value']
if rvalue == HISTORICAL:
history = self.history[target]
if len(history) < self.history_size:
return None
rvalue = sum(history) / float(len(history))
rvalue = expr['mod'](rvalue)
return rvalue | python | def get_value_for_expr(self, expr, target):
"""I have no idea."""
if expr in LOGICAL_OPERATORS.values():
return None
rvalue = expr['value']
if rvalue == HISTORICAL:
history = self.history[target]
if len(history) < self.history_size:
return None
rvalue = sum(history) / float(len(history))
rvalue = expr['mod'](rvalue)
return rvalue | [
"def",
"get_value_for_expr",
"(",
"self",
",",
"expr",
",",
"target",
")",
":",
"if",
"expr",
"in",
"LOGICAL_OPERATORS",
".",
"values",
"(",
")",
":",
"return",
"None",
"rvalue",
"=",
"expr",
"[",
"'value'",
"]",
"if",
"rvalue",
"==",
"HISTORICAL",
":",
... | I have no idea. | [
"I",
"have",
"no",
"idea",
"."
] | c1f071e9f557693bc90f6acbc314994985dc3b77 | https://github.com/klen/graphite-beacon/blob/c1f071e9f557693bc90f6acbc314994985dc3b77/graphite_beacon/alerts.py#L201-L213 | train | 25,681 |
klen/graphite-beacon | graphite_beacon/alerts.py | BaseAlert.notify | def notify(self, level, value, target=None, ntype=None, rule=None):
"""Notify main reactor about event."""
# Did we see the event before?
if target in self.state and level == self.state[target]:
return False
# Do we see the event first time?
if target not in self.state and level == 'normal' \
and not self.reactor.options['send_initial']:
return False
self.state[target] = level
return self.reactor.notify(level, self, value, target=target, ntype=ntype, rule=rule) | python | def notify(self, level, value, target=None, ntype=None, rule=None):
"""Notify main reactor about event."""
# Did we see the event before?
if target in self.state and level == self.state[target]:
return False
# Do we see the event first time?
if target not in self.state and level == 'normal' \
and not self.reactor.options['send_initial']:
return False
self.state[target] = level
return self.reactor.notify(level, self, value, target=target, ntype=ntype, rule=rule) | [
"def",
"notify",
"(",
"self",
",",
"level",
",",
"value",
",",
"target",
"=",
"None",
",",
"ntype",
"=",
"None",
",",
"rule",
"=",
"None",
")",
":",
"# Did we see the event before?",
"if",
"target",
"in",
"self",
".",
"state",
"and",
"level",
"==",
"se... | Notify main reactor about event. | [
"Notify",
"main",
"reactor",
"about",
"event",
"."
] | c1f071e9f557693bc90f6acbc314994985dc3b77 | https://github.com/klen/graphite-beacon/blob/c1f071e9f557693bc90f6acbc314994985dc3b77/graphite_beacon/alerts.py#L215-L227 | train | 25,682 |
klen/graphite-beacon | graphite_beacon/alerts.py | GraphiteAlert.load | def load(self):
"""Load data from Graphite."""
LOGGER.debug('%s: start checking: %s', self.name, self.query)
if self.waiting:
self.notify('warning', 'Process takes too much time', target='waiting', ntype='common')
else:
self.waiting = True
try:
response = yield self.client.fetch(self.url, auth_username=self.auth_username,
auth_password=self.auth_password,
request_timeout=self.request_timeout,
connect_timeout=self.connect_timeout,
validate_cert=self.validate_cert)
records = (
GraphiteRecord(line, self.default_nan_value, self.ignore_nan)
for line in response.buffer)
data = [
(None if record.empty else getattr(record, self.method), record.target)
for record in records]
if len(data) == 0:
raise ValueError('No data')
self.check(data)
self.notify('normal', 'Metrics are loaded', target='loading', ntype='common')
except Exception as e:
self.notify(
self.loading_error, 'Loading error: %s' % e, target='loading', ntype='common')
self.waiting = False | python | def load(self):
"""Load data from Graphite."""
LOGGER.debug('%s: start checking: %s', self.name, self.query)
if self.waiting:
self.notify('warning', 'Process takes too much time', target='waiting', ntype='common')
else:
self.waiting = True
try:
response = yield self.client.fetch(self.url, auth_username=self.auth_username,
auth_password=self.auth_password,
request_timeout=self.request_timeout,
connect_timeout=self.connect_timeout,
validate_cert=self.validate_cert)
records = (
GraphiteRecord(line, self.default_nan_value, self.ignore_nan)
for line in response.buffer)
data = [
(None if record.empty else getattr(record, self.method), record.target)
for record in records]
if len(data) == 0:
raise ValueError('No data')
self.check(data)
self.notify('normal', 'Metrics are loaded', target='loading', ntype='common')
except Exception as e:
self.notify(
self.loading_error, 'Loading error: %s' % e, target='loading', ntype='common')
self.waiting = False | [
"def",
"load",
"(",
"self",
")",
":",
"LOGGER",
".",
"debug",
"(",
"'%s: start checking: %s'",
",",
"self",
".",
"name",
",",
"self",
".",
"query",
")",
"if",
"self",
".",
"waiting",
":",
"self",
".",
"notify",
"(",
"'warning'",
",",
"'Process takes too ... | Load data from Graphite. | [
"Load",
"data",
"from",
"Graphite",
"."
] | c1f071e9f557693bc90f6acbc314994985dc3b77 | https://github.com/klen/graphite-beacon/blob/c1f071e9f557693bc90f6acbc314994985dc3b77/graphite_beacon/alerts.py#L259-L285 | train | 25,683 |
klen/graphite-beacon | graphite_beacon/alerts.py | GraphiteAlert.get_graph_url | def get_graph_url(self, target, graphite_url=None):
"""Get Graphite URL."""
return self._graphite_url(target, graphite_url=graphite_url, raw_data=False) | python | def get_graph_url(self, target, graphite_url=None):
"""Get Graphite URL."""
return self._graphite_url(target, graphite_url=graphite_url, raw_data=False) | [
"def",
"get_graph_url",
"(",
"self",
",",
"target",
",",
"graphite_url",
"=",
"None",
")",
":",
"return",
"self",
".",
"_graphite_url",
"(",
"target",
",",
"graphite_url",
"=",
"graphite_url",
",",
"raw_data",
"=",
"False",
")"
] | Get Graphite URL. | [
"Get",
"Graphite",
"URL",
"."
] | c1f071e9f557693bc90f6acbc314994985dc3b77 | https://github.com/klen/graphite-beacon/blob/c1f071e9f557693bc90f6acbc314994985dc3b77/graphite_beacon/alerts.py#L287-L289 | train | 25,684 |
klen/graphite-beacon | graphite_beacon/alerts.py | GraphiteAlert._graphite_url | def _graphite_url(self, query, raw_data=False, graphite_url=None):
"""Build Graphite URL."""
query = escape.url_escape(query)
graphite_url = graphite_url or self.reactor.options.get('public_graphite_url')
url = "{base}/render/?target={query}&from=-{from_time}&until=-{until}".format(
base=graphite_url, query=query,
from_time=self.from_time.as_graphite(),
until=self.until.as_graphite(),
)
if raw_data:
url = "{}&format=raw".format(url)
return url | python | def _graphite_url(self, query, raw_data=False, graphite_url=None):
"""Build Graphite URL."""
query = escape.url_escape(query)
graphite_url = graphite_url or self.reactor.options.get('public_graphite_url')
url = "{base}/render/?target={query}&from=-{from_time}&until=-{until}".format(
base=graphite_url, query=query,
from_time=self.from_time.as_graphite(),
until=self.until.as_graphite(),
)
if raw_data:
url = "{}&format=raw".format(url)
return url | [
"def",
"_graphite_url",
"(",
"self",
",",
"query",
",",
"raw_data",
"=",
"False",
",",
"graphite_url",
"=",
"None",
")",
":",
"query",
"=",
"escape",
".",
"url_escape",
"(",
"query",
")",
"graphite_url",
"=",
"graphite_url",
"or",
"self",
".",
"reactor",
... | Build Graphite URL. | [
"Build",
"Graphite",
"URL",
"."
] | c1f071e9f557693bc90f6acbc314994985dc3b77 | https://github.com/klen/graphite-beacon/blob/c1f071e9f557693bc90f6acbc314994985dc3b77/graphite_beacon/alerts.py#L291-L303 | train | 25,685 |
klen/graphite-beacon | graphite_beacon/alerts.py | URLAlert.load | def load(self):
"""Load URL."""
LOGGER.debug('%s: start checking: %s', self.name, self.query)
if self.waiting:
self.notify('warning', 'Process takes too much time', target='waiting', ntype='common')
else:
self.waiting = True
try:
response = yield self.client.fetch(
self.query, method=self.options.get('method', 'GET'),
request_timeout=self.request_timeout,
connect_timeout=self.connect_timeout,
validate_cert=self.options.get('validate_cert', True))
self.check([(self.get_data(response), self.query)])
self.notify('normal', 'Metrics are loaded', target='loading', ntype='common')
except Exception as e:
self.notify('critical', str(e), target='loading', ntype='common')
self.waiting = False | python | def load(self):
"""Load URL."""
LOGGER.debug('%s: start checking: %s', self.name, self.query)
if self.waiting:
self.notify('warning', 'Process takes too much time', target='waiting', ntype='common')
else:
self.waiting = True
try:
response = yield self.client.fetch(
self.query, method=self.options.get('method', 'GET'),
request_timeout=self.request_timeout,
connect_timeout=self.connect_timeout,
validate_cert=self.options.get('validate_cert', True))
self.check([(self.get_data(response), self.query)])
self.notify('normal', 'Metrics are loaded', target='loading', ntype='common')
except Exception as e:
self.notify('critical', str(e), target='loading', ntype='common')
self.waiting = False | [
"def",
"load",
"(",
"self",
")",
":",
"LOGGER",
".",
"debug",
"(",
"'%s: start checking: %s'",
",",
"self",
".",
"name",
",",
"self",
".",
"query",
")",
"if",
"self",
".",
"waiting",
":",
"self",
".",
"notify",
"(",
"'warning'",
",",
"'Process takes too ... | Load URL. | [
"Load",
"URL",
"."
] | c1f071e9f557693bc90f6acbc314994985dc3b77 | https://github.com/klen/graphite-beacon/blob/c1f071e9f557693bc90f6acbc314994985dc3b77/graphite_beacon/alerts.py#L318-L337 | train | 25,686 |
klen/graphite-beacon | graphite_beacon/core.py | _get_loader | def _get_loader(config):
"""Determine which config file type and loader to use based on a filename.
:param config str: filename to config file
:return: a tuple of the loader type and callable to load
:rtype: (str, Callable)
"""
if config.endswith('.yml') or config.endswith('.yaml'):
if not yaml:
LOGGER.error("pyyaml must be installed to use the YAML loader")
# TODO: stop reactor if running
return None, None
return 'yaml', yaml.load
else:
return 'json', json.loads | python | def _get_loader(config):
"""Determine which config file type and loader to use based on a filename.
:param config str: filename to config file
:return: a tuple of the loader type and callable to load
:rtype: (str, Callable)
"""
if config.endswith('.yml') or config.endswith('.yaml'):
if not yaml:
LOGGER.error("pyyaml must be installed to use the YAML loader")
# TODO: stop reactor if running
return None, None
return 'yaml', yaml.load
else:
return 'json', json.loads | [
"def",
"_get_loader",
"(",
"config",
")",
":",
"if",
"config",
".",
"endswith",
"(",
"'.yml'",
")",
"or",
"config",
".",
"endswith",
"(",
"'.yaml'",
")",
":",
"if",
"not",
"yaml",
":",
"LOGGER",
".",
"error",
"(",
"\"pyyaml must be installed to use the YAML ... | Determine which config file type and loader to use based on a filename.
:param config str: filename to config file
:return: a tuple of the loader type and callable to load
:rtype: (str, Callable) | [
"Determine",
"which",
"config",
"file",
"type",
"and",
"loader",
"to",
"use",
"based",
"on",
"a",
"filename",
"."
] | c1f071e9f557693bc90f6acbc314994985dc3b77 | https://github.com/klen/graphite-beacon/blob/c1f071e9f557693bc90f6acbc314994985dc3b77/graphite_beacon/core.py#L185-L199 | train | 25,687 |
klen/graphite-beacon | graphite_beacon/core.py | Reactor.start | def start(self, start_loop=True):
"""Start all the things.
:param start_loop bool: whether to start the ioloop. should be False if
the IOLoop is managed externally
"""
self.start_alerts()
if self.options.get('pidfile'):
with open(self.options.get('pidfile'), 'w') as fpid:
fpid.write(str(os.getpid()))
self.callback.start()
LOGGER.info('Reactor starts')
if start_loop:
self.loop.start() | python | def start(self, start_loop=True):
"""Start all the things.
:param start_loop bool: whether to start the ioloop. should be False if
the IOLoop is managed externally
"""
self.start_alerts()
if self.options.get('pidfile'):
with open(self.options.get('pidfile'), 'w') as fpid:
fpid.write(str(os.getpid()))
self.callback.start()
LOGGER.info('Reactor starts')
if start_loop:
self.loop.start() | [
"def",
"start",
"(",
"self",
",",
"start_loop",
"=",
"True",
")",
":",
"self",
".",
"start_alerts",
"(",
")",
"if",
"self",
".",
"options",
".",
"get",
"(",
"'pidfile'",
")",
":",
"with",
"open",
"(",
"self",
".",
"options",
".",
"get",
"(",
"'pidf... | Start all the things.
:param start_loop bool: whether to start the ioloop. should be False if
the IOLoop is managed externally | [
"Start",
"all",
"the",
"things",
"."
] | c1f071e9f557693bc90f6acbc314994985dc3b77 | https://github.com/klen/graphite-beacon/blob/c1f071e9f557693bc90f6acbc314994985dc3b77/graphite_beacon/core.py#L148-L162 | train | 25,688 |
klen/graphite-beacon | graphite_beacon/core.py | Reactor.notify | def notify(self, level, alert, value, target=None, ntype=None, rule=None):
""" Provide the event to the handlers. """
LOGGER.info('Notify %s:%s:%s:%s', level, alert, value, target or "")
if ntype is None:
ntype = alert.source
for handler in self.handlers.get(level, []):
handler.notify(level, alert, value, target=target, ntype=ntype, rule=rule) | python | def notify(self, level, alert, value, target=None, ntype=None, rule=None):
""" Provide the event to the handlers. """
LOGGER.info('Notify %s:%s:%s:%s', level, alert, value, target or "")
if ntype is None:
ntype = alert.source
for handler in self.handlers.get(level, []):
handler.notify(level, alert, value, target=target, ntype=ntype, rule=rule) | [
"def",
"notify",
"(",
"self",
",",
"level",
",",
"alert",
",",
"value",
",",
"target",
"=",
"None",
",",
"ntype",
"=",
"None",
",",
"rule",
"=",
"None",
")",
":",
"LOGGER",
".",
"info",
"(",
"'Notify %s:%s:%s:%s'",
",",
"level",
",",
"alert",
",",
... | Provide the event to the handlers. | [
"Provide",
"the",
"event",
"to",
"the",
"handlers",
"."
] | c1f071e9f557693bc90f6acbc314994985dc3b77 | https://github.com/klen/graphite-beacon/blob/c1f071e9f557693bc90f6acbc314994985dc3b77/graphite_beacon/core.py#L173-L182 | train | 25,689 |
klen/graphite-beacon | graphite_beacon/handlers/telegram.py | write_to_file | def write_to_file(chats, chatfile):
"""called every time chats are modified"""
with open(chatfile, 'w') as handler:
handler.write('\n'.join((str(id_) for id_ in chats))) | python | def write_to_file(chats, chatfile):
"""called every time chats are modified"""
with open(chatfile, 'w') as handler:
handler.write('\n'.join((str(id_) for id_ in chats))) | [
"def",
"write_to_file",
"(",
"chats",
",",
"chatfile",
")",
":",
"with",
"open",
"(",
"chatfile",
",",
"'w'",
")",
"as",
"handler",
":",
"handler",
".",
"write",
"(",
"'\\n'",
".",
"join",
"(",
"(",
"str",
"(",
"id_",
")",
"for",
"id_",
"in",
"chat... | called every time chats are modified | [
"called",
"every",
"time",
"chats",
"are",
"modified"
] | c1f071e9f557693bc90f6acbc314994985dc3b77 | https://github.com/klen/graphite-beacon/blob/c1f071e9f557693bc90f6acbc314994985dc3b77/graphite_beacon/handlers/telegram.py#L174-L177 | train | 25,690 |
klen/graphite-beacon | graphite_beacon/handlers/telegram.py | get_chatlist | def get_chatlist(chatfile):
"""Try reading ids of saved chats from file.
If we fail, return empty set"""
if not chatfile:
return set()
try:
with open(chatfile) as file_contents:
return set(int(chat) for chat in file_contents)
except (OSError, IOError) as exc:
LOGGER.error('could not load saved chats:\n%s', exc)
return set() | python | def get_chatlist(chatfile):
"""Try reading ids of saved chats from file.
If we fail, return empty set"""
if not chatfile:
return set()
try:
with open(chatfile) as file_contents:
return set(int(chat) for chat in file_contents)
except (OSError, IOError) as exc:
LOGGER.error('could not load saved chats:\n%s', exc)
return set() | [
"def",
"get_chatlist",
"(",
"chatfile",
")",
":",
"if",
"not",
"chatfile",
":",
"return",
"set",
"(",
")",
"try",
":",
"with",
"open",
"(",
"chatfile",
")",
"as",
"file_contents",
":",
"return",
"set",
"(",
"int",
"(",
"chat",
")",
"for",
"chat",
"in... | Try reading ids of saved chats from file.
If we fail, return empty set | [
"Try",
"reading",
"ids",
"of",
"saved",
"chats",
"from",
"file",
".",
"If",
"we",
"fail",
"return",
"empty",
"set"
] | c1f071e9f557693bc90f6acbc314994985dc3b77 | https://github.com/klen/graphite-beacon/blob/c1f071e9f557693bc90f6acbc314994985dc3b77/graphite_beacon/handlers/telegram.py#L180-L190 | train | 25,691 |
klen/graphite-beacon | graphite_beacon/handlers/telegram.py | get_data | def get_data(upd, bot_ident):
"""Parse telegram update."""
update_content = json.loads(upd.decode())
result = update_content['result']
data = (get_fields(update, bot_ident) for update in result)
return (dt for dt in data if dt is not None) | python | def get_data(upd, bot_ident):
"""Parse telegram update."""
update_content = json.loads(upd.decode())
result = update_content['result']
data = (get_fields(update, bot_ident) for update in result)
return (dt for dt in data if dt is not None) | [
"def",
"get_data",
"(",
"upd",
",",
"bot_ident",
")",
":",
"update_content",
"=",
"json",
".",
"loads",
"(",
"upd",
".",
"decode",
"(",
")",
")",
"result",
"=",
"update_content",
"[",
"'result'",
"]",
"data",
"=",
"(",
"get_fields",
"(",
"update",
",",... | Parse telegram update. | [
"Parse",
"telegram",
"update",
"."
] | c1f071e9f557693bc90f6acbc314994985dc3b77 | https://github.com/klen/graphite-beacon/blob/c1f071e9f557693bc90f6acbc314994985dc3b77/graphite_beacon/handlers/telegram.py#L193-L199 | train | 25,692 |
klen/graphite-beacon | graphite_beacon/handlers/telegram.py | get_fields | def get_fields(upd, bot_ident):
"""In telegram api, not every update has message field,
and not every message has update field.
We skip those cases. Rest of fields are mandatory.
We also skip if text is not a valid command to handler.
"""
msg = upd.get('message', {})
text = msg.get('text')
if not text:
return
chat_id = msg['chat']['id']
command = filter_commands(text, chat_id, bot_ident)
if not command:
return
return (upd['update_id'], chat_id, msg['message_id'], command) | python | def get_fields(upd, bot_ident):
"""In telegram api, not every update has message field,
and not every message has update field.
We skip those cases. Rest of fields are mandatory.
We also skip if text is not a valid command to handler.
"""
msg = upd.get('message', {})
text = msg.get('text')
if not text:
return
chat_id = msg['chat']['id']
command = filter_commands(text, chat_id, bot_ident)
if not command:
return
return (upd['update_id'], chat_id, msg['message_id'], command) | [
"def",
"get_fields",
"(",
"upd",
",",
"bot_ident",
")",
":",
"msg",
"=",
"upd",
".",
"get",
"(",
"'message'",
",",
"{",
"}",
")",
"text",
"=",
"msg",
".",
"get",
"(",
"'text'",
")",
"if",
"not",
"text",
":",
"return",
"chat_id",
"=",
"msg",
"[",
... | In telegram api, not every update has message field,
and not every message has update field.
We skip those cases. Rest of fields are mandatory.
We also skip if text is not a valid command to handler. | [
"In",
"telegram",
"api",
"not",
"every",
"update",
"has",
"message",
"field",
"and",
"not",
"every",
"message",
"has",
"update",
"field",
".",
"We",
"skip",
"those",
"cases",
".",
"Rest",
"of",
"fields",
"are",
"mandatory",
".",
"We",
"also",
"skip",
"if... | c1f071e9f557693bc90f6acbc314994985dc3b77 | https://github.com/klen/graphite-beacon/blob/c1f071e9f557693bc90f6acbc314994985dc3b77/graphite_beacon/handlers/telegram.py#L202-L216 | train | 25,693 |
klen/graphite-beacon | graphite_beacon/handlers/telegram.py | TelegramHandler._listen_commands | def _listen_commands(self):
"""Monitor new updates and send them further to
self._respond_commands, where bot actions
are decided.
"""
self._last_update = None
update_body = {'timeout': 2}
while True:
latest = self._last_update
# increase offset to filter out older updates
update_body.update({'offset': latest + 1} if latest else {})
update_resp = self.client.get_updates(update_body)
update_resp.add_done_callback(self._respond_commands)
yield gen.sleep(5) | python | def _listen_commands(self):
"""Monitor new updates and send them further to
self._respond_commands, where bot actions
are decided.
"""
self._last_update = None
update_body = {'timeout': 2}
while True:
latest = self._last_update
# increase offset to filter out older updates
update_body.update({'offset': latest + 1} if latest else {})
update_resp = self.client.get_updates(update_body)
update_resp.add_done_callback(self._respond_commands)
yield gen.sleep(5) | [
"def",
"_listen_commands",
"(",
"self",
")",
":",
"self",
".",
"_last_update",
"=",
"None",
"update_body",
"=",
"{",
"'timeout'",
":",
"2",
"}",
"while",
"True",
":",
"latest",
"=",
"self",
".",
"_last_update",
"# increase offset to filter out older updates",
"u... | Monitor new updates and send them further to
self._respond_commands, where bot actions
are decided. | [
"Monitor",
"new",
"updates",
"and",
"send",
"them",
"further",
"to",
"self",
".",
"_respond_commands",
"where",
"bot",
"actions",
"are",
"decided",
"."
] | c1f071e9f557693bc90f6acbc314994985dc3b77 | https://github.com/klen/graphite-beacon/blob/c1f071e9f557693bc90f6acbc314994985dc3b77/graphite_beacon/handlers/telegram.py#L70-L85 | train | 25,694 |
klen/graphite-beacon | graphite_beacon/handlers/telegram.py | TelegramHandler._respond_commands | def _respond_commands(self, update_response):
"""Extract commands to bot from update and
act accordingly. For description of commands,
see HELP_MESSAGE variable on top of this module.
"""
chatfile = self.chatfile
chats = self.chats
exc, upd = update_response.exception(), update_response.result().body
if exc:
LOGGER.error(str(exc))
if not upd:
return
data = get_data(upd, self.bot_ident)
for update_id, chat_id, message_id, command in data:
self._last_update = update_id
chat_is_known = chat_id in chats
chats_changed = False
reply_text = None
if command == '/activate':
if chat_is_known:
reply_text = 'This chat is already activated.'
else:
LOGGER.debug(
'Adding chat [%s] to notify list.', chat_id)
reply_text = 'Activated.'
chats.add(chat_id)
chats_changed = True
elif command == '/deactivate':
if chat_is_known:
LOGGER.debug(
'Deleting chat [%s] from notify list.', chat_id)
reply_text = 'Deactivated.'
chats.remove(chat_id)
chats_changed = True
if chats_changed and chatfile:
write_to_file(chats, chatfile)
elif command == '/help':
reply_text = HELP_MESSAGE
else:
LOGGER.warning('Could not parse command: '
'bot ident is wrong or missing')
if reply_text:
yield self.client.send_message({
'chat_id': chat_id,
'reply_to_message_id': message_id,
'text': reply_text,
'parse_mode': 'Markdown',
}) | python | def _respond_commands(self, update_response):
"""Extract commands to bot from update and
act accordingly. For description of commands,
see HELP_MESSAGE variable on top of this module.
"""
chatfile = self.chatfile
chats = self.chats
exc, upd = update_response.exception(), update_response.result().body
if exc:
LOGGER.error(str(exc))
if not upd:
return
data = get_data(upd, self.bot_ident)
for update_id, chat_id, message_id, command in data:
self._last_update = update_id
chat_is_known = chat_id in chats
chats_changed = False
reply_text = None
if command == '/activate':
if chat_is_known:
reply_text = 'This chat is already activated.'
else:
LOGGER.debug(
'Adding chat [%s] to notify list.', chat_id)
reply_text = 'Activated.'
chats.add(chat_id)
chats_changed = True
elif command == '/deactivate':
if chat_is_known:
LOGGER.debug(
'Deleting chat [%s] from notify list.', chat_id)
reply_text = 'Deactivated.'
chats.remove(chat_id)
chats_changed = True
if chats_changed and chatfile:
write_to_file(chats, chatfile)
elif command == '/help':
reply_text = HELP_MESSAGE
else:
LOGGER.warning('Could not parse command: '
'bot ident is wrong or missing')
if reply_text:
yield self.client.send_message({
'chat_id': chat_id,
'reply_to_message_id': message_id,
'text': reply_text,
'parse_mode': 'Markdown',
}) | [
"def",
"_respond_commands",
"(",
"self",
",",
"update_response",
")",
":",
"chatfile",
"=",
"self",
".",
"chatfile",
"chats",
"=",
"self",
".",
"chats",
"exc",
",",
"upd",
"=",
"update_response",
".",
"exception",
"(",
")",
",",
"update_response",
".",
"re... | Extract commands to bot from update and
act accordingly. For description of commands,
see HELP_MESSAGE variable on top of this module. | [
"Extract",
"commands",
"to",
"bot",
"from",
"update",
"and",
"act",
"accordingly",
".",
"For",
"description",
"of",
"commands",
"see",
"HELP_MESSAGE",
"variable",
"on",
"top",
"of",
"this",
"module",
"."
] | c1f071e9f557693bc90f6acbc314994985dc3b77 | https://github.com/klen/graphite-beacon/blob/c1f071e9f557693bc90f6acbc314994985dc3b77/graphite_beacon/handlers/telegram.py#L88-L144 | train | 25,695 |
klen/graphite-beacon | graphite_beacon/handlers/telegram.py | TelegramHandler.notify | def notify(self, level, *args, **kwargs):
"""Sends alerts to telegram chats.
This method is called from top level module.
Do not rename it.
"""
LOGGER.debug('Handler (%s) %s', self.name, level)
notify_text = self.get_message(level, *args, **kwargs)
for chat in self.chats.copy():
data = {"chat_id": chat, "text": notify_text}
yield self.client.send_message(data) | python | def notify(self, level, *args, **kwargs):
"""Sends alerts to telegram chats.
This method is called from top level module.
Do not rename it.
"""
LOGGER.debug('Handler (%s) %s', self.name, level)
notify_text = self.get_message(level, *args, **kwargs)
for chat in self.chats.copy():
data = {"chat_id": chat, "text": notify_text}
yield self.client.send_message(data) | [
"def",
"notify",
"(",
"self",
",",
"level",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"LOGGER",
".",
"debug",
"(",
"'Handler (%s) %s'",
",",
"self",
".",
"name",
",",
"level",
")",
"notify_text",
"=",
"self",
".",
"get_message",
"(",
"leve... | Sends alerts to telegram chats.
This method is called from top level module.
Do not rename it. | [
"Sends",
"alerts",
"to",
"telegram",
"chats",
".",
"This",
"method",
"is",
"called",
"from",
"top",
"level",
"module",
".",
"Do",
"not",
"rename",
"it",
"."
] | c1f071e9f557693bc90f6acbc314994985dc3b77 | https://github.com/klen/graphite-beacon/blob/c1f071e9f557693bc90f6acbc314994985dc3b77/graphite_beacon/handlers/telegram.py#L147-L158 | train | 25,696 |
klen/graphite-beacon | graphite_beacon/handlers/telegram.py | TelegramHandler.get_message | def get_message(self, level, alert, value, **kwargs):
"""Standart alert message. Same format across all
graphite-beacon handlers.
"""
target, ntype = kwargs.get('target'), kwargs.get('ntype')
msg_type = 'telegram' if ntype == 'graphite' else 'short'
tmpl = TEMPLATES[ntype][msg_type]
generated = tmpl.generate(
level=level, reactor=self.reactor, alert=alert,
value=value, target=target,)
return generated.decode().strip() | python | def get_message(self, level, alert, value, **kwargs):
"""Standart alert message. Same format across all
graphite-beacon handlers.
"""
target, ntype = kwargs.get('target'), kwargs.get('ntype')
msg_type = 'telegram' if ntype == 'graphite' else 'short'
tmpl = TEMPLATES[ntype][msg_type]
generated = tmpl.generate(
level=level, reactor=self.reactor, alert=alert,
value=value, target=target,)
return generated.decode().strip() | [
"def",
"get_message",
"(",
"self",
",",
"level",
",",
"alert",
",",
"value",
",",
"*",
"*",
"kwargs",
")",
":",
"target",
",",
"ntype",
"=",
"kwargs",
".",
"get",
"(",
"'target'",
")",
",",
"kwargs",
".",
"get",
"(",
"'ntype'",
")",
"msg_type",
"="... | Standart alert message. Same format across all
graphite-beacon handlers. | [
"Standart",
"alert",
"message",
".",
"Same",
"format",
"across",
"all",
"graphite",
"-",
"beacon",
"handlers",
"."
] | c1f071e9f557693bc90f6acbc314994985dc3b77 | https://github.com/klen/graphite-beacon/blob/c1f071e9f557693bc90f6acbc314994985dc3b77/graphite_beacon/handlers/telegram.py#L160-L171 | train | 25,697 |
klen/graphite-beacon | graphite_beacon/handlers/telegram.py | CustomClient.fetchmaker | def fetchmaker(self, telegram_api_method):
"""Receives api method as string and returns
wrapper around AsyncHTTPClient's fetch method
"""
fetch = self.client.fetch
request = self.url(telegram_api_method)
def _fetcher(body, method='POST', headers=None):
"""Uses fetch method of tornado http client."""
body = json.dumps(body)
if not headers:
headers = {}
headers.update({'Content-Type': 'application/json'})
return fetch(
request=request, body=body, method=method, headers=headers)
return _fetcher | python | def fetchmaker(self, telegram_api_method):
"""Receives api method as string and returns
wrapper around AsyncHTTPClient's fetch method
"""
fetch = self.client.fetch
request = self.url(telegram_api_method)
def _fetcher(body, method='POST', headers=None):
"""Uses fetch method of tornado http client."""
body = json.dumps(body)
if not headers:
headers = {}
headers.update({'Content-Type': 'application/json'})
return fetch(
request=request, body=body, method=method, headers=headers)
return _fetcher | [
"def",
"fetchmaker",
"(",
"self",
",",
"telegram_api_method",
")",
":",
"fetch",
"=",
"self",
".",
"client",
".",
"fetch",
"request",
"=",
"self",
".",
"url",
"(",
"telegram_api_method",
")",
"def",
"_fetcher",
"(",
"body",
",",
"method",
"=",
"'POST'",
... | Receives api method as string and returns
wrapper around AsyncHTTPClient's fetch method | [
"Receives",
"api",
"method",
"as",
"string",
"and",
"returns",
"wrapper",
"around",
"AsyncHTTPClient",
"s",
"fetch",
"method"
] | c1f071e9f557693bc90f6acbc314994985dc3b77 | https://github.com/klen/graphite-beacon/blob/c1f071e9f557693bc90f6acbc314994985dc3b77/graphite_beacon/handlers/telegram.py#L259-L275 | train | 25,698 |
klen/graphite-beacon | graphite_beacon/units.py | TimeUnit._normalize_value_ms | def _normalize_value_ms(cls, value):
"""Normalize a value in ms to the largest unit possible without decimal places.
Note that this ignores fractions of a second and always returns a value _at least_
in seconds.
:return: the normalized value and unit name
:rtype: Tuple[Union[int, float], str]
"""
value = round(value / 1000) * 1000 # Ignore fractions of second
sorted_units = sorted(cls.UNITS_IN_MILLISECONDS.items(),
key=lambda x: x[1], reverse=True)
for unit, unit_in_ms in sorted_units:
unit_value = value / unit_in_ms
if unit_value.is_integer():
return int(unit_value), unit
return value, MILLISECOND | python | def _normalize_value_ms(cls, value):
"""Normalize a value in ms to the largest unit possible without decimal places.
Note that this ignores fractions of a second and always returns a value _at least_
in seconds.
:return: the normalized value and unit name
:rtype: Tuple[Union[int, float], str]
"""
value = round(value / 1000) * 1000 # Ignore fractions of second
sorted_units = sorted(cls.UNITS_IN_MILLISECONDS.items(),
key=lambda x: x[1], reverse=True)
for unit, unit_in_ms in sorted_units:
unit_value = value / unit_in_ms
if unit_value.is_integer():
return int(unit_value), unit
return value, MILLISECOND | [
"def",
"_normalize_value_ms",
"(",
"cls",
",",
"value",
")",
":",
"value",
"=",
"round",
"(",
"value",
"/",
"1000",
")",
"*",
"1000",
"# Ignore fractions of second",
"sorted_units",
"=",
"sorted",
"(",
"cls",
".",
"UNITS_IN_MILLISECONDS",
".",
"items",
"(",
... | Normalize a value in ms to the largest unit possible without decimal places.
Note that this ignores fractions of a second and always returns a value _at least_
in seconds.
:return: the normalized value and unit name
:rtype: Tuple[Union[int, float], str] | [
"Normalize",
"a",
"value",
"in",
"ms",
"to",
"the",
"largest",
"unit",
"possible",
"without",
"decimal",
"places",
"."
] | c1f071e9f557693bc90f6acbc314994985dc3b77 | https://github.com/klen/graphite-beacon/blob/c1f071e9f557693bc90f6acbc314994985dc3b77/graphite_beacon/units.py#L101-L118 | train | 25,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.