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
sequence | docstring
stringlengths 3
17.3k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 87
242
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
ponty/psidialogs | psidialogs/api/tkfiledialog_api.py | askopenfile | def askopenfile(mode="r", **options):
"Ask for a filename to open, and returned the opened file"
filename = askopenfilename(**options)
if filename:
return open(filename, mode)
return None | python | def askopenfile(mode="r", **options):
"Ask for a filename to open, and returned the opened file"
filename = askopenfilename(**options)
if filename:
return open(filename, mode)
return None | [
"def",
"askopenfile",
"(",
"mode",
"=",
"\"r\"",
",",
"*",
"*",
"options",
")",
":",
"filename",
"=",
"askopenfilename",
"(",
"*",
"*",
"options",
")",
"if",
"filename",
":",
"return",
"open",
"(",
"filename",
",",
"mode",
")",
"return",
"None"
] | Ask for a filename to open, and returned the opened file | [
"Ask",
"for",
"a",
"filename",
"to",
"open",
"and",
"returned",
"the",
"opened",
"file"
] | e385ab6b48cb43af52b810a1bf76a8135f4585b8 | https://github.com/ponty/psidialogs/blob/e385ab6b48cb43af52b810a1bf76a8135f4585b8/psidialogs/api/tkfiledialog_api.py#L4-L10 | train |
ponty/psidialogs | psidialogs/api/tkfiledialog_api.py | askopenfiles | def askopenfiles(mode="r", **options):
"""Ask for multiple filenames and return the open file
objects
returns a list of open file objects or an empty list if
cancel selected
"""
files = askopenfilenames(**options)
if files:
ofiles = []
for filename in files:
ofiles.append(open(filename, mode))
files = ofiles
return files | python | def askopenfiles(mode="r", **options):
"""Ask for multiple filenames and return the open file
objects
returns a list of open file objects or an empty list if
cancel selected
"""
files = askopenfilenames(**options)
if files:
ofiles = []
for filename in files:
ofiles.append(open(filename, mode))
files = ofiles
return files | [
"def",
"askopenfiles",
"(",
"mode",
"=",
"\"r\"",
",",
"*",
"*",
"options",
")",
":",
"files",
"=",
"askopenfilenames",
"(",
"*",
"*",
"options",
")",
"if",
"files",
":",
"ofiles",
"=",
"[",
"]",
"for",
"filename",
"in",
"files",
":",
"ofiles",
".",
"append",
"(",
"open",
"(",
"filename",
",",
"mode",
")",
")",
"files",
"=",
"ofiles",
"return",
"files"
] | Ask for multiple filenames and return the open file
objects
returns a list of open file objects or an empty list if
cancel selected | [
"Ask",
"for",
"multiple",
"filenames",
"and",
"return",
"the",
"open",
"file",
"objects"
] | e385ab6b48cb43af52b810a1bf76a8135f4585b8 | https://github.com/ponty/psidialogs/blob/e385ab6b48cb43af52b810a1bf76a8135f4585b8/psidialogs/api/tkfiledialog_api.py#L13-L27 | train |
ponty/psidialogs | psidialogs/api/tkfiledialog_api.py | asksaveasfile | def asksaveasfile(mode="w", **options):
"Ask for a filename to save as, and returned the opened file"
filename = asksaveasfilename(**options)
if filename:
return open(filename, mode)
return None | python | def asksaveasfile(mode="w", **options):
"Ask for a filename to save as, and returned the opened file"
filename = asksaveasfilename(**options)
if filename:
return open(filename, mode)
return None | [
"def",
"asksaveasfile",
"(",
"mode",
"=",
"\"w\"",
",",
"*",
"*",
"options",
")",
":",
"filename",
"=",
"asksaveasfilename",
"(",
"*",
"*",
"options",
")",
"if",
"filename",
":",
"return",
"open",
"(",
"filename",
",",
"mode",
")",
"return",
"None"
] | Ask for a filename to save as, and returned the opened file | [
"Ask",
"for",
"a",
"filename",
"to",
"save",
"as",
"and",
"returned",
"the",
"opened",
"file"
] | e385ab6b48cb43af52b810a1bf76a8135f4585b8 | https://github.com/ponty/psidialogs/blob/e385ab6b48cb43af52b810a1bf76a8135f4585b8/psidialogs/api/tkfiledialog_api.py#L30-L36 | train |
clbarnes/coordinates | coordinates/classes.py | spaced_coordinate | def spaced_coordinate(name, keys, ordered=True):
"""
Create a subclass of Coordinate, instances of which must have exactly the given keys.
Parameters
----------
name : str
Name of the new class
keys : sequence
Keys which instances must exclusively have
ordered : bool
Whether to set the class' ``default_order`` based on the order of ``keys``
Returns
-------
type
"""
def validate(self):
"""Raise a ValueError if the instance's keys are incorrect"""
if set(keys) != set(self):
raise ValueError('{} needs keys {} and got {}'.format(type(self).__name__, keys, tuple(self)))
new_class = type(name, (Coordinate, ), {'default_order': keys if ordered else None, '_validate': validate})
return new_class | python | def spaced_coordinate(name, keys, ordered=True):
"""
Create a subclass of Coordinate, instances of which must have exactly the given keys.
Parameters
----------
name : str
Name of the new class
keys : sequence
Keys which instances must exclusively have
ordered : bool
Whether to set the class' ``default_order`` based on the order of ``keys``
Returns
-------
type
"""
def validate(self):
"""Raise a ValueError if the instance's keys are incorrect"""
if set(keys) != set(self):
raise ValueError('{} needs keys {} and got {}'.format(type(self).__name__, keys, tuple(self)))
new_class = type(name, (Coordinate, ), {'default_order': keys if ordered else None, '_validate': validate})
return new_class | [
"def",
"spaced_coordinate",
"(",
"name",
",",
"keys",
",",
"ordered",
"=",
"True",
")",
":",
"def",
"validate",
"(",
"self",
")",
":",
"\"\"\"Raise a ValueError if the instance's keys are incorrect\"\"\"",
"if",
"set",
"(",
"keys",
")",
"!=",
"set",
"(",
"self",
")",
":",
"raise",
"ValueError",
"(",
"'{} needs keys {} and got {}'",
".",
"format",
"(",
"type",
"(",
"self",
")",
".",
"__name__",
",",
"keys",
",",
"tuple",
"(",
"self",
")",
")",
")",
"new_class",
"=",
"type",
"(",
"name",
",",
"(",
"Coordinate",
",",
")",
",",
"{",
"'default_order'",
":",
"keys",
"if",
"ordered",
"else",
"None",
",",
"'_validate'",
":",
"validate",
"}",
")",
"return",
"new_class"
] | Create a subclass of Coordinate, instances of which must have exactly the given keys.
Parameters
----------
name : str
Name of the new class
keys : sequence
Keys which instances must exclusively have
ordered : bool
Whether to set the class' ``default_order`` based on the order of ``keys``
Returns
-------
type | [
"Create",
"a",
"subclass",
"of",
"Coordinate",
"instances",
"of",
"which",
"must",
"have",
"exactly",
"the",
"given",
"keys",
"."
] | 2f5b3ca855da069204407f4bb7e8eb5d4835dfe0 | https://github.com/clbarnes/coordinates/blob/2f5b3ca855da069204407f4bb7e8eb5d4835dfe0/coordinates/classes.py#L289-L312 | train |
clbarnes/coordinates | coordinates/classes.py | MathDict.norm | def norm(self, order=2):
"""Find the vector norm, with the given order, of the values"""
return (sum(val**order for val in abs(self).values()))**(1/order) | python | def norm(self, order=2):
"""Find the vector norm, with the given order, of the values"""
return (sum(val**order for val in abs(self).values()))**(1/order) | [
"def",
"norm",
"(",
"self",
",",
"order",
"=",
"2",
")",
":",
"return",
"(",
"sum",
"(",
"val",
"**",
"order",
"for",
"val",
"in",
"abs",
"(",
"self",
")",
".",
"values",
"(",
")",
")",
")",
"**",
"(",
"1",
"/",
"order",
")"
] | Find the vector norm, with the given order, of the values | [
"Find",
"the",
"vector",
"norm",
"with",
"the",
"given",
"order",
"of",
"the",
"values"
] | 2f5b3ca855da069204407f4bb7e8eb5d4835dfe0 | https://github.com/clbarnes/coordinates/blob/2f5b3ca855da069204407f4bb7e8eb5d4835dfe0/coordinates/classes.py#L175-L177 | train |
Xaroth/libzfs-python | libzfs/utils/jsonify.py | jsonify | def jsonify(o, max_depth=-1, parse_enums=PARSE_KEEP):
"""
Walks through object o, and attempts to get the property instead of the key, if available.
This means that for our VDev objects we can easily get a dict of all the 'parsed' values.
"""
if max_depth == 0:
return o
max_depth -= 1
if isinstance(o, dict):
keyattrs = getattr(o.__class__, '_altnames', {})
def _getter(key, value):
key = keyattrs.get(key, key)
other = getattr(o, key, value)
if callable(other):
other = value
if isinstance(key, Enum): # Make sure we use a name as the key... if we don't it might mess some things up.
key = key.name
return key, jsonify(other, max_depth=max_depth, parse_enums=parse_enums)
return dict(_getter(key, value) for key, value in six.iteritems(o))
elif isinstance(o, list):
return [jsonify(x, max_depth=max_depth, parse_enums=parse_enums) for x in o]
elif isinstance(o, tuple):
return (jsonify(x, max_depth=max_depth, parse_enums=parse_enums) for x in o)
elif isinstance(o, Enum):
o = _parse_enum(o, parse_enums=parse_enums)
return o | python | def jsonify(o, max_depth=-1, parse_enums=PARSE_KEEP):
"""
Walks through object o, and attempts to get the property instead of the key, if available.
This means that for our VDev objects we can easily get a dict of all the 'parsed' values.
"""
if max_depth == 0:
return o
max_depth -= 1
if isinstance(o, dict):
keyattrs = getattr(o.__class__, '_altnames', {})
def _getter(key, value):
key = keyattrs.get(key, key)
other = getattr(o, key, value)
if callable(other):
other = value
if isinstance(key, Enum): # Make sure we use a name as the key... if we don't it might mess some things up.
key = key.name
return key, jsonify(other, max_depth=max_depth, parse_enums=parse_enums)
return dict(_getter(key, value) for key, value in six.iteritems(o))
elif isinstance(o, list):
return [jsonify(x, max_depth=max_depth, parse_enums=parse_enums) for x in o]
elif isinstance(o, tuple):
return (jsonify(x, max_depth=max_depth, parse_enums=parse_enums) for x in o)
elif isinstance(o, Enum):
o = _parse_enum(o, parse_enums=parse_enums)
return o | [
"def",
"jsonify",
"(",
"o",
",",
"max_depth",
"=",
"-",
"1",
",",
"parse_enums",
"=",
"PARSE_KEEP",
")",
":",
"if",
"max_depth",
"==",
"0",
":",
"return",
"o",
"max_depth",
"-=",
"1",
"if",
"isinstance",
"(",
"o",
",",
"dict",
")",
":",
"keyattrs",
"=",
"getattr",
"(",
"o",
".",
"__class__",
",",
"'_altnames'",
",",
"{",
"}",
")",
"def",
"_getter",
"(",
"key",
",",
"value",
")",
":",
"key",
"=",
"keyattrs",
".",
"get",
"(",
"key",
",",
"key",
")",
"other",
"=",
"getattr",
"(",
"o",
",",
"key",
",",
"value",
")",
"if",
"callable",
"(",
"other",
")",
":",
"other",
"=",
"value",
"if",
"isinstance",
"(",
"key",
",",
"Enum",
")",
":",
"# Make sure we use a name as the key... if we don't it might mess some things up.",
"key",
"=",
"key",
".",
"name",
"return",
"key",
",",
"jsonify",
"(",
"other",
",",
"max_depth",
"=",
"max_depth",
",",
"parse_enums",
"=",
"parse_enums",
")",
"return",
"dict",
"(",
"_getter",
"(",
"key",
",",
"value",
")",
"for",
"key",
",",
"value",
"in",
"six",
".",
"iteritems",
"(",
"o",
")",
")",
"elif",
"isinstance",
"(",
"o",
",",
"list",
")",
":",
"return",
"[",
"jsonify",
"(",
"x",
",",
"max_depth",
"=",
"max_depth",
",",
"parse_enums",
"=",
"parse_enums",
")",
"for",
"x",
"in",
"o",
"]",
"elif",
"isinstance",
"(",
"o",
",",
"tuple",
")",
":",
"return",
"(",
"jsonify",
"(",
"x",
",",
"max_depth",
"=",
"max_depth",
",",
"parse_enums",
"=",
"parse_enums",
")",
"for",
"x",
"in",
"o",
")",
"elif",
"isinstance",
"(",
"o",
",",
"Enum",
")",
":",
"o",
"=",
"_parse_enum",
"(",
"o",
",",
"parse_enums",
"=",
"parse_enums",
")",
"return",
"o"
] | Walks through object o, and attempts to get the property instead of the key, if available.
This means that for our VDev objects we can easily get a dict of all the 'parsed' values. | [
"Walks",
"through",
"object",
"o",
"and",
"attempts",
"to",
"get",
"the",
"property",
"instead",
"of",
"the",
"key",
"if",
"available",
".",
"This",
"means",
"that",
"for",
"our",
"VDev",
"objects",
"we",
"can",
"easily",
"get",
"a",
"dict",
"of",
"all",
"the",
"parsed",
"values",
"."
] | 146e5f28de5971bb6eb64fd82b098c5f302f0b33 | https://github.com/Xaroth/libzfs-python/blob/146e5f28de5971bb6eb64fd82b098c5f302f0b33/libzfs/utils/jsonify.py#L25-L52 | train |
gitenberg-dev/gitberg | gitenberg/make.py | NewFilesHandler.copy_files | def copy_files(self):
""" Copy the LICENSE and CONTRIBUTING files to each folder repo
Generate covers if needed. Dump the metadata.
"""
files = [u'LICENSE', u'CONTRIBUTING.rst']
this_dir = dirname(abspath(__file__))
for _file in files:
sh.cp(
'{0}/templates/{1}'.format(this_dir, _file),
'{0}/'.format(self.book.local_path)
)
# copy metadata rdf file
if self.book.meta.rdf_path: # if None, meta is from yaml file
sh.cp(
self.book.meta.rdf_path,
'{0}/'.format(self.book.local_path)
)
if 'GITenberg' not in self.book.meta.subjects:
if not self.book.meta.subjects:
self.book.meta.metadata['subjects'] = []
self.book.meta.metadata['subjects'].append('GITenberg')
self.save_meta() | python | def copy_files(self):
""" Copy the LICENSE and CONTRIBUTING files to each folder repo
Generate covers if needed. Dump the metadata.
"""
files = [u'LICENSE', u'CONTRIBUTING.rst']
this_dir = dirname(abspath(__file__))
for _file in files:
sh.cp(
'{0}/templates/{1}'.format(this_dir, _file),
'{0}/'.format(self.book.local_path)
)
# copy metadata rdf file
if self.book.meta.rdf_path: # if None, meta is from yaml file
sh.cp(
self.book.meta.rdf_path,
'{0}/'.format(self.book.local_path)
)
if 'GITenberg' not in self.book.meta.subjects:
if not self.book.meta.subjects:
self.book.meta.metadata['subjects'] = []
self.book.meta.metadata['subjects'].append('GITenberg')
self.save_meta() | [
"def",
"copy_files",
"(",
"self",
")",
":",
"files",
"=",
"[",
"u'LICENSE'",
",",
"u'CONTRIBUTING.rst'",
"]",
"this_dir",
"=",
"dirname",
"(",
"abspath",
"(",
"__file__",
")",
")",
"for",
"_file",
"in",
"files",
":",
"sh",
".",
"cp",
"(",
"'{0}/templates/{1}'",
".",
"format",
"(",
"this_dir",
",",
"_file",
")",
",",
"'{0}/'",
".",
"format",
"(",
"self",
".",
"book",
".",
"local_path",
")",
")",
"# copy metadata rdf file",
"if",
"self",
".",
"book",
".",
"meta",
".",
"rdf_path",
":",
"# if None, meta is from yaml file",
"sh",
".",
"cp",
"(",
"self",
".",
"book",
".",
"meta",
".",
"rdf_path",
",",
"'{0}/'",
".",
"format",
"(",
"self",
".",
"book",
".",
"local_path",
")",
")",
"if",
"'GITenberg'",
"not",
"in",
"self",
".",
"book",
".",
"meta",
".",
"subjects",
":",
"if",
"not",
"self",
".",
"book",
".",
"meta",
".",
"subjects",
":",
"self",
".",
"book",
".",
"meta",
".",
"metadata",
"[",
"'subjects'",
"]",
"=",
"[",
"]",
"self",
".",
"book",
".",
"meta",
".",
"metadata",
"[",
"'subjects'",
"]",
".",
"append",
"(",
"'GITenberg'",
")",
"self",
".",
"save_meta",
"(",
")"
] | Copy the LICENSE and CONTRIBUTING files to each folder repo
Generate covers if needed. Dump the metadata. | [
"Copy",
"the",
"LICENSE",
"and",
"CONTRIBUTING",
"files",
"to",
"each",
"folder",
"repo",
"Generate",
"covers",
"if",
"needed",
".",
"Dump",
"the",
"metadata",
"."
] | 3f6db8b5a22ccdd2110d3199223c30db4e558b5c | https://github.com/gitenberg-dev/gitberg/blob/3f6db8b5a22ccdd2110d3199223c30db4e558b5c/gitenberg/make.py#L47-L70 | train |
ethan-nelson/osm_diff_tool | osmdt/extract.py | _collate_data | def _collate_data(collation, first_axis, second_axis):
"""
Collects information about the number of edit actions belonging to keys in
a supplied dictionary of object or changeset ids.
Parameters
----------
collation : dict
A dictionary of OpenStreetMap object or changeset ids.
first_axis : string
An object or changeset key for the collation to be performed on.
second_axis : {'create','modify','delete'}
An action key to be added to the first_axis key.
"""
if first_axis not in collation:
collation[first_axis] = {}
collation[first_axis]["create"] = 0
collation[first_axis]["modify"] = 0
collation[first_axis]["delete"] = 0
first = collation[first_axis]
first[second_axis] = first[second_axis] + 1
collation[first_axis] = first | python | def _collate_data(collation, first_axis, second_axis):
"""
Collects information about the number of edit actions belonging to keys in
a supplied dictionary of object or changeset ids.
Parameters
----------
collation : dict
A dictionary of OpenStreetMap object or changeset ids.
first_axis : string
An object or changeset key for the collation to be performed on.
second_axis : {'create','modify','delete'}
An action key to be added to the first_axis key.
"""
if first_axis not in collation:
collation[first_axis] = {}
collation[first_axis]["create"] = 0
collation[first_axis]["modify"] = 0
collation[first_axis]["delete"] = 0
first = collation[first_axis]
first[second_axis] = first[second_axis] + 1
collation[first_axis] = first | [
"def",
"_collate_data",
"(",
"collation",
",",
"first_axis",
",",
"second_axis",
")",
":",
"if",
"first_axis",
"not",
"in",
"collation",
":",
"collation",
"[",
"first_axis",
"]",
"=",
"{",
"}",
"collation",
"[",
"first_axis",
"]",
"[",
"\"create\"",
"]",
"=",
"0",
"collation",
"[",
"first_axis",
"]",
"[",
"\"modify\"",
"]",
"=",
"0",
"collation",
"[",
"first_axis",
"]",
"[",
"\"delete\"",
"]",
"=",
"0",
"first",
"=",
"collation",
"[",
"first_axis",
"]",
"first",
"[",
"second_axis",
"]",
"=",
"first",
"[",
"second_axis",
"]",
"+",
"1",
"collation",
"[",
"first_axis",
"]",
"=",
"first"
] | Collects information about the number of edit actions belonging to keys in
a supplied dictionary of object or changeset ids.
Parameters
----------
collation : dict
A dictionary of OpenStreetMap object or changeset ids.
first_axis : string
An object or changeset key for the collation to be performed on.
second_axis : {'create','modify','delete'}
An action key to be added to the first_axis key. | [
"Collects",
"information",
"about",
"the",
"number",
"of",
"edit",
"actions",
"belonging",
"to",
"keys",
"in",
"a",
"supplied",
"dictionary",
"of",
"object",
"or",
"changeset",
"ids",
"."
] | d5b083100dedd9427ad23c4be5316f89a55ec8f0 | https://github.com/ethan-nelson/osm_diff_tool/blob/d5b083100dedd9427ad23c4be5316f89a55ec8f0/osmdt/extract.py#L1-L27 | train |
ethan-nelson/osm_diff_tool | osmdt/extract.py | extract_changesets | def extract_changesets(objects):
"""
Provides information about each changeset present in an OpenStreetMap diff
file.
Parameters
----------
objects : osc_decoder class
A class containing OpenStreetMap object dictionaries.
Returns
-------
changeset_collation : dict
A dictionary of dictionaries with each changeset as a separate key,
information about each changeset as attributes in that dictionary,
and the actions performed in the changeset as keys.
"""
def add_changeset_info(collation, axis, item):
"""
"""
if axis not in collation:
collation[axis] = {}
first = collation[axis]
first["id"] = axis
first["username"] = item["username"]
first["uid"] = item["uid"]
first["timestamp"] = item["timestamp"]
collation[axis] = first
changeset_collation = {}
for node in objects.nodes.values():
_collate_data(changeset_collation, node['changeset'], node['action'])
add_changeset_info(changeset_collation, node['changeset'], node)
for way in objects.ways.values():
_collate_data(changeset_collation, way['changeset'], way['action'])
add_changeset_info(changeset_collation, way['changeset'], way)
for relation in objects.relations.values():
_collate_data(changeset_collation, relation['changeset'], relation['action'])
add_changeset_info(changeset_collation, relation['changeset'], relation)
return changeset_collation | python | def extract_changesets(objects):
"""
Provides information about each changeset present in an OpenStreetMap diff
file.
Parameters
----------
objects : osc_decoder class
A class containing OpenStreetMap object dictionaries.
Returns
-------
changeset_collation : dict
A dictionary of dictionaries with each changeset as a separate key,
information about each changeset as attributes in that dictionary,
and the actions performed in the changeset as keys.
"""
def add_changeset_info(collation, axis, item):
"""
"""
if axis not in collation:
collation[axis] = {}
first = collation[axis]
first["id"] = axis
first["username"] = item["username"]
first["uid"] = item["uid"]
first["timestamp"] = item["timestamp"]
collation[axis] = first
changeset_collation = {}
for node in objects.nodes.values():
_collate_data(changeset_collation, node['changeset'], node['action'])
add_changeset_info(changeset_collation, node['changeset'], node)
for way in objects.ways.values():
_collate_data(changeset_collation, way['changeset'], way['action'])
add_changeset_info(changeset_collation, way['changeset'], way)
for relation in objects.relations.values():
_collate_data(changeset_collation, relation['changeset'], relation['action'])
add_changeset_info(changeset_collation, relation['changeset'], relation)
return changeset_collation | [
"def",
"extract_changesets",
"(",
"objects",
")",
":",
"def",
"add_changeset_info",
"(",
"collation",
",",
"axis",
",",
"item",
")",
":",
"\"\"\"\n \"\"\"",
"if",
"axis",
"not",
"in",
"collation",
":",
"collation",
"[",
"axis",
"]",
"=",
"{",
"}",
"first",
"=",
"collation",
"[",
"axis",
"]",
"first",
"[",
"\"id\"",
"]",
"=",
"axis",
"first",
"[",
"\"username\"",
"]",
"=",
"item",
"[",
"\"username\"",
"]",
"first",
"[",
"\"uid\"",
"]",
"=",
"item",
"[",
"\"uid\"",
"]",
"first",
"[",
"\"timestamp\"",
"]",
"=",
"item",
"[",
"\"timestamp\"",
"]",
"collation",
"[",
"axis",
"]",
"=",
"first",
"changeset_collation",
"=",
"{",
"}",
"for",
"node",
"in",
"objects",
".",
"nodes",
".",
"values",
"(",
")",
":",
"_collate_data",
"(",
"changeset_collation",
",",
"node",
"[",
"'changeset'",
"]",
",",
"node",
"[",
"'action'",
"]",
")",
"add_changeset_info",
"(",
"changeset_collation",
",",
"node",
"[",
"'changeset'",
"]",
",",
"node",
")",
"for",
"way",
"in",
"objects",
".",
"ways",
".",
"values",
"(",
")",
":",
"_collate_data",
"(",
"changeset_collation",
",",
"way",
"[",
"'changeset'",
"]",
",",
"way",
"[",
"'action'",
"]",
")",
"add_changeset_info",
"(",
"changeset_collation",
",",
"way",
"[",
"'changeset'",
"]",
",",
"way",
")",
"for",
"relation",
"in",
"objects",
".",
"relations",
".",
"values",
"(",
")",
":",
"_collate_data",
"(",
"changeset_collation",
",",
"relation",
"[",
"'changeset'",
"]",
",",
"relation",
"[",
"'action'",
"]",
")",
"add_changeset_info",
"(",
"changeset_collation",
",",
"relation",
"[",
"'changeset'",
"]",
",",
"relation",
")",
"return",
"changeset_collation"
] | Provides information about each changeset present in an OpenStreetMap diff
file.
Parameters
----------
objects : osc_decoder class
A class containing OpenStreetMap object dictionaries.
Returns
-------
changeset_collation : dict
A dictionary of dictionaries with each changeset as a separate key,
information about each changeset as attributes in that dictionary,
and the actions performed in the changeset as keys. | [
"Provides",
"information",
"about",
"each",
"changeset",
"present",
"in",
"an",
"OpenStreetMap",
"diff",
"file",
"."
] | d5b083100dedd9427ad23c4be5316f89a55ec8f0 | https://github.com/ethan-nelson/osm_diff_tool/blob/d5b083100dedd9427ad23c4be5316f89a55ec8f0/osmdt/extract.py#L30-L74 | train |
xlzd/xtls | xtls/util.py | to_str | def to_str(obj):
"""
convert a object to string
"""
if isinstance(obj, str):
return obj
if isinstance(obj, unicode):
return obj.encode('utf-8')
return str(obj) | python | def to_str(obj):
"""
convert a object to string
"""
if isinstance(obj, str):
return obj
if isinstance(obj, unicode):
return obj.encode('utf-8')
return str(obj) | [
"def",
"to_str",
"(",
"obj",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"str",
")",
":",
"return",
"obj",
"if",
"isinstance",
"(",
"obj",
",",
"unicode",
")",
":",
"return",
"obj",
".",
"encode",
"(",
"'utf-8'",
")",
"return",
"str",
"(",
"obj",
")"
] | convert a object to string | [
"convert",
"a",
"object",
"to",
"string"
] | b3cc0ab24197ecaa39adcad7cd828cada9c04a4e | https://github.com/xlzd/xtls/blob/b3cc0ab24197ecaa39adcad7cd828cada9c04a4e/xtls/util.py#L33-L41 | train |
spotify/gordon-gcp | src/gordon_gcp/clients/gdns.py | GDNSClient.get_managed_zone | def get_managed_zone(self, zone):
"""Get the GDNS managed zone name for a DNS zone.
Google uses custom string names with specific `requirements
<https://cloud.google.com/dns/api/v1/managedZones#resource>`_
for storing records. The scheme implemented here chooses a
managed zone name which removes the trailing dot and replaces
other dots with dashes, and in the case of reverse records,
uses only the two most significant octets, prepended with
'reverse'. At least two octets are required for reverse DNS zones.
Example:
get_managed_zone('example.com.') = 'example-com'
get_managed_zone('20.10.in-addr.arpa.) = 'reverse-20-10'
get_managed_zone('30.20.10.in-addr.arpa.) = 'reverse-20-10'
get_managed_zone('40.30.20.10.in-addr.arpa.) = 'reverse-20-10'
Args:
zone (str): DNS zone.
Returns:
str of managed zone name.
"""
if zone.endswith('.in-addr.arpa.'):
return self.reverse_prefix + '-'.join(zone.split('.')[-5:-3])
return self.forward_prefix + '-'.join(zone.split('.')[:-1]) | python | def get_managed_zone(self, zone):
"""Get the GDNS managed zone name for a DNS zone.
Google uses custom string names with specific `requirements
<https://cloud.google.com/dns/api/v1/managedZones#resource>`_
for storing records. The scheme implemented here chooses a
managed zone name which removes the trailing dot and replaces
other dots with dashes, and in the case of reverse records,
uses only the two most significant octets, prepended with
'reverse'. At least two octets are required for reverse DNS zones.
Example:
get_managed_zone('example.com.') = 'example-com'
get_managed_zone('20.10.in-addr.arpa.) = 'reverse-20-10'
get_managed_zone('30.20.10.in-addr.arpa.) = 'reverse-20-10'
get_managed_zone('40.30.20.10.in-addr.arpa.) = 'reverse-20-10'
Args:
zone (str): DNS zone.
Returns:
str of managed zone name.
"""
if zone.endswith('.in-addr.arpa.'):
return self.reverse_prefix + '-'.join(zone.split('.')[-5:-3])
return self.forward_prefix + '-'.join(zone.split('.')[:-1]) | [
"def",
"get_managed_zone",
"(",
"self",
",",
"zone",
")",
":",
"if",
"zone",
".",
"endswith",
"(",
"'.in-addr.arpa.'",
")",
":",
"return",
"self",
".",
"reverse_prefix",
"+",
"'-'",
".",
"join",
"(",
"zone",
".",
"split",
"(",
"'.'",
")",
"[",
"-",
"5",
":",
"-",
"3",
"]",
")",
"return",
"self",
".",
"forward_prefix",
"+",
"'-'",
".",
"join",
"(",
"zone",
".",
"split",
"(",
"'.'",
")",
"[",
":",
"-",
"1",
"]",
")"
] | Get the GDNS managed zone name for a DNS zone.
Google uses custom string names with specific `requirements
<https://cloud.google.com/dns/api/v1/managedZones#resource>`_
for storing records. The scheme implemented here chooses a
managed zone name which removes the trailing dot and replaces
other dots with dashes, and in the case of reverse records,
uses only the two most significant octets, prepended with
'reverse'. At least two octets are required for reverse DNS zones.
Example:
get_managed_zone('example.com.') = 'example-com'
get_managed_zone('20.10.in-addr.arpa.) = 'reverse-20-10'
get_managed_zone('30.20.10.in-addr.arpa.) = 'reverse-20-10'
get_managed_zone('40.30.20.10.in-addr.arpa.) = 'reverse-20-10'
Args:
zone (str): DNS zone.
Returns:
str of managed zone name. | [
"Get",
"the",
"GDNS",
"managed",
"zone",
"name",
"for",
"a",
"DNS",
"zone",
"."
] | 5ab19e3c2fe6ace72ee91e2ef1a1326f90b805da | https://github.com/spotify/gordon-gcp/blob/5ab19e3c2fe6ace72ee91e2ef1a1326f90b805da/src/gordon_gcp/clients/gdns.py#L81-L106 | train |
spotify/gordon-gcp | src/gordon_gcp/clients/gdns.py | GDNSClient.get_records_for_zone | async def get_records_for_zone(self, dns_zone, params=None):
"""Get all resource record sets for a managed zone, using the DNS zone.
Args:
dns_zone (str): Desired DNS zone to query.
params (dict): (optional) Additional query parameters for HTTP
requests to the GDNS API.
Returns:
list of dicts representing rrsets.
"""
managed_zone = self.get_managed_zone(dns_zone)
url = f'{self._base_url}/managedZones/{managed_zone}/rrsets'
if not params:
params = {}
if 'fields' not in params:
# Get only the fields we care about
params['fields'] = ('rrsets/name,rrsets/kind,rrsets/rrdatas,'
'rrsets/type,rrsets/ttl,nextPageToken')
next_page_token = None
records = []
while True:
if next_page_token:
params['pageToken'] = next_page_token
response = await self.get_json(url, params=params)
records.extend(response['rrsets'])
next_page_token = response.get('nextPageToken')
if not next_page_token:
break
logging.info(f'Found {len(records)} rrsets for zone "{dns_zone}".')
return records | python | async def get_records_for_zone(self, dns_zone, params=None):
"""Get all resource record sets for a managed zone, using the DNS zone.
Args:
dns_zone (str): Desired DNS zone to query.
params (dict): (optional) Additional query parameters for HTTP
requests to the GDNS API.
Returns:
list of dicts representing rrsets.
"""
managed_zone = self.get_managed_zone(dns_zone)
url = f'{self._base_url}/managedZones/{managed_zone}/rrsets'
if not params:
params = {}
if 'fields' not in params:
# Get only the fields we care about
params['fields'] = ('rrsets/name,rrsets/kind,rrsets/rrdatas,'
'rrsets/type,rrsets/ttl,nextPageToken')
next_page_token = None
records = []
while True:
if next_page_token:
params['pageToken'] = next_page_token
response = await self.get_json(url, params=params)
records.extend(response['rrsets'])
next_page_token = response.get('nextPageToken')
if not next_page_token:
break
logging.info(f'Found {len(records)} rrsets for zone "{dns_zone}".')
return records | [
"async",
"def",
"get_records_for_zone",
"(",
"self",
",",
"dns_zone",
",",
"params",
"=",
"None",
")",
":",
"managed_zone",
"=",
"self",
".",
"get_managed_zone",
"(",
"dns_zone",
")",
"url",
"=",
"f'{self._base_url}/managedZones/{managed_zone}/rrsets'",
"if",
"not",
"params",
":",
"params",
"=",
"{",
"}",
"if",
"'fields'",
"not",
"in",
"params",
":",
"# Get only the fields we care about",
"params",
"[",
"'fields'",
"]",
"=",
"(",
"'rrsets/name,rrsets/kind,rrsets/rrdatas,'",
"'rrsets/type,rrsets/ttl,nextPageToken'",
")",
"next_page_token",
"=",
"None",
"records",
"=",
"[",
"]",
"while",
"True",
":",
"if",
"next_page_token",
":",
"params",
"[",
"'pageToken'",
"]",
"=",
"next_page_token",
"response",
"=",
"await",
"self",
".",
"get_json",
"(",
"url",
",",
"params",
"=",
"params",
")",
"records",
".",
"extend",
"(",
"response",
"[",
"'rrsets'",
"]",
")",
"next_page_token",
"=",
"response",
".",
"get",
"(",
"'nextPageToken'",
")",
"if",
"not",
"next_page_token",
":",
"break",
"logging",
".",
"info",
"(",
"f'Found {len(records)} rrsets for zone \"{dns_zone}\".'",
")",
"return",
"records"
] | Get all resource record sets for a managed zone, using the DNS zone.
Args:
dns_zone (str): Desired DNS zone to query.
params (dict): (optional) Additional query parameters for HTTP
requests to the GDNS API.
Returns:
list of dicts representing rrsets. | [
"Get",
"all",
"resource",
"record",
"sets",
"for",
"a",
"managed",
"zone",
"using",
"the",
"DNS",
"zone",
"."
] | 5ab19e3c2fe6ace72ee91e2ef1a1326f90b805da | https://github.com/spotify/gordon-gcp/blob/5ab19e3c2fe6ace72ee91e2ef1a1326f90b805da/src/gordon_gcp/clients/gdns.py#L108-L141 | train |
spotify/gordon-gcp | src/gordon_gcp/clients/gdns.py | GDNSClient.is_change_done | async def is_change_done(self, zone, change_id):
"""Check if a DNS change has completed.
Args:
zone (str): DNS zone of the change.
change_id (str): Identifier of the change.
Returns:
Boolean
"""
zone_id = self.get_managed_zone(zone)
url = f'{self._base_url}/managedZones/{zone_id}/changes/{change_id}'
resp = await self.get_json(url)
return resp['status'] == self.DNS_CHANGES_DONE | python | async def is_change_done(self, zone, change_id):
"""Check if a DNS change has completed.
Args:
zone (str): DNS zone of the change.
change_id (str): Identifier of the change.
Returns:
Boolean
"""
zone_id = self.get_managed_zone(zone)
url = f'{self._base_url}/managedZones/{zone_id}/changes/{change_id}'
resp = await self.get_json(url)
return resp['status'] == self.DNS_CHANGES_DONE | [
"async",
"def",
"is_change_done",
"(",
"self",
",",
"zone",
",",
"change_id",
")",
":",
"zone_id",
"=",
"self",
".",
"get_managed_zone",
"(",
"zone",
")",
"url",
"=",
"f'{self._base_url}/managedZones/{zone_id}/changes/{change_id}'",
"resp",
"=",
"await",
"self",
".",
"get_json",
"(",
"url",
")",
"return",
"resp",
"[",
"'status'",
"]",
"==",
"self",
".",
"DNS_CHANGES_DONE"
] | Check if a DNS change has completed.
Args:
zone (str): DNS zone of the change.
change_id (str): Identifier of the change.
Returns:
Boolean | [
"Check",
"if",
"a",
"DNS",
"change",
"has",
"completed",
"."
] | 5ab19e3c2fe6ace72ee91e2ef1a1326f90b805da | https://github.com/spotify/gordon-gcp/blob/5ab19e3c2fe6ace72ee91e2ef1a1326f90b805da/src/gordon_gcp/clients/gdns.py#L143-L155 | train |
spotify/gordon-gcp | src/gordon_gcp/clients/gdns.py | GDNSClient.publish_changes | async def publish_changes(self, zone, changes):
"""Post changes to a zone.
Args:
zone (str): DNS zone of the change.
changes (dict): JSON compatible dict of a `Change
<https://cloud.google.com/dns/api/v1/changes>`_.
Returns:
string identifier of the change.
"""
zone_id = self.get_managed_zone(zone)
url = f'{self._base_url}/managedZones/{zone_id}/changes'
resp = await self.request('post', url, json=changes)
return json.loads(resp)['id'] | python | async def publish_changes(self, zone, changes):
"""Post changes to a zone.
Args:
zone (str): DNS zone of the change.
changes (dict): JSON compatible dict of a `Change
<https://cloud.google.com/dns/api/v1/changes>`_.
Returns:
string identifier of the change.
"""
zone_id = self.get_managed_zone(zone)
url = f'{self._base_url}/managedZones/{zone_id}/changes'
resp = await self.request('post', url, json=changes)
return json.loads(resp)['id'] | [
"async",
"def",
"publish_changes",
"(",
"self",
",",
"zone",
",",
"changes",
")",
":",
"zone_id",
"=",
"self",
".",
"get_managed_zone",
"(",
"zone",
")",
"url",
"=",
"f'{self._base_url}/managedZones/{zone_id}/changes'",
"resp",
"=",
"await",
"self",
".",
"request",
"(",
"'post'",
",",
"url",
",",
"json",
"=",
"changes",
")",
"return",
"json",
".",
"loads",
"(",
"resp",
")",
"[",
"'id'",
"]"
] | Post changes to a zone.
Args:
zone (str): DNS zone of the change.
changes (dict): JSON compatible dict of a `Change
<https://cloud.google.com/dns/api/v1/changes>`_.
Returns:
string identifier of the change. | [
"Post",
"changes",
"to",
"a",
"zone",
"."
] | 5ab19e3c2fe6ace72ee91e2ef1a1326f90b805da | https://github.com/spotify/gordon-gcp/blob/5ab19e3c2fe6ace72ee91e2ef1a1326f90b805da/src/gordon_gcp/clients/gdns.py#L157-L170 | train |
Scille/autobahn-sync | autobahn_sync/session.py | SyncSession.leave | def leave(self, reason=None, message=None):
"""Actively close this WAMP session.
Replace :meth:`autobahn.wamp.interface.IApplicationSession.leave`
"""
# see https://github.com/crossbario/autobahn-python/issues/605
return self._async_session.leave(reason=reason, log_message=message) | python | def leave(self, reason=None, message=None):
"""Actively close this WAMP session.
Replace :meth:`autobahn.wamp.interface.IApplicationSession.leave`
"""
# see https://github.com/crossbario/autobahn-python/issues/605
return self._async_session.leave(reason=reason, log_message=message) | [
"def",
"leave",
"(",
"self",
",",
"reason",
"=",
"None",
",",
"message",
"=",
"None",
")",
":",
"# see https://github.com/crossbario/autobahn-python/issues/605",
"return",
"self",
".",
"_async_session",
".",
"leave",
"(",
"reason",
"=",
"reason",
",",
"log_message",
"=",
"message",
")"
] | Actively close this WAMP session.
Replace :meth:`autobahn.wamp.interface.IApplicationSession.leave` | [
"Actively",
"close",
"this",
"WAMP",
"session",
"."
] | d75fceff0d1aee61fa6dd0168eb1cd40794ad827 | https://github.com/Scille/autobahn-sync/blob/d75fceff0d1aee61fa6dd0168eb1cd40794ad827/autobahn_sync/session.py#L69-L75 | train |
Scille/autobahn-sync | autobahn_sync/session.py | SyncSession.call | def call(self, procedure, *args, **kwargs):
"""Call a remote procedure.
Replace :meth:`autobahn.wamp.interface.IApplicationSession.call`
"""
return self._async_session.call(procedure, *args, **kwargs) | python | def call(self, procedure, *args, **kwargs):
"""Call a remote procedure.
Replace :meth:`autobahn.wamp.interface.IApplicationSession.call`
"""
return self._async_session.call(procedure, *args, **kwargs) | [
"def",
"call",
"(",
"self",
",",
"procedure",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_async_session",
".",
"call",
"(",
"procedure",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Call a remote procedure.
Replace :meth:`autobahn.wamp.interface.IApplicationSession.call` | [
"Call",
"a",
"remote",
"procedure",
"."
] | d75fceff0d1aee61fa6dd0168eb1cd40794ad827 | https://github.com/Scille/autobahn-sync/blob/d75fceff0d1aee61fa6dd0168eb1cd40794ad827/autobahn_sync/session.py#L78-L83 | train |
Scille/autobahn-sync | autobahn_sync/session.py | SyncSession.register | def register(self, endpoint, procedure=None, options=None):
"""Register a procedure for remote calling.
Replace :meth:`autobahn.wamp.interface.IApplicationSession.register`
"""
def proxy_endpoint(*args, **kwargs):
return self._callbacks_runner.put(partial(endpoint, *args, **kwargs))
return self._async_session.register(proxy_endpoint, procedure=procedure, options=options) | python | def register(self, endpoint, procedure=None, options=None):
"""Register a procedure for remote calling.
Replace :meth:`autobahn.wamp.interface.IApplicationSession.register`
"""
def proxy_endpoint(*args, **kwargs):
return self._callbacks_runner.put(partial(endpoint, *args, **kwargs))
return self._async_session.register(proxy_endpoint, procedure=procedure, options=options) | [
"def",
"register",
"(",
"self",
",",
"endpoint",
",",
"procedure",
"=",
"None",
",",
"options",
"=",
"None",
")",
":",
"def",
"proxy_endpoint",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_callbacks_runner",
".",
"put",
"(",
"partial",
"(",
"endpoint",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")",
"return",
"self",
".",
"_async_session",
".",
"register",
"(",
"proxy_endpoint",
",",
"procedure",
"=",
"procedure",
",",
"options",
"=",
"options",
")"
] | Register a procedure for remote calling.
Replace :meth:`autobahn.wamp.interface.IApplicationSession.register` | [
"Register",
"a",
"procedure",
"for",
"remote",
"calling",
"."
] | d75fceff0d1aee61fa6dd0168eb1cd40794ad827 | https://github.com/Scille/autobahn-sync/blob/d75fceff0d1aee61fa6dd0168eb1cd40794ad827/autobahn_sync/session.py#L86-L93 | train |
Scille/autobahn-sync | autobahn_sync/session.py | SyncSession.publish | def publish(self, topic, *args, **kwargs):
"""Publish an event to a topic.
Replace :meth:`autobahn.wamp.interface.IApplicationSession.publish`
"""
return self._async_session.publish(topic, *args, **kwargs) | python | def publish(self, topic, *args, **kwargs):
"""Publish an event to a topic.
Replace :meth:`autobahn.wamp.interface.IApplicationSession.publish`
"""
return self._async_session.publish(topic, *args, **kwargs) | [
"def",
"publish",
"(",
"self",
",",
"topic",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_async_session",
".",
"publish",
"(",
"topic",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Publish an event to a topic.
Replace :meth:`autobahn.wamp.interface.IApplicationSession.publish` | [
"Publish",
"an",
"event",
"to",
"a",
"topic",
"."
] | d75fceff0d1aee61fa6dd0168eb1cd40794ad827 | https://github.com/Scille/autobahn-sync/blob/d75fceff0d1aee61fa6dd0168eb1cd40794ad827/autobahn_sync/session.py#L100-L105 | train |
Scille/autobahn-sync | autobahn_sync/session.py | SyncSession.subscribe | def subscribe(self, handler, topic=None, options=None):
"""Subscribe to a topic for receiving events.
Replace :meth:`autobahn.wamp.interface.IApplicationSession.subscribe`
"""
def proxy_handler(*args, **kwargs):
return self._callbacks_runner.put(partial(handler, *args, **kwargs))
return self._async_session.subscribe(proxy_handler, topic=topic, options=options) | python | def subscribe(self, handler, topic=None, options=None):
"""Subscribe to a topic for receiving events.
Replace :meth:`autobahn.wamp.interface.IApplicationSession.subscribe`
"""
def proxy_handler(*args, **kwargs):
return self._callbacks_runner.put(partial(handler, *args, **kwargs))
return self._async_session.subscribe(proxy_handler, topic=topic, options=options) | [
"def",
"subscribe",
"(",
"self",
",",
"handler",
",",
"topic",
"=",
"None",
",",
"options",
"=",
"None",
")",
":",
"def",
"proxy_handler",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_callbacks_runner",
".",
"put",
"(",
"partial",
"(",
"handler",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")",
"return",
"self",
".",
"_async_session",
".",
"subscribe",
"(",
"proxy_handler",
",",
"topic",
"=",
"topic",
",",
"options",
"=",
"options",
")"
] | Subscribe to a topic for receiving events.
Replace :meth:`autobahn.wamp.interface.IApplicationSession.subscribe` | [
"Subscribe",
"to",
"a",
"topic",
"for",
"receiving",
"events",
"."
] | d75fceff0d1aee61fa6dd0168eb1cd40794ad827 | https://github.com/Scille/autobahn-sync/blob/d75fceff0d1aee61fa6dd0168eb1cd40794ad827/autobahn_sync/session.py#L108-L115 | train |
joeblackwaslike/base58check | base58check/__init__.py | b58encode | def b58encode(val, charset=DEFAULT_CHARSET):
"""Encode input to base58check encoding.
:param bytes val: The value to base58check encode.
:param bytes charset: (optional) The character set to use for encoding.
:return: the encoded bytestring.
:rtype: bytes
:raises: TypeError: if `val` is not bytes.
Usage::
>>> import base58check
>>> base58check.b58encode(b'1BoatSLRHtKNngkdXEeobR76b53LETtpyT')
b'\x00v\x80\xad\xec\x8e\xab\xca\xba\xc6v\xbe\x9e\x83\x85J\xde\x0b\xd2,\xdb\x0b\xb9`\xde'
"""
def _b58encode_int(int_, default=bytes([charset[0]])):
if not int_ and default:
return default
output = b''
while int_:
int_, idx = divmod(int_, base)
output = charset[idx:idx+1] + output
return output
if not isinstance(val, bytes):
raise TypeError(
"a bytes-like object is required, not '%s', "
"use .encode('ascii') to encode unicode strings" %
type(val).__name__)
if isinstance(charset, str):
charset = charset.encode('ascii')
base = len(charset)
if not base == 58:
raise ValueError('charset base must be 58, not %s' % base)
pad_len = len(val)
val = val.lstrip(b'\0')
pad_len -= len(val)
p, acc = 1, 0
for char in deque(reversed(val)):
acc += p * char
p = p << 8
result = _b58encode_int(acc, default=False)
prefix = bytes([charset[0]]) * pad_len
return prefix + result | python | def b58encode(val, charset=DEFAULT_CHARSET):
"""Encode input to base58check encoding.
:param bytes val: The value to base58check encode.
:param bytes charset: (optional) The character set to use for encoding.
:return: the encoded bytestring.
:rtype: bytes
:raises: TypeError: if `val` is not bytes.
Usage::
>>> import base58check
>>> base58check.b58encode(b'1BoatSLRHtKNngkdXEeobR76b53LETtpyT')
b'\x00v\x80\xad\xec\x8e\xab\xca\xba\xc6v\xbe\x9e\x83\x85J\xde\x0b\xd2,\xdb\x0b\xb9`\xde'
"""
def _b58encode_int(int_, default=bytes([charset[0]])):
if not int_ and default:
return default
output = b''
while int_:
int_, idx = divmod(int_, base)
output = charset[idx:idx+1] + output
return output
if not isinstance(val, bytes):
raise TypeError(
"a bytes-like object is required, not '%s', "
"use .encode('ascii') to encode unicode strings" %
type(val).__name__)
if isinstance(charset, str):
charset = charset.encode('ascii')
base = len(charset)
if not base == 58:
raise ValueError('charset base must be 58, not %s' % base)
pad_len = len(val)
val = val.lstrip(b'\0')
pad_len -= len(val)
p, acc = 1, 0
for char in deque(reversed(val)):
acc += p * char
p = p << 8
result = _b58encode_int(acc, default=False)
prefix = bytes([charset[0]]) * pad_len
return prefix + result | [
"def",
"b58encode",
"(",
"val",
",",
"charset",
"=",
"DEFAULT_CHARSET",
")",
":",
"def",
"_b58encode_int",
"(",
"int_",
",",
"default",
"=",
"bytes",
"(",
"[",
"charset",
"[",
"0",
"]",
"]",
")",
")",
":",
"if",
"not",
"int_",
"and",
"default",
":",
"return",
"default",
"output",
"=",
"b''",
"while",
"int_",
":",
"int_",
",",
"idx",
"=",
"divmod",
"(",
"int_",
",",
"base",
")",
"output",
"=",
"charset",
"[",
"idx",
":",
"idx",
"+",
"1",
"]",
"+",
"output",
"return",
"output",
"if",
"not",
"isinstance",
"(",
"val",
",",
"bytes",
")",
":",
"raise",
"TypeError",
"(",
"\"a bytes-like object is required, not '%s', \"",
"\"use .encode('ascii') to encode unicode strings\"",
"%",
"type",
"(",
"val",
")",
".",
"__name__",
")",
"if",
"isinstance",
"(",
"charset",
",",
"str",
")",
":",
"charset",
"=",
"charset",
".",
"encode",
"(",
"'ascii'",
")",
"base",
"=",
"len",
"(",
"charset",
")",
"if",
"not",
"base",
"==",
"58",
":",
"raise",
"ValueError",
"(",
"'charset base must be 58, not %s'",
"%",
"base",
")",
"pad_len",
"=",
"len",
"(",
"val",
")",
"val",
"=",
"val",
".",
"lstrip",
"(",
"b'\\0'",
")",
"pad_len",
"-=",
"len",
"(",
"val",
")",
"p",
",",
"acc",
"=",
"1",
",",
"0",
"for",
"char",
"in",
"deque",
"(",
"reversed",
"(",
"val",
")",
")",
":",
"acc",
"+=",
"p",
"*",
"char",
"p",
"=",
"p",
"<<",
"8",
"result",
"=",
"_b58encode_int",
"(",
"acc",
",",
"default",
"=",
"False",
")",
"prefix",
"=",
"bytes",
"(",
"[",
"charset",
"[",
"0",
"]",
"]",
")",
"*",
"pad_len",
"return",
"prefix",
"+",
"result"
] | Encode input to base58check encoding.
:param bytes val: The value to base58check encode.
:param bytes charset: (optional) The character set to use for encoding.
:return: the encoded bytestring.
:rtype: bytes
:raises: TypeError: if `val` is not bytes.
Usage::
>>> import base58check
>>> base58check.b58encode(b'1BoatSLRHtKNngkdXEeobR76b53LETtpyT')
b'\x00v\x80\xad\xec\x8e\xab\xca\xba\xc6v\xbe\x9e\x83\x85J\xde\x0b\xd2,\xdb\x0b\xb9`\xde' | [
"Encode",
"input",
"to",
"base58check",
"encoding",
"."
] | 417282766e697b8affc926a5f52cb9fcc41978cc | https://github.com/joeblackwaslike/base58check/blob/417282766e697b8affc926a5f52cb9fcc41978cc/base58check/__init__.py#L43-L93 | train |
joeblackwaslike/base58check | base58check/__init__.py | b58decode | def b58decode(val, charset=DEFAULT_CHARSET):
"""Decode base58check encoded input to original raw bytes.
:param bytes val: The value to base58cheeck decode.
:param bytes charset: (optional) The character set to use for decoding.
:return: the decoded bytes.
:rtype: bytes
Usage::
>>> import base58check
>>> base58check.b58decode('\x00v\x80\xad\xec\x8e\xab\xca\xba\xc6v\xbe'
... '\x9e\x83\x85J\xde\x0b\xd2,\xdb\x0b\xb9`\xde')
b'1BoatSLRHtKNngkdXEeobR76b53LETtpyT'
"""
def _b58decode_int(val):
output = 0
for char in val:
output = output * base + charset.index(char)
return output
if isinstance(val, str):
val = val.encode()
if isinstance(charset, str):
charset = charset.encode()
base = len(charset)
if not base == 58:
raise ValueError('charset base must be 58, not %s' % base)
pad_len = len(val)
val = val.lstrip(bytes([charset[0]]))
pad_len -= len(val)
acc = _b58decode_int(val)
result = deque()
while acc > 0:
acc, mod = divmod(acc, 256)
result.appendleft(mod)
prefix = b'\0' * pad_len
return prefix + bytes(result) | python | def b58decode(val, charset=DEFAULT_CHARSET):
"""Decode base58check encoded input to original raw bytes.
:param bytes val: The value to base58cheeck decode.
:param bytes charset: (optional) The character set to use for decoding.
:return: the decoded bytes.
:rtype: bytes
Usage::
>>> import base58check
>>> base58check.b58decode('\x00v\x80\xad\xec\x8e\xab\xca\xba\xc6v\xbe'
... '\x9e\x83\x85J\xde\x0b\xd2,\xdb\x0b\xb9`\xde')
b'1BoatSLRHtKNngkdXEeobR76b53LETtpyT'
"""
def _b58decode_int(val):
output = 0
for char in val:
output = output * base + charset.index(char)
return output
if isinstance(val, str):
val = val.encode()
if isinstance(charset, str):
charset = charset.encode()
base = len(charset)
if not base == 58:
raise ValueError('charset base must be 58, not %s' % base)
pad_len = len(val)
val = val.lstrip(bytes([charset[0]]))
pad_len -= len(val)
acc = _b58decode_int(val)
result = deque()
while acc > 0:
acc, mod = divmod(acc, 256)
result.appendleft(mod)
prefix = b'\0' * pad_len
return prefix + bytes(result) | [
"def",
"b58decode",
"(",
"val",
",",
"charset",
"=",
"DEFAULT_CHARSET",
")",
":",
"def",
"_b58decode_int",
"(",
"val",
")",
":",
"output",
"=",
"0",
"for",
"char",
"in",
"val",
":",
"output",
"=",
"output",
"*",
"base",
"+",
"charset",
".",
"index",
"(",
"char",
")",
"return",
"output",
"if",
"isinstance",
"(",
"val",
",",
"str",
")",
":",
"val",
"=",
"val",
".",
"encode",
"(",
")",
"if",
"isinstance",
"(",
"charset",
",",
"str",
")",
":",
"charset",
"=",
"charset",
".",
"encode",
"(",
")",
"base",
"=",
"len",
"(",
"charset",
")",
"if",
"not",
"base",
"==",
"58",
":",
"raise",
"ValueError",
"(",
"'charset base must be 58, not %s'",
"%",
"base",
")",
"pad_len",
"=",
"len",
"(",
"val",
")",
"val",
"=",
"val",
".",
"lstrip",
"(",
"bytes",
"(",
"[",
"charset",
"[",
"0",
"]",
"]",
")",
")",
"pad_len",
"-=",
"len",
"(",
"val",
")",
"acc",
"=",
"_b58decode_int",
"(",
"val",
")",
"result",
"=",
"deque",
"(",
")",
"while",
"acc",
">",
"0",
":",
"acc",
",",
"mod",
"=",
"divmod",
"(",
"acc",
",",
"256",
")",
"result",
".",
"appendleft",
"(",
"mod",
")",
"prefix",
"=",
"b'\\0'",
"*",
"pad_len",
"return",
"prefix",
"+",
"bytes",
"(",
"result",
")"
] | Decode base58check encoded input to original raw bytes.
:param bytes val: The value to base58cheeck decode.
:param bytes charset: (optional) The character set to use for decoding.
:return: the decoded bytes.
:rtype: bytes
Usage::
>>> import base58check
>>> base58check.b58decode('\x00v\x80\xad\xec\x8e\xab\xca\xba\xc6v\xbe'
... '\x9e\x83\x85J\xde\x0b\xd2,\xdb\x0b\xb9`\xde')
b'1BoatSLRHtKNngkdXEeobR76b53LETtpyT' | [
"Decode",
"base58check",
"encoded",
"input",
"to",
"original",
"raw",
"bytes",
"."
] | 417282766e697b8affc926a5f52cb9fcc41978cc | https://github.com/joeblackwaslike/base58check/blob/417282766e697b8affc926a5f52cb9fcc41978cc/base58check/__init__.py#L96-L141 | train |
zourtney/gpiocrust | gpiocrust/raspberry_pi.py | InputPin.wait_for_edge | def wait_for_edge(self):
"""
This will remove remove any callbacks you might have specified
"""
GPIO.remove_event_detect(self._pin)
GPIO.wait_for_edge(self._pin, self._edge) | python | def wait_for_edge(self):
"""
This will remove remove any callbacks you might have specified
"""
GPIO.remove_event_detect(self._pin)
GPIO.wait_for_edge(self._pin, self._edge) | [
"def",
"wait_for_edge",
"(",
"self",
")",
":",
"GPIO",
".",
"remove_event_detect",
"(",
"self",
".",
"_pin",
")",
"GPIO",
".",
"wait_for_edge",
"(",
"self",
".",
"_pin",
",",
"self",
".",
"_edge",
")"
] | This will remove remove any callbacks you might have specified | [
"This",
"will",
"remove",
"remove",
"any",
"callbacks",
"you",
"might",
"have",
"specified"
] | 4973d467754c50510647ddf855fdc7a73be8a5f6 | https://github.com/zourtney/gpiocrust/blob/4973d467754c50510647ddf855fdc7a73be8a5f6/gpiocrust/raspberry_pi.py#L148-L153 | train |
indietyp/django-automated-logging | automated_logging/signals/request.py | request_finished_callback | def request_finished_callback(sender, **kwargs):
"""This function logs if the user acceses the page"""
logger = logging.getLogger(__name__)
level = settings.AUTOMATED_LOGGING['loglevel']['request']
user = get_current_user()
uri, application, method, status = get_current_environ()
excludes = settings.AUTOMATED_LOGGING['exclude']['request']
if status and status in excludes:
return
if method and method.lower() in excludes:
return
if not settings.AUTOMATED_LOGGING['request']['query']:
uri = urllib.parse.urlparse(uri).path
logger.log(level, ('%s performed request at %s (%s %s)' %
(user, uri, method, status)).replace(" ", " "), extra={
'action': 'request',
'data': {
'user': user,
'uri': uri,
'method': method,
'application': application,
'status': status
}
}) | python | def request_finished_callback(sender, **kwargs):
"""This function logs if the user acceses the page"""
logger = logging.getLogger(__name__)
level = settings.AUTOMATED_LOGGING['loglevel']['request']
user = get_current_user()
uri, application, method, status = get_current_environ()
excludes = settings.AUTOMATED_LOGGING['exclude']['request']
if status and status in excludes:
return
if method and method.lower() in excludes:
return
if not settings.AUTOMATED_LOGGING['request']['query']:
uri = urllib.parse.urlparse(uri).path
logger.log(level, ('%s performed request at %s (%s %s)' %
(user, uri, method, status)).replace(" ", " "), extra={
'action': 'request',
'data': {
'user': user,
'uri': uri,
'method': method,
'application': application,
'status': status
}
}) | [
"def",
"request_finished_callback",
"(",
"sender",
",",
"*",
"*",
"kwargs",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"level",
"=",
"settings",
".",
"AUTOMATED_LOGGING",
"[",
"'loglevel'",
"]",
"[",
"'request'",
"]",
"user",
"=",
"get_current_user",
"(",
")",
"uri",
",",
"application",
",",
"method",
",",
"status",
"=",
"get_current_environ",
"(",
")",
"excludes",
"=",
"settings",
".",
"AUTOMATED_LOGGING",
"[",
"'exclude'",
"]",
"[",
"'request'",
"]",
"if",
"status",
"and",
"status",
"in",
"excludes",
":",
"return",
"if",
"method",
"and",
"method",
".",
"lower",
"(",
")",
"in",
"excludes",
":",
"return",
"if",
"not",
"settings",
".",
"AUTOMATED_LOGGING",
"[",
"'request'",
"]",
"[",
"'query'",
"]",
":",
"uri",
"=",
"urllib",
".",
"parse",
".",
"urlparse",
"(",
"uri",
")",
".",
"path",
"logger",
".",
"log",
"(",
"level",
",",
"(",
"'%s performed request at %s (%s %s)'",
"%",
"(",
"user",
",",
"uri",
",",
"method",
",",
"status",
")",
")",
".",
"replace",
"(",
"\" \"",
",",
"\" \"",
")",
",",
"extra",
"=",
"{",
"'action'",
":",
"'request'",
",",
"'data'",
":",
"{",
"'user'",
":",
"user",
",",
"'uri'",
":",
"uri",
",",
"'method'",
":",
"method",
",",
"'application'",
":",
"application",
",",
"'status'",
":",
"status",
"}",
"}",
")"
] | This function logs if the user acceses the page | [
"This",
"function",
"logs",
"if",
"the",
"user",
"acceses",
"the",
"page"
] | 095dfc6df62dca45f7db4516bc35e52085d0a01c | https://github.com/indietyp/django-automated-logging/blob/095dfc6df62dca45f7db4516bc35e52085d0a01c/automated_logging/signals/request.py#L20-L48 | train |
indietyp/django-automated-logging | automated_logging/signals/request.py | request_exception | def request_exception(sender, request, **kwargs):
"""
Automated request exception logging.
The function can also return an WSGIRequest exception,
which does not supply either status_code or reason_phrase.
"""
if not isinstance(request, WSGIRequest):
logger = logging.getLogger(__name__)
level = CRITICAL if request.status_code <= 500 else WARNING
logger.log(level, '%s exception occured (%s)',
request.status_code, request.reason_phrase)
else:
logger = logging.getLogger(__name__)
logger.log(WARNING, 'WSGIResponse exception occured') | python | def request_exception(sender, request, **kwargs):
"""
Automated request exception logging.
The function can also return an WSGIRequest exception,
which does not supply either status_code or reason_phrase.
"""
if not isinstance(request, WSGIRequest):
logger = logging.getLogger(__name__)
level = CRITICAL if request.status_code <= 500 else WARNING
logger.log(level, '%s exception occured (%s)',
request.status_code, request.reason_phrase)
else:
logger = logging.getLogger(__name__)
logger.log(WARNING, 'WSGIResponse exception occured') | [
"def",
"request_exception",
"(",
"sender",
",",
"request",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"isinstance",
"(",
"request",
",",
"WSGIRequest",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"level",
"=",
"CRITICAL",
"if",
"request",
".",
"status_code",
"<=",
"500",
"else",
"WARNING",
"logger",
".",
"log",
"(",
"level",
",",
"'%s exception occured (%s)'",
",",
"request",
".",
"status_code",
",",
"request",
".",
"reason_phrase",
")",
"else",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"logger",
".",
"log",
"(",
"WARNING",
",",
"'WSGIResponse exception occured'",
")"
] | Automated request exception logging.
The function can also return an WSGIRequest exception,
which does not supply either status_code or reason_phrase. | [
"Automated",
"request",
"exception",
"logging",
"."
] | 095dfc6df62dca45f7db4516bc35e52085d0a01c | https://github.com/indietyp/django-automated-logging/blob/095dfc6df62dca45f7db4516bc35e52085d0a01c/automated_logging/signals/request.py#L52-L68 | train |
gitenberg-dev/gitberg | gitenberg/util/pg.py | source_start | def source_start(base='', book_id='book'):
"""
chooses a starting source file in the 'base' directory for id = book_id
"""
repo_htm_path = "{book_id}-h/{book_id}-h.htm".format(book_id=book_id)
possible_paths = ["book.asciidoc",
repo_htm_path,
"{}-0.txt".format(book_id),
"{}-8.txt".format(book_id),
"{}.txt".format(book_id),
"{}-pdf.pdf".format(book_id),
]
# return the first match
for path in possible_paths:
fullpath = os.path.join(base, path)
if os.path.exists(fullpath):
return path
return None | python | def source_start(base='', book_id='book'):
"""
chooses a starting source file in the 'base' directory for id = book_id
"""
repo_htm_path = "{book_id}-h/{book_id}-h.htm".format(book_id=book_id)
possible_paths = ["book.asciidoc",
repo_htm_path,
"{}-0.txt".format(book_id),
"{}-8.txt".format(book_id),
"{}.txt".format(book_id),
"{}-pdf.pdf".format(book_id),
]
# return the first match
for path in possible_paths:
fullpath = os.path.join(base, path)
if os.path.exists(fullpath):
return path
return None | [
"def",
"source_start",
"(",
"base",
"=",
"''",
",",
"book_id",
"=",
"'book'",
")",
":",
"repo_htm_path",
"=",
"\"{book_id}-h/{book_id}-h.htm\"",
".",
"format",
"(",
"book_id",
"=",
"book_id",
")",
"possible_paths",
"=",
"[",
"\"book.asciidoc\"",
",",
"repo_htm_path",
",",
"\"{}-0.txt\"",
".",
"format",
"(",
"book_id",
")",
",",
"\"{}-8.txt\"",
".",
"format",
"(",
"book_id",
")",
",",
"\"{}.txt\"",
".",
"format",
"(",
"book_id",
")",
",",
"\"{}-pdf.pdf\"",
".",
"format",
"(",
"book_id",
")",
",",
"]",
"# return the first match",
"for",
"path",
"in",
"possible_paths",
":",
"fullpath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"base",
",",
"path",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"fullpath",
")",
":",
"return",
"path",
"return",
"None"
] | chooses a starting source file in the 'base' directory for id = book_id | [
"chooses",
"a",
"starting",
"source",
"file",
"in",
"the",
"base",
"directory",
"for",
"id",
"=",
"book_id"
] | 3f6db8b5a22ccdd2110d3199223c30db4e558b5c | https://github.com/gitenberg-dev/gitberg/blob/3f6db8b5a22ccdd2110d3199223c30db4e558b5c/gitenberg/util/pg.py#L3-L24 | train |
Bystroushaak/bottle-rest | src/bottle_rest/__init__.py | pretty_dump | def pretty_dump(fn):
"""
Decorator used to output prettified JSON.
``response.content_type`` is set to ``application/json; charset=utf-8``.
Args:
fn (fn pointer): Function returning any basic python data structure.
Returns:
str: Data converted to prettified JSON.
"""
@wraps(fn)
def pretty_dump_wrapper(*args, **kwargs):
response.content_type = "application/json; charset=utf-8"
return json.dumps(
fn(*args, **kwargs),
# sort_keys=True,
indent=4,
separators=(',', ': ')
)
return pretty_dump_wrapper | python | def pretty_dump(fn):
"""
Decorator used to output prettified JSON.
``response.content_type`` is set to ``application/json; charset=utf-8``.
Args:
fn (fn pointer): Function returning any basic python data structure.
Returns:
str: Data converted to prettified JSON.
"""
@wraps(fn)
def pretty_dump_wrapper(*args, **kwargs):
response.content_type = "application/json; charset=utf-8"
return json.dumps(
fn(*args, **kwargs),
# sort_keys=True,
indent=4,
separators=(',', ': ')
)
return pretty_dump_wrapper | [
"def",
"pretty_dump",
"(",
"fn",
")",
":",
"@",
"wraps",
"(",
"fn",
")",
"def",
"pretty_dump_wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"response",
".",
"content_type",
"=",
"\"application/json; charset=utf-8\"",
"return",
"json",
".",
"dumps",
"(",
"fn",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
",",
"# sort_keys=True,",
"indent",
"=",
"4",
",",
"separators",
"=",
"(",
"','",
",",
"': '",
")",
")",
"return",
"pretty_dump_wrapper"
] | Decorator used to output prettified JSON.
``response.content_type`` is set to ``application/json; charset=utf-8``.
Args:
fn (fn pointer): Function returning any basic python data structure.
Returns:
str: Data converted to prettified JSON. | [
"Decorator",
"used",
"to",
"output",
"prettified",
"JSON",
"."
] | 428ef68a632ac092cdd49e2f03a664dbaccb0b86 | https://github.com/Bystroushaak/bottle-rest/blob/428ef68a632ac092cdd49e2f03a664dbaccb0b86/src/bottle_rest/__init__.py#L22-L46 | train |
Bystroushaak/bottle-rest | src/bottle_rest/__init__.py | decode_json_body | def decode_json_body():
"""
Decode ``bottle.request.body`` to JSON.
Returns:
obj: Structure decoded by ``json.loads()``.
Raises:
HTTPError: 400 in case the data was malformed.
"""
raw_data = request.body.read()
try:
return json.loads(raw_data)
except ValueError as e:
raise HTTPError(400, e.__str__()) | python | def decode_json_body():
"""
Decode ``bottle.request.body`` to JSON.
Returns:
obj: Structure decoded by ``json.loads()``.
Raises:
HTTPError: 400 in case the data was malformed.
"""
raw_data = request.body.read()
try:
return json.loads(raw_data)
except ValueError as e:
raise HTTPError(400, e.__str__()) | [
"def",
"decode_json_body",
"(",
")",
":",
"raw_data",
"=",
"request",
".",
"body",
".",
"read",
"(",
")",
"try",
":",
"return",
"json",
".",
"loads",
"(",
"raw_data",
")",
"except",
"ValueError",
"as",
"e",
":",
"raise",
"HTTPError",
"(",
"400",
",",
"e",
".",
"__str__",
"(",
")",
")"
] | Decode ``bottle.request.body`` to JSON.
Returns:
obj: Structure decoded by ``json.loads()``.
Raises:
HTTPError: 400 in case the data was malformed. | [
"Decode",
"bottle",
".",
"request",
".",
"body",
"to",
"JSON",
"."
] | 428ef68a632ac092cdd49e2f03a664dbaccb0b86 | https://github.com/Bystroushaak/bottle-rest/blob/428ef68a632ac092cdd49e2f03a664dbaccb0b86/src/bottle_rest/__init__.py#L49-L64 | train |
Bystroushaak/bottle-rest | src/bottle_rest/__init__.py | handle_type_error | def handle_type_error(fn):
"""
Convert ``TypeError`` to ``bottle.HTTPError`` with ``400`` code and message
about wrong parameters.
Raises:
HTTPError: 400 in case too many/too little function parameters were \
given.
"""
@wraps(fn)
def handle_type_error_wrapper(*args, **kwargs):
def any_match(string_list, obj):
return filter(lambda x: x in obj, string_list)
try:
return fn(*args, **kwargs)
except TypeError as e:
message = e.__str__()
str_list = [
"takes exactly",
"got an unexpected",
"takes no argument",
]
if fn.__name__ in message and any_match(str_list, message):
raise HTTPError(400, message)
raise # This will cause 500: Internal server error
return handle_type_error_wrapper | python | def handle_type_error(fn):
"""
Convert ``TypeError`` to ``bottle.HTTPError`` with ``400`` code and message
about wrong parameters.
Raises:
HTTPError: 400 in case too many/too little function parameters were \
given.
"""
@wraps(fn)
def handle_type_error_wrapper(*args, **kwargs):
def any_match(string_list, obj):
return filter(lambda x: x in obj, string_list)
try:
return fn(*args, **kwargs)
except TypeError as e:
message = e.__str__()
str_list = [
"takes exactly",
"got an unexpected",
"takes no argument",
]
if fn.__name__ in message and any_match(str_list, message):
raise HTTPError(400, message)
raise # This will cause 500: Internal server error
return handle_type_error_wrapper | [
"def",
"handle_type_error",
"(",
"fn",
")",
":",
"@",
"wraps",
"(",
"fn",
")",
"def",
"handle_type_error_wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"any_match",
"(",
"string_list",
",",
"obj",
")",
":",
"return",
"filter",
"(",
"lambda",
"x",
":",
"x",
"in",
"obj",
",",
"string_list",
")",
"try",
":",
"return",
"fn",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"except",
"TypeError",
"as",
"e",
":",
"message",
"=",
"e",
".",
"__str__",
"(",
")",
"str_list",
"=",
"[",
"\"takes exactly\"",
",",
"\"got an unexpected\"",
",",
"\"takes no argument\"",
",",
"]",
"if",
"fn",
".",
"__name__",
"in",
"message",
"and",
"any_match",
"(",
"str_list",
",",
"message",
")",
":",
"raise",
"HTTPError",
"(",
"400",
",",
"message",
")",
"raise",
"# This will cause 500: Internal server error",
"return",
"handle_type_error_wrapper"
] | Convert ``TypeError`` to ``bottle.HTTPError`` with ``400`` code and message
about wrong parameters.
Raises:
HTTPError: 400 in case too many/too little function parameters were \
given. | [
"Convert",
"TypeError",
"to",
"bottle",
".",
"HTTPError",
"with",
"400",
"code",
"and",
"message",
"about",
"wrong",
"parameters",
"."
] | 428ef68a632ac092cdd49e2f03a664dbaccb0b86 | https://github.com/Bystroushaak/bottle-rest/blob/428ef68a632ac092cdd49e2f03a664dbaccb0b86/src/bottle_rest/__init__.py#L91-L119 | train |
Bystroushaak/bottle-rest | src/bottle_rest/__init__.py | json_to_params | def json_to_params(fn=None, return_json=True):
"""
Convert JSON in the body of the request to the parameters for the wrapped
function.
If the JSON is list, add it to ``*args``.
If dict, add it to ``**kwargs`` in non-rewrite mode (no key in ``**kwargs``
will be overwritten).
If single value, add it to ``*args``.
Args:
return_json (bool, default True): Should the decorator automatically
convert returned value to JSON?
"""
def json_to_params_decorator(fn):
@handle_type_error
@wraps(fn)
def json_to_params_wrapper(*args, **kwargs):
data = decode_json_body()
if type(data) in [tuple, list]:
args = list(args) + data
elif type(data) == dict:
# transport only items that are not already in kwargs
allowed_keys = set(data.keys()) - set(kwargs.keys())
for key in allowed_keys:
kwargs[key] = data[key]
elif type(data) in PRIMITIVE_TYPES:
args = list(args)
args.append(data)
if not return_json:
return fn(*args, **kwargs)
return encode_json_body(
fn(*args, **kwargs)
)
return json_to_params_wrapper
if fn: # python decorator with optional parameters bukkake
return json_to_params_decorator(fn)
return json_to_params_decorator | python | def json_to_params(fn=None, return_json=True):
"""
Convert JSON in the body of the request to the parameters for the wrapped
function.
If the JSON is list, add it to ``*args``.
If dict, add it to ``**kwargs`` in non-rewrite mode (no key in ``**kwargs``
will be overwritten).
If single value, add it to ``*args``.
Args:
return_json (bool, default True): Should the decorator automatically
convert returned value to JSON?
"""
def json_to_params_decorator(fn):
@handle_type_error
@wraps(fn)
def json_to_params_wrapper(*args, **kwargs):
data = decode_json_body()
if type(data) in [tuple, list]:
args = list(args) + data
elif type(data) == dict:
# transport only items that are not already in kwargs
allowed_keys = set(data.keys()) - set(kwargs.keys())
for key in allowed_keys:
kwargs[key] = data[key]
elif type(data) in PRIMITIVE_TYPES:
args = list(args)
args.append(data)
if not return_json:
return fn(*args, **kwargs)
return encode_json_body(
fn(*args, **kwargs)
)
return json_to_params_wrapper
if fn: # python decorator with optional parameters bukkake
return json_to_params_decorator(fn)
return json_to_params_decorator | [
"def",
"json_to_params",
"(",
"fn",
"=",
"None",
",",
"return_json",
"=",
"True",
")",
":",
"def",
"json_to_params_decorator",
"(",
"fn",
")",
":",
"@",
"handle_type_error",
"@",
"wraps",
"(",
"fn",
")",
"def",
"json_to_params_wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"data",
"=",
"decode_json_body",
"(",
")",
"if",
"type",
"(",
"data",
")",
"in",
"[",
"tuple",
",",
"list",
"]",
":",
"args",
"=",
"list",
"(",
"args",
")",
"+",
"data",
"elif",
"type",
"(",
"data",
")",
"==",
"dict",
":",
"# transport only items that are not already in kwargs",
"allowed_keys",
"=",
"set",
"(",
"data",
".",
"keys",
"(",
")",
")",
"-",
"set",
"(",
"kwargs",
".",
"keys",
"(",
")",
")",
"for",
"key",
"in",
"allowed_keys",
":",
"kwargs",
"[",
"key",
"]",
"=",
"data",
"[",
"key",
"]",
"elif",
"type",
"(",
"data",
")",
"in",
"PRIMITIVE_TYPES",
":",
"args",
"=",
"list",
"(",
"args",
")",
"args",
".",
"append",
"(",
"data",
")",
"if",
"not",
"return_json",
":",
"return",
"fn",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"encode_json_body",
"(",
"fn",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")",
"return",
"json_to_params_wrapper",
"if",
"fn",
":",
"# python decorator with optional parameters bukkake",
"return",
"json_to_params_decorator",
"(",
"fn",
")",
"return",
"json_to_params_decorator"
] | Convert JSON in the body of the request to the parameters for the wrapped
function.
If the JSON is list, add it to ``*args``.
If dict, add it to ``**kwargs`` in non-rewrite mode (no key in ``**kwargs``
will be overwritten).
If single value, add it to ``*args``.
Args:
return_json (bool, default True): Should the decorator automatically
convert returned value to JSON? | [
"Convert",
"JSON",
"in",
"the",
"body",
"of",
"the",
"request",
"to",
"the",
"parameters",
"for",
"the",
"wrapped",
"function",
"."
] | 428ef68a632ac092cdd49e2f03a664dbaccb0b86 | https://github.com/Bystroushaak/bottle-rest/blob/428ef68a632ac092cdd49e2f03a664dbaccb0b86/src/bottle_rest/__init__.py#L122-L167 | train |
Bystroushaak/bottle-rest | src/bottle_rest/__init__.py | json_to_data | def json_to_data(fn=None, return_json=True):
"""
Decode JSON from the request and add it as ``data`` parameter for wrapped
function.
Args:
return_json (bool, default True): Should the decorator automatically
convert returned value to JSON?
"""
def json_to_data_decorator(fn):
@handle_type_error
@wraps(fn)
def get_data_wrapper(*args, **kwargs):
kwargs["data"] = decode_json_body()
if not return_json:
return fn(*args, **kwargs)
return encode_json_body(
fn(*args, **kwargs)
)
return get_data_wrapper
if fn: # python decorator with optional parameters bukkake
return json_to_data_decorator(fn)
return json_to_data_decorator | python | def json_to_data(fn=None, return_json=True):
"""
Decode JSON from the request and add it as ``data`` parameter for wrapped
function.
Args:
return_json (bool, default True): Should the decorator automatically
convert returned value to JSON?
"""
def json_to_data_decorator(fn):
@handle_type_error
@wraps(fn)
def get_data_wrapper(*args, **kwargs):
kwargs["data"] = decode_json_body()
if not return_json:
return fn(*args, **kwargs)
return encode_json_body(
fn(*args, **kwargs)
)
return get_data_wrapper
if fn: # python decorator with optional parameters bukkake
return json_to_data_decorator(fn)
return json_to_data_decorator | [
"def",
"json_to_data",
"(",
"fn",
"=",
"None",
",",
"return_json",
"=",
"True",
")",
":",
"def",
"json_to_data_decorator",
"(",
"fn",
")",
":",
"@",
"handle_type_error",
"@",
"wraps",
"(",
"fn",
")",
"def",
"get_data_wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"\"data\"",
"]",
"=",
"decode_json_body",
"(",
")",
"if",
"not",
"return_json",
":",
"return",
"fn",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"encode_json_body",
"(",
"fn",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")",
"return",
"get_data_wrapper",
"if",
"fn",
":",
"# python decorator with optional parameters bukkake",
"return",
"json_to_data_decorator",
"(",
"fn",
")",
"return",
"json_to_data_decorator"
] | Decode JSON from the request and add it as ``data`` parameter for wrapped
function.
Args:
return_json (bool, default True): Should the decorator automatically
convert returned value to JSON? | [
"Decode",
"JSON",
"from",
"the",
"request",
"and",
"add",
"it",
"as",
"data",
"parameter",
"for",
"wrapped",
"function",
"."
] | 428ef68a632ac092cdd49e2f03a664dbaccb0b86 | https://github.com/Bystroushaak/bottle-rest/blob/428ef68a632ac092cdd49e2f03a664dbaccb0b86/src/bottle_rest/__init__.py#L170-L197 | train |
Bystroushaak/bottle-rest | src/bottle_rest/__init__.py | form_to_params | def form_to_params(fn=None, return_json=True):
"""
Convert bottle forms request to parameters for the wrapped function.
Args:
return_json (bool, default True): Should the decorator automatically
convert returned value to JSON?
"""
def forms_to_params_decorator(fn):
@handle_type_error
@wraps(fn)
def forms_to_params_wrapper(*args, **kwargs):
kwargs.update(
dict(request.forms)
)
if not return_json:
return fn(*args, **kwargs)
return encode_json_body(
fn(*args, **kwargs)
)
return forms_to_params_wrapper
if fn: # python decorator with optional parameters bukkake
return forms_to_params_decorator(fn)
return forms_to_params_decorator | python | def form_to_params(fn=None, return_json=True):
"""
Convert bottle forms request to parameters for the wrapped function.
Args:
return_json (bool, default True): Should the decorator automatically
convert returned value to JSON?
"""
def forms_to_params_decorator(fn):
@handle_type_error
@wraps(fn)
def forms_to_params_wrapper(*args, **kwargs):
kwargs.update(
dict(request.forms)
)
if not return_json:
return fn(*args, **kwargs)
return encode_json_body(
fn(*args, **kwargs)
)
return forms_to_params_wrapper
if fn: # python decorator with optional parameters bukkake
return forms_to_params_decorator(fn)
return forms_to_params_decorator | [
"def",
"form_to_params",
"(",
"fn",
"=",
"None",
",",
"return_json",
"=",
"True",
")",
":",
"def",
"forms_to_params_decorator",
"(",
"fn",
")",
":",
"@",
"handle_type_error",
"@",
"wraps",
"(",
"fn",
")",
"def",
"forms_to_params_wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
".",
"update",
"(",
"dict",
"(",
"request",
".",
"forms",
")",
")",
"if",
"not",
"return_json",
":",
"return",
"fn",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"encode_json_body",
"(",
"fn",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")",
"return",
"forms_to_params_wrapper",
"if",
"fn",
":",
"# python decorator with optional parameters bukkake",
"return",
"forms_to_params_decorator",
"(",
"fn",
")",
"return",
"forms_to_params_decorator"
] | Convert bottle forms request to parameters for the wrapped function.
Args:
return_json (bool, default True): Should the decorator automatically
convert returned value to JSON? | [
"Convert",
"bottle",
"forms",
"request",
"to",
"parameters",
"for",
"the",
"wrapped",
"function",
"."
] | 428ef68a632ac092cdd49e2f03a664dbaccb0b86 | https://github.com/Bystroushaak/bottle-rest/blob/428ef68a632ac092cdd49e2f03a664dbaccb0b86/src/bottle_rest/__init__.py#L200-L228 | train |
ethan-nelson/osm_diff_tool | osmdt/fetch.py | fetch | def fetch(sequence, time='hour'):
"""
Fetch an OpenStreetMap diff file.
Parameters
----------
sequence : string or integer
Diff file sequence desired. Maximum of 9 characters allowed. The value
should follow the two directory and file name structure from the site,
e.g. https://planet.osm.org/replication/hour/NNN/NNN/NNN.osc.gz (with
leading zeros optional).
time : {'minute', 'hour', or 'day'}, optional
Denotes the diff file time granulation to be downloaded. The value
must be a valid directory at https://planet.osm.org/replication/.
Returns
-------
data_stream : class
A file-like class containing a decompressed data stream from the
fetched diff file in string format.
"""
import StringIO
import gzip
import requests
if time not in ['minute','hour','day']:
raise ValueError('The supplied type of replication file does not exist.')
sqn = str(sequence).zfill(9)
url = "https://planet.osm.org/replication/%s/%s/%s/%s.osc.gz" %\
(time, sqn[0:3], sqn[3:6], sqn[6:9])
content = requests.get(url)
if content.status_code == 404:
raise EnvironmentError('Diff file cannot be found.')
content = StringIO.StringIO(content.content)
data_stream = gzip.GzipFile(fileobj=content)
return data_stream | python | def fetch(sequence, time='hour'):
"""
Fetch an OpenStreetMap diff file.
Parameters
----------
sequence : string or integer
Diff file sequence desired. Maximum of 9 characters allowed. The value
should follow the two directory and file name structure from the site,
e.g. https://planet.osm.org/replication/hour/NNN/NNN/NNN.osc.gz (with
leading zeros optional).
time : {'minute', 'hour', or 'day'}, optional
Denotes the diff file time granulation to be downloaded. The value
must be a valid directory at https://planet.osm.org/replication/.
Returns
-------
data_stream : class
A file-like class containing a decompressed data stream from the
fetched diff file in string format.
"""
import StringIO
import gzip
import requests
if time not in ['minute','hour','day']:
raise ValueError('The supplied type of replication file does not exist.')
sqn = str(sequence).zfill(9)
url = "https://planet.osm.org/replication/%s/%s/%s/%s.osc.gz" %\
(time, sqn[0:3], sqn[3:6], sqn[6:9])
content = requests.get(url)
if content.status_code == 404:
raise EnvironmentError('Diff file cannot be found.')
content = StringIO.StringIO(content.content)
data_stream = gzip.GzipFile(fileobj=content)
return data_stream | [
"def",
"fetch",
"(",
"sequence",
",",
"time",
"=",
"'hour'",
")",
":",
"import",
"StringIO",
"import",
"gzip",
"import",
"requests",
"if",
"time",
"not",
"in",
"[",
"'minute'",
",",
"'hour'",
",",
"'day'",
"]",
":",
"raise",
"ValueError",
"(",
"'The supplied type of replication file does not exist.'",
")",
"sqn",
"=",
"str",
"(",
"sequence",
")",
".",
"zfill",
"(",
"9",
")",
"url",
"=",
"\"https://planet.osm.org/replication/%s/%s/%s/%s.osc.gz\"",
"%",
"(",
"time",
",",
"sqn",
"[",
"0",
":",
"3",
"]",
",",
"sqn",
"[",
"3",
":",
"6",
"]",
",",
"sqn",
"[",
"6",
":",
"9",
"]",
")",
"content",
"=",
"requests",
".",
"get",
"(",
"url",
")",
"if",
"content",
".",
"status_code",
"==",
"404",
":",
"raise",
"EnvironmentError",
"(",
"'Diff file cannot be found.'",
")",
"content",
"=",
"StringIO",
".",
"StringIO",
"(",
"content",
".",
"content",
")",
"data_stream",
"=",
"gzip",
".",
"GzipFile",
"(",
"fileobj",
"=",
"content",
")",
"return",
"data_stream"
] | Fetch an OpenStreetMap diff file.
Parameters
----------
sequence : string or integer
Diff file sequence desired. Maximum of 9 characters allowed. The value
should follow the two directory and file name structure from the site,
e.g. https://planet.osm.org/replication/hour/NNN/NNN/NNN.osc.gz (with
leading zeros optional).
time : {'minute', 'hour', or 'day'}, optional
Denotes the diff file time granulation to be downloaded. The value
must be a valid directory at https://planet.osm.org/replication/.
Returns
-------
data_stream : class
A file-like class containing a decompressed data stream from the
fetched diff file in string format. | [
"Fetch",
"an",
"OpenStreetMap",
"diff",
"file",
"."
] | d5b083100dedd9427ad23c4be5316f89a55ec8f0 | https://github.com/ethan-nelson/osm_diff_tool/blob/d5b083100dedd9427ad23c4be5316f89a55ec8f0/osmdt/fetch.py#L1-L42 | train |
indietyp/django-automated-logging | automated_logging/signals/m2m.py | m2m_callback | def m2m_callback(sender, instance, action, reverse, model, pk_set, using, **kwargs):
"""
Many 2 Many relationship signall receivver.
Detect Many 2 Many relationship changes and append these to existing model or create if needed.
These get not recorded from the pre_save or post_save method and must therefor be received from
another method. This method to be precise.
"""
if validate_instance(instance) and settings.AUTOMATED_LOGGING['to_database']:
if action in ["post_add", 'post_remove']:
modification = [model.objects.get(pk=x) for x in pk_set]
if 'al_chl' in instance.__dict__.keys() and instance.al_chl:
changelog = instance.al_chl
else:
changelog = ModelChangelog()
changelog.information = ModelObject()
changelog.information.value = repr(instance)
changelog.information.type = ContentType.objects.get_for_model(instance)
changelog.information.save()
changelog.save()
for f in modification:
obj = ModelObject()
obj.value = repr(f)
try:
obj.type = ContentType.objects.get_for_model(f)
except Exception:
logger = logging.getLogger(__name__)
logger.debug('Could not determin the type of the modification.')
obj.save()
if action == 'post_add':
changelog.inserted.add(obj)
else:
changelog.removed.add(obj)
changelog.save()
instance.al_chl = changelog
if 'al_evt' in instance.__dict__.keys():
target = instance.al_evt
else:
target = Model()
target.user = get_current_user()
target.action = 2 if action == 'post_add' else 2
target.save()
ct = ContentType.objects.get_for_model(instance).app_label
target.application = Application.objects.get_or_create(name=ct)[0]
target.information = ModelObject()
target.information.value = repr(instance)
target.information.type = ContentType.objects.get_for_model(instance)
target.information.save()
instance.al_evt = target
target.modification = changelog
target.save() | python | def m2m_callback(sender, instance, action, reverse, model, pk_set, using, **kwargs):
"""
Many 2 Many relationship signall receivver.
Detect Many 2 Many relationship changes and append these to existing model or create if needed.
These get not recorded from the pre_save or post_save method and must therefor be received from
another method. This method to be precise.
"""
if validate_instance(instance) and settings.AUTOMATED_LOGGING['to_database']:
if action in ["post_add", 'post_remove']:
modification = [model.objects.get(pk=x) for x in pk_set]
if 'al_chl' in instance.__dict__.keys() and instance.al_chl:
changelog = instance.al_chl
else:
changelog = ModelChangelog()
changelog.information = ModelObject()
changelog.information.value = repr(instance)
changelog.information.type = ContentType.objects.get_for_model(instance)
changelog.information.save()
changelog.save()
for f in modification:
obj = ModelObject()
obj.value = repr(f)
try:
obj.type = ContentType.objects.get_for_model(f)
except Exception:
logger = logging.getLogger(__name__)
logger.debug('Could not determin the type of the modification.')
obj.save()
if action == 'post_add':
changelog.inserted.add(obj)
else:
changelog.removed.add(obj)
changelog.save()
instance.al_chl = changelog
if 'al_evt' in instance.__dict__.keys():
target = instance.al_evt
else:
target = Model()
target.user = get_current_user()
target.action = 2 if action == 'post_add' else 2
target.save()
ct = ContentType.objects.get_for_model(instance).app_label
target.application = Application.objects.get_or_create(name=ct)[0]
target.information = ModelObject()
target.information.value = repr(instance)
target.information.type = ContentType.objects.get_for_model(instance)
target.information.save()
instance.al_evt = target
target.modification = changelog
target.save() | [
"def",
"m2m_callback",
"(",
"sender",
",",
"instance",
",",
"action",
",",
"reverse",
",",
"model",
",",
"pk_set",
",",
"using",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"validate_instance",
"(",
"instance",
")",
"and",
"settings",
".",
"AUTOMATED_LOGGING",
"[",
"'to_database'",
"]",
":",
"if",
"action",
"in",
"[",
"\"post_add\"",
",",
"'post_remove'",
"]",
":",
"modification",
"=",
"[",
"model",
".",
"objects",
".",
"get",
"(",
"pk",
"=",
"x",
")",
"for",
"x",
"in",
"pk_set",
"]",
"if",
"'al_chl'",
"in",
"instance",
".",
"__dict__",
".",
"keys",
"(",
")",
"and",
"instance",
".",
"al_chl",
":",
"changelog",
"=",
"instance",
".",
"al_chl",
"else",
":",
"changelog",
"=",
"ModelChangelog",
"(",
")",
"changelog",
".",
"information",
"=",
"ModelObject",
"(",
")",
"changelog",
".",
"information",
".",
"value",
"=",
"repr",
"(",
"instance",
")",
"changelog",
".",
"information",
".",
"type",
"=",
"ContentType",
".",
"objects",
".",
"get_for_model",
"(",
"instance",
")",
"changelog",
".",
"information",
".",
"save",
"(",
")",
"changelog",
".",
"save",
"(",
")",
"for",
"f",
"in",
"modification",
":",
"obj",
"=",
"ModelObject",
"(",
")",
"obj",
".",
"value",
"=",
"repr",
"(",
"f",
")",
"try",
":",
"obj",
".",
"type",
"=",
"ContentType",
".",
"objects",
".",
"get_for_model",
"(",
"f",
")",
"except",
"Exception",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"logger",
".",
"debug",
"(",
"'Could not determin the type of the modification.'",
")",
"obj",
".",
"save",
"(",
")",
"if",
"action",
"==",
"'post_add'",
":",
"changelog",
".",
"inserted",
".",
"add",
"(",
"obj",
")",
"else",
":",
"changelog",
".",
"removed",
".",
"add",
"(",
"obj",
")",
"changelog",
".",
"save",
"(",
")",
"instance",
".",
"al_chl",
"=",
"changelog",
"if",
"'al_evt'",
"in",
"instance",
".",
"__dict__",
".",
"keys",
"(",
")",
":",
"target",
"=",
"instance",
".",
"al_evt",
"else",
":",
"target",
"=",
"Model",
"(",
")",
"target",
".",
"user",
"=",
"get_current_user",
"(",
")",
"target",
".",
"action",
"=",
"2",
"if",
"action",
"==",
"'post_add'",
"else",
"2",
"target",
".",
"save",
"(",
")",
"ct",
"=",
"ContentType",
".",
"objects",
".",
"get_for_model",
"(",
"instance",
")",
".",
"app_label",
"target",
".",
"application",
"=",
"Application",
".",
"objects",
".",
"get_or_create",
"(",
"name",
"=",
"ct",
")",
"[",
"0",
"]",
"target",
".",
"information",
"=",
"ModelObject",
"(",
")",
"target",
".",
"information",
".",
"value",
"=",
"repr",
"(",
"instance",
")",
"target",
".",
"information",
".",
"type",
"=",
"ContentType",
".",
"objects",
".",
"get_for_model",
"(",
"instance",
")",
"target",
".",
"information",
".",
"save",
"(",
")",
"instance",
".",
"al_evt",
"=",
"target",
"target",
".",
"modification",
"=",
"changelog",
"target",
".",
"save",
"(",
")"
] | Many 2 Many relationship signall receivver.
Detect Many 2 Many relationship changes and append these to existing model or create if needed.
These get not recorded from the pre_save or post_save method and must therefor be received from
another method. This method to be precise. | [
"Many",
"2",
"Many",
"relationship",
"signall",
"receivver",
"."
] | 095dfc6df62dca45f7db4516bc35e52085d0a01c | https://github.com/indietyp/django-automated-logging/blob/095dfc6df62dca45f7db4516bc35e52085d0a01c/automated_logging/signals/m2m.py#L13-L73 | train |
gitenberg-dev/gitberg | gitenberg/util/tenprintcover.py | Image.font | def font(self, name, properties):
"""
Return a tuple that contains font properties required for rendering.
"""
size, slant, weight = (properties)
return (name, (self.ty(size), slant, weight)) | python | def font(self, name, properties):
"""
Return a tuple that contains font properties required for rendering.
"""
size, slant, weight = (properties)
return (name, (self.ty(size), slant, weight)) | [
"def",
"font",
"(",
"self",
",",
"name",
",",
"properties",
")",
":",
"size",
",",
"slant",
",",
"weight",
"=",
"(",
"properties",
")",
"return",
"(",
"name",
",",
"(",
"self",
".",
"ty",
"(",
"size",
")",
",",
"slant",
",",
"weight",
")",
")"
] | Return a tuple that contains font properties required for rendering. | [
"Return",
"a",
"tuple",
"that",
"contains",
"font",
"properties",
"required",
"for",
"rendering",
"."
] | 3f6db8b5a22ccdd2110d3199223c30db4e558b5c | https://github.com/gitenberg-dev/gitberg/blob/3f6db8b5a22ccdd2110d3199223c30db4e558b5c/gitenberg/util/tenprintcover.py#L222-L227 | train |
Xorso/pyalarmdotcom | pyalarmdotcom/pyalarmdotcom.py | Alarmdotcom.async_update | def async_update(self):
"""Fetch the latest state."""
_LOGGER.debug('Calling update on Alarm.com')
response = None
if not self._login_info:
yield from self.async_login()
try:
with async_timeout.timeout(10, loop=self._loop):
response = yield from self._websession.get(
self.ALARMDOTCOM_URL + '{}/main.aspx'.format(
self._login_info['sessionkey']),
headers={'User-Agent': 'Mozilla/5.0 '
'(Windows NT 6.1; '
'WOW64; rv:40.0) '
'Gecko/20100101 '
'Firefox/40.1'}
)
_LOGGER.debug('Response from Alarm.com: %s', response.status)
text = yield from response.text()
_LOGGER.debug(text)
tree = BeautifulSoup(text, 'html.parser')
try:
self.state = tree.select(self.ALARM_STATE)[0].get_text()
_LOGGER.debug(
'Current alarm state: %s', self.state)
self.sensor_status = tree.select(self.SENSOR_STATUS)[0].get_text()
_LOGGER.debug(
'Current sensor status: %s', self.sensor_status)
except IndexError:
# We may have timed out. Re-login again
self.state = None
self.sensor_status = None
self._login_info = None
yield from self.async_update()
except (asyncio.TimeoutError, aiohttp.ClientError):
_LOGGER.error("Can not load login page from Alarm.com")
return False
finally:
if response is not None:
yield from response.release() | python | def async_update(self):
"""Fetch the latest state."""
_LOGGER.debug('Calling update on Alarm.com')
response = None
if not self._login_info:
yield from self.async_login()
try:
with async_timeout.timeout(10, loop=self._loop):
response = yield from self._websession.get(
self.ALARMDOTCOM_URL + '{}/main.aspx'.format(
self._login_info['sessionkey']),
headers={'User-Agent': 'Mozilla/5.0 '
'(Windows NT 6.1; '
'WOW64; rv:40.0) '
'Gecko/20100101 '
'Firefox/40.1'}
)
_LOGGER.debug('Response from Alarm.com: %s', response.status)
text = yield from response.text()
_LOGGER.debug(text)
tree = BeautifulSoup(text, 'html.parser')
try:
self.state = tree.select(self.ALARM_STATE)[0].get_text()
_LOGGER.debug(
'Current alarm state: %s', self.state)
self.sensor_status = tree.select(self.SENSOR_STATUS)[0].get_text()
_LOGGER.debug(
'Current sensor status: %s', self.sensor_status)
except IndexError:
# We may have timed out. Re-login again
self.state = None
self.sensor_status = None
self._login_info = None
yield from self.async_update()
except (asyncio.TimeoutError, aiohttp.ClientError):
_LOGGER.error("Can not load login page from Alarm.com")
return False
finally:
if response is not None:
yield from response.release() | [
"def",
"async_update",
"(",
"self",
")",
":",
"_LOGGER",
".",
"debug",
"(",
"'Calling update on Alarm.com'",
")",
"response",
"=",
"None",
"if",
"not",
"self",
".",
"_login_info",
":",
"yield",
"from",
"self",
".",
"async_login",
"(",
")",
"try",
":",
"with",
"async_timeout",
".",
"timeout",
"(",
"10",
",",
"loop",
"=",
"self",
".",
"_loop",
")",
":",
"response",
"=",
"yield",
"from",
"self",
".",
"_websession",
".",
"get",
"(",
"self",
".",
"ALARMDOTCOM_URL",
"+",
"'{}/main.aspx'",
".",
"format",
"(",
"self",
".",
"_login_info",
"[",
"'sessionkey'",
"]",
")",
",",
"headers",
"=",
"{",
"'User-Agent'",
":",
"'Mozilla/5.0 '",
"'(Windows NT 6.1; '",
"'WOW64; rv:40.0) '",
"'Gecko/20100101 '",
"'Firefox/40.1'",
"}",
")",
"_LOGGER",
".",
"debug",
"(",
"'Response from Alarm.com: %s'",
",",
"response",
".",
"status",
")",
"text",
"=",
"yield",
"from",
"response",
".",
"text",
"(",
")",
"_LOGGER",
".",
"debug",
"(",
"text",
")",
"tree",
"=",
"BeautifulSoup",
"(",
"text",
",",
"'html.parser'",
")",
"try",
":",
"self",
".",
"state",
"=",
"tree",
".",
"select",
"(",
"self",
".",
"ALARM_STATE",
")",
"[",
"0",
"]",
".",
"get_text",
"(",
")",
"_LOGGER",
".",
"debug",
"(",
"'Current alarm state: %s'",
",",
"self",
".",
"state",
")",
"self",
".",
"sensor_status",
"=",
"tree",
".",
"select",
"(",
"self",
".",
"SENSOR_STATUS",
")",
"[",
"0",
"]",
".",
"get_text",
"(",
")",
"_LOGGER",
".",
"debug",
"(",
"'Current sensor status: %s'",
",",
"self",
".",
"sensor_status",
")",
"except",
"IndexError",
":",
"# We may have timed out. Re-login again",
"self",
".",
"state",
"=",
"None",
"self",
".",
"sensor_status",
"=",
"None",
"self",
".",
"_login_info",
"=",
"None",
"yield",
"from",
"self",
".",
"async_update",
"(",
")",
"except",
"(",
"asyncio",
".",
"TimeoutError",
",",
"aiohttp",
".",
"ClientError",
")",
":",
"_LOGGER",
".",
"error",
"(",
"\"Can not load login page from Alarm.com\"",
")",
"return",
"False",
"finally",
":",
"if",
"response",
"is",
"not",
"None",
":",
"yield",
"from",
"response",
".",
"release",
"(",
")"
] | Fetch the latest state. | [
"Fetch",
"the",
"latest",
"state",
"."
] | 9d2cfe1968d52bb23533aeda80ca5efbfb692304 | https://github.com/Xorso/pyalarmdotcom/blob/9d2cfe1968d52bb23533aeda80ca5efbfb692304/pyalarmdotcom/pyalarmdotcom.py#L209-L249 | train |
gitenberg-dev/gitberg | gitenberg/push.py | GithubRepo.create_api_handler | def create_api_handler(self):
""" Creates an api handler and sets it on self """
try:
self.github = github3.login(username=config.data['gh_user'],
password=config.data['gh_password'])
except KeyError as e:
raise config.NotConfigured(e)
logger.info("ratelimit remaining: {}".format(self.github.ratelimit_remaining))
if hasattr(self.github, 'set_user_agent'):
self.github.set_user_agent('{}: {}'.format(self.org_name, self.org_homepage))
try:
self.org = self.github.organization(self.org_name)
except github3.GitHubError:
logger.error("Possibly the github ratelimit has been exceeded")
logger.info("ratelimit: " + str(self.github.ratelimit_remaining)) | python | def create_api_handler(self):
""" Creates an api handler and sets it on self """
try:
self.github = github3.login(username=config.data['gh_user'],
password=config.data['gh_password'])
except KeyError as e:
raise config.NotConfigured(e)
logger.info("ratelimit remaining: {}".format(self.github.ratelimit_remaining))
if hasattr(self.github, 'set_user_agent'):
self.github.set_user_agent('{}: {}'.format(self.org_name, self.org_homepage))
try:
self.org = self.github.organization(self.org_name)
except github3.GitHubError:
logger.error("Possibly the github ratelimit has been exceeded")
logger.info("ratelimit: " + str(self.github.ratelimit_remaining)) | [
"def",
"create_api_handler",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"github",
"=",
"github3",
".",
"login",
"(",
"username",
"=",
"config",
".",
"data",
"[",
"'gh_user'",
"]",
",",
"password",
"=",
"config",
".",
"data",
"[",
"'gh_password'",
"]",
")",
"except",
"KeyError",
"as",
"e",
":",
"raise",
"config",
".",
"NotConfigured",
"(",
"e",
")",
"logger",
".",
"info",
"(",
"\"ratelimit remaining: {}\"",
".",
"format",
"(",
"self",
".",
"github",
".",
"ratelimit_remaining",
")",
")",
"if",
"hasattr",
"(",
"self",
".",
"github",
",",
"'set_user_agent'",
")",
":",
"self",
".",
"github",
".",
"set_user_agent",
"(",
"'{}: {}'",
".",
"format",
"(",
"self",
".",
"org_name",
",",
"self",
".",
"org_homepage",
")",
")",
"try",
":",
"self",
".",
"org",
"=",
"self",
".",
"github",
".",
"organization",
"(",
"self",
".",
"org_name",
")",
"except",
"github3",
".",
"GitHubError",
":",
"logger",
".",
"error",
"(",
"\"Possibly the github ratelimit has been exceeded\"",
")",
"logger",
".",
"info",
"(",
"\"ratelimit: \"",
"+",
"str",
"(",
"self",
".",
"github",
".",
"ratelimit_remaining",
")",
")"
] | Creates an api handler and sets it on self | [
"Creates",
"an",
"api",
"handler",
"and",
"sets",
"it",
"on",
"self"
] | 3f6db8b5a22ccdd2110d3199223c30db4e558b5c | https://github.com/gitenberg-dev/gitberg/blob/3f6db8b5a22ccdd2110d3199223c30db4e558b5c/gitenberg/push.py#L72-L86 | train |
dstanek/snake-guice | snakeguice/decorators.py | _validate_func_args | def _validate_func_args(func, kwargs):
"""Validate decorator args when used to decorate a function."""
args, varargs, varkw, defaults = inspect.getargspec(func)
if set(kwargs.keys()) != set(args[1:]): # chop off self
raise TypeError("decorator kwargs do not match %s()'s kwargs"
% func.__name__) | python | def _validate_func_args(func, kwargs):
"""Validate decorator args when used to decorate a function."""
args, varargs, varkw, defaults = inspect.getargspec(func)
if set(kwargs.keys()) != set(args[1:]): # chop off self
raise TypeError("decorator kwargs do not match %s()'s kwargs"
% func.__name__) | [
"def",
"_validate_func_args",
"(",
"func",
",",
"kwargs",
")",
":",
"args",
",",
"varargs",
",",
"varkw",
",",
"defaults",
"=",
"inspect",
".",
"getargspec",
"(",
"func",
")",
"if",
"set",
"(",
"kwargs",
".",
"keys",
"(",
")",
")",
"!=",
"set",
"(",
"args",
"[",
"1",
":",
"]",
")",
":",
"# chop off self",
"raise",
"TypeError",
"(",
"\"decorator kwargs do not match %s()'s kwargs\"",
"%",
"func",
".",
"__name__",
")"
] | Validate decorator args when used to decorate a function. | [
"Validate",
"decorator",
"args",
"when",
"used",
"to",
"decorate",
"a",
"function",
"."
] | d20b62de3ee31e84119c801756398c35ed803fb3 | https://github.com/dstanek/snake-guice/blob/d20b62de3ee31e84119c801756398c35ed803fb3/snakeguice/decorators.py#L52-L58 | train |
dstanek/snake-guice | snakeguice/decorators.py | enclosing_frame | def enclosing_frame(frame=None, level=2):
"""Get an enclosing frame that skips decorator code"""
frame = frame or sys._getframe(level)
while frame.f_globals.get('__name__') == __name__: frame = frame.f_back
return frame | python | def enclosing_frame(frame=None, level=2):
"""Get an enclosing frame that skips decorator code"""
frame = frame or sys._getframe(level)
while frame.f_globals.get('__name__') == __name__: frame = frame.f_back
return frame | [
"def",
"enclosing_frame",
"(",
"frame",
"=",
"None",
",",
"level",
"=",
"2",
")",
":",
"frame",
"=",
"frame",
"or",
"sys",
".",
"_getframe",
"(",
"level",
")",
"while",
"frame",
".",
"f_globals",
".",
"get",
"(",
"'__name__'",
")",
"==",
"__name__",
":",
"frame",
"=",
"frame",
".",
"f_back",
"return",
"frame"
] | Get an enclosing frame that skips decorator code | [
"Get",
"an",
"enclosing",
"frame",
"that",
"skips",
"decorator",
"code"
] | d20b62de3ee31e84119c801756398c35ed803fb3 | https://github.com/dstanek/snake-guice/blob/d20b62de3ee31e84119c801756398c35ed803fb3/snakeguice/decorators.py#L61-L65 | train |
spotify/gordon-gcp | src/gordon_gcp/plugins/service/__init__.py | get_event_consumer | def get_event_consumer(config, success_channel, error_channel, metrics,
**kwargs):
"""Get a GPSEventConsumer client.
A factory function that validates configuration, creates schema
validator and parser clients, creates an auth and a pubsub client,
and returns an event consumer (:interface:`gordon.interfaces.
IRunnable` and :interface:`gordon.interfaces.IMessageHandler`)
provider.
Args:
config (dict): Google Cloud Pub/Sub-related configuration.
success_channel (asyncio.Queue): Queue to place a successfully
consumed message to be further handled by the ``gordon``
core system.
error_channel (asyncio.Queue): Queue to place a message met
with errors to be further handled by the ``gordon`` core
system.
metrics (obj): :interface:`IMetricRelay` implementation.
kwargs (dict): Additional keyword arguments to pass to the
event consumer.
Returns:
A :class:`GPSEventConsumer` instance.
"""
builder = event_consumer.GPSEventConsumerBuilder(
config, success_channel, error_channel, metrics, **kwargs)
return builder.build_event_consumer() | python | def get_event_consumer(config, success_channel, error_channel, metrics,
**kwargs):
"""Get a GPSEventConsumer client.
A factory function that validates configuration, creates schema
validator and parser clients, creates an auth and a pubsub client,
and returns an event consumer (:interface:`gordon.interfaces.
IRunnable` and :interface:`gordon.interfaces.IMessageHandler`)
provider.
Args:
config (dict): Google Cloud Pub/Sub-related configuration.
success_channel (asyncio.Queue): Queue to place a successfully
consumed message to be further handled by the ``gordon``
core system.
error_channel (asyncio.Queue): Queue to place a message met
with errors to be further handled by the ``gordon`` core
system.
metrics (obj): :interface:`IMetricRelay` implementation.
kwargs (dict): Additional keyword arguments to pass to the
event consumer.
Returns:
A :class:`GPSEventConsumer` instance.
"""
builder = event_consumer.GPSEventConsumerBuilder(
config, success_channel, error_channel, metrics, **kwargs)
return builder.build_event_consumer() | [
"def",
"get_event_consumer",
"(",
"config",
",",
"success_channel",
",",
"error_channel",
",",
"metrics",
",",
"*",
"*",
"kwargs",
")",
":",
"builder",
"=",
"event_consumer",
".",
"GPSEventConsumerBuilder",
"(",
"config",
",",
"success_channel",
",",
"error_channel",
",",
"metrics",
",",
"*",
"*",
"kwargs",
")",
"return",
"builder",
".",
"build_event_consumer",
"(",
")"
] | Get a GPSEventConsumer client.
A factory function that validates configuration, creates schema
validator and parser clients, creates an auth and a pubsub client,
and returns an event consumer (:interface:`gordon.interfaces.
IRunnable` and :interface:`gordon.interfaces.IMessageHandler`)
provider.
Args:
config (dict): Google Cloud Pub/Sub-related configuration.
success_channel (asyncio.Queue): Queue to place a successfully
consumed message to be further handled by the ``gordon``
core system.
error_channel (asyncio.Queue): Queue to place a message met
with errors to be further handled by the ``gordon`` core
system.
metrics (obj): :interface:`IMetricRelay` implementation.
kwargs (dict): Additional keyword arguments to pass to the
event consumer.
Returns:
A :class:`GPSEventConsumer` instance. | [
"Get",
"a",
"GPSEventConsumer",
"client",
"."
] | 5ab19e3c2fe6ace72ee91e2ef1a1326f90b805da | https://github.com/spotify/gordon-gcp/blob/5ab19e3c2fe6ace72ee91e2ef1a1326f90b805da/src/gordon_gcp/plugins/service/__init__.py#L34-L60 | train |
spotify/gordon-gcp | src/gordon_gcp/plugins/service/__init__.py | get_enricher | def get_enricher(config, metrics, **kwargs):
"""Get a GCEEnricher client.
A factory function that validates configuration and returns an
enricher client (:interface:`gordon.interfaces.IMessageHandler`)
provider.
Args:
config (dict): Google Compute Engine API related configuration.
metrics (obj): :interface:`IMetricRelay` implementation.
kwargs (dict): Additional keyword arguments to pass to the
enricher.
Returns:
A :class:`GCEEnricher` instance.
"""
builder = enricher.GCEEnricherBuilder(
config, metrics, **kwargs)
return builder.build_enricher() | python | def get_enricher(config, metrics, **kwargs):
"""Get a GCEEnricher client.
A factory function that validates configuration and returns an
enricher client (:interface:`gordon.interfaces.IMessageHandler`)
provider.
Args:
config (dict): Google Compute Engine API related configuration.
metrics (obj): :interface:`IMetricRelay` implementation.
kwargs (dict): Additional keyword arguments to pass to the
enricher.
Returns:
A :class:`GCEEnricher` instance.
"""
builder = enricher.GCEEnricherBuilder(
config, metrics, **kwargs)
return builder.build_enricher() | [
"def",
"get_enricher",
"(",
"config",
",",
"metrics",
",",
"*",
"*",
"kwargs",
")",
":",
"builder",
"=",
"enricher",
".",
"GCEEnricherBuilder",
"(",
"config",
",",
"metrics",
",",
"*",
"*",
"kwargs",
")",
"return",
"builder",
".",
"build_enricher",
"(",
")"
] | Get a GCEEnricher client.
A factory function that validates configuration and returns an
enricher client (:interface:`gordon.interfaces.IMessageHandler`)
provider.
Args:
config (dict): Google Compute Engine API related configuration.
metrics (obj): :interface:`IMetricRelay` implementation.
kwargs (dict): Additional keyword arguments to pass to the
enricher.
Returns:
A :class:`GCEEnricher` instance. | [
"Get",
"a",
"GCEEnricher",
"client",
"."
] | 5ab19e3c2fe6ace72ee91e2ef1a1326f90b805da | https://github.com/spotify/gordon-gcp/blob/5ab19e3c2fe6ace72ee91e2ef1a1326f90b805da/src/gordon_gcp/plugins/service/__init__.py#L63-L80 | train |
spotify/gordon-gcp | src/gordon_gcp/plugins/service/__init__.py | get_gdns_publisher | def get_gdns_publisher(config, metrics, **kwargs):
"""Get a GDNSPublisher client.
A factory function that validates configuration and returns a
publisher client (:interface:`gordon.interfaces.IMessageHandler`)
provider.
Args:
config (dict): Google Cloud DNS API related configuration.
metrics (obj): :interface:`IMetricRelay` implementation.
kwargs (dict): Additional keyword arguments to pass to the
publisher.
Returns:
A :class:`GDNSPublisher` instance.
"""
builder = gdns_publisher.GDNSPublisherBuilder(
config, metrics, **kwargs)
return builder.build_publisher() | python | def get_gdns_publisher(config, metrics, **kwargs):
"""Get a GDNSPublisher client.
A factory function that validates configuration and returns a
publisher client (:interface:`gordon.interfaces.IMessageHandler`)
provider.
Args:
config (dict): Google Cloud DNS API related configuration.
metrics (obj): :interface:`IMetricRelay` implementation.
kwargs (dict): Additional keyword arguments to pass to the
publisher.
Returns:
A :class:`GDNSPublisher` instance.
"""
builder = gdns_publisher.GDNSPublisherBuilder(
config, metrics, **kwargs)
return builder.build_publisher() | [
"def",
"get_gdns_publisher",
"(",
"config",
",",
"metrics",
",",
"*",
"*",
"kwargs",
")",
":",
"builder",
"=",
"gdns_publisher",
".",
"GDNSPublisherBuilder",
"(",
"config",
",",
"metrics",
",",
"*",
"*",
"kwargs",
")",
"return",
"builder",
".",
"build_publisher",
"(",
")"
] | Get a GDNSPublisher client.
A factory function that validates configuration and returns a
publisher client (:interface:`gordon.interfaces.IMessageHandler`)
provider.
Args:
config (dict): Google Cloud DNS API related configuration.
metrics (obj): :interface:`IMetricRelay` implementation.
kwargs (dict): Additional keyword arguments to pass to the
publisher.
Returns:
A :class:`GDNSPublisher` instance. | [
"Get",
"a",
"GDNSPublisher",
"client",
"."
] | 5ab19e3c2fe6ace72ee91e2ef1a1326f90b805da | https://github.com/spotify/gordon-gcp/blob/5ab19e3c2fe6ace72ee91e2ef1a1326f90b805da/src/gordon_gcp/plugins/service/__init__.py#L83-L100 | train |
openvax/mhcnames | mhcnames/normalization.py | normalize_allele_name | def normalize_allele_name(raw_allele, omit_dra1=False, infer_class2_pair=True):
"""MHC alleles are named with a frustratingly loose system. It's not uncommon
to see dozens of different forms for the same allele.
Note: this function works with both class I and class II allele names (including
alpha/beta pairs).
For example, these all refer to the same MHC sequence:
- HLA-A*02:01
- HLA-A02:01
- HLA-A:02:01
- HLA-A0201
- HLA-A00201
Additionally, for human alleles, the species prefix is often omitted:
- A*02:01
- A*00201
- A*0201
- A02:01
- A:02:01
- A:002:01
- A0201
- A00201
We might also encounter "6 digit" and "8 digit" MHC types (which specify
variants that don't affect amino acid sequence), for our purposes these
should be truncated to their "4-digit" forms:
- A*02:01:01
- A*02:01:01:01
There are also suffixes which we're going to ignore:
- HLA-A*02:01:01G
And lastly, for human alleles, there are serotypes which we'll treat
as approximately equal to a 4-digit type.
- HLA-A2
- A2
These should all be normalized to:
HLA-A*02:01
"""
cache_key = (raw_allele, omit_dra1, infer_class2_pair)
if cache_key in _normalized_allele_cache:
return _normalized_allele_cache[cache_key]
parsed_alleles = parse_classi_or_classii_allele_name(
raw_allele, infer_pair=infer_class2_pair)
species = parsed_alleles[0].species
normalized_list = [species]
# Optionally omit the alpha allele, e.g. for IEDB predictors.
if omit_dra1 and len(parsed_alleles) == 2:
alpha, beta = parsed_alleles
# by convention the alpha allelle is omitted since it's assumed
# to be DRA1*01:01
if alpha == _DRA1_0101:
parsed_alleles = [beta]
for parsed_allele in parsed_alleles:
if len(parsed_allele.allele_family) > 0:
normalized_list.append("%s*%s:%s" % (
parsed_allele.gene,
parsed_allele.allele_family,
parsed_allele.allele_code))
else:
# mice don't have allele families
# e.g. H-2-Kd
# species = H-2
# gene = K
# allele = d
normalized_list.append("%s%s" % (
parsed_allele.gene,
parsed_allele.allele_code))
normalized = "-".join(normalized_list)
_normalized_allele_cache[cache_key] = normalized
return normalized | python | def normalize_allele_name(raw_allele, omit_dra1=False, infer_class2_pair=True):
"""MHC alleles are named with a frustratingly loose system. It's not uncommon
to see dozens of different forms for the same allele.
Note: this function works with both class I and class II allele names (including
alpha/beta pairs).
For example, these all refer to the same MHC sequence:
- HLA-A*02:01
- HLA-A02:01
- HLA-A:02:01
- HLA-A0201
- HLA-A00201
Additionally, for human alleles, the species prefix is often omitted:
- A*02:01
- A*00201
- A*0201
- A02:01
- A:02:01
- A:002:01
- A0201
- A00201
We might also encounter "6 digit" and "8 digit" MHC types (which specify
variants that don't affect amino acid sequence), for our purposes these
should be truncated to their "4-digit" forms:
- A*02:01:01
- A*02:01:01:01
There are also suffixes which we're going to ignore:
- HLA-A*02:01:01G
And lastly, for human alleles, there are serotypes which we'll treat
as approximately equal to a 4-digit type.
- HLA-A2
- A2
These should all be normalized to:
HLA-A*02:01
"""
cache_key = (raw_allele, omit_dra1, infer_class2_pair)
if cache_key in _normalized_allele_cache:
return _normalized_allele_cache[cache_key]
parsed_alleles = parse_classi_or_classii_allele_name(
raw_allele, infer_pair=infer_class2_pair)
species = parsed_alleles[0].species
normalized_list = [species]
# Optionally omit the alpha allele, e.g. for IEDB predictors.
if omit_dra1 and len(parsed_alleles) == 2:
alpha, beta = parsed_alleles
# by convention the alpha allelle is omitted since it's assumed
# to be DRA1*01:01
if alpha == _DRA1_0101:
parsed_alleles = [beta]
for parsed_allele in parsed_alleles:
if len(parsed_allele.allele_family) > 0:
normalized_list.append("%s*%s:%s" % (
parsed_allele.gene,
parsed_allele.allele_family,
parsed_allele.allele_code))
else:
# mice don't have allele families
# e.g. H-2-Kd
# species = H-2
# gene = K
# allele = d
normalized_list.append("%s%s" % (
parsed_allele.gene,
parsed_allele.allele_code))
normalized = "-".join(normalized_list)
_normalized_allele_cache[cache_key] = normalized
return normalized | [
"def",
"normalize_allele_name",
"(",
"raw_allele",
",",
"omit_dra1",
"=",
"False",
",",
"infer_class2_pair",
"=",
"True",
")",
":",
"cache_key",
"=",
"(",
"raw_allele",
",",
"omit_dra1",
",",
"infer_class2_pair",
")",
"if",
"cache_key",
"in",
"_normalized_allele_cache",
":",
"return",
"_normalized_allele_cache",
"[",
"cache_key",
"]",
"parsed_alleles",
"=",
"parse_classi_or_classii_allele_name",
"(",
"raw_allele",
",",
"infer_pair",
"=",
"infer_class2_pair",
")",
"species",
"=",
"parsed_alleles",
"[",
"0",
"]",
".",
"species",
"normalized_list",
"=",
"[",
"species",
"]",
"# Optionally omit the alpha allele, e.g. for IEDB predictors.",
"if",
"omit_dra1",
"and",
"len",
"(",
"parsed_alleles",
")",
"==",
"2",
":",
"alpha",
",",
"beta",
"=",
"parsed_alleles",
"# by convention the alpha allelle is omitted since it's assumed",
"# to be DRA1*01:01",
"if",
"alpha",
"==",
"_DRA1_0101",
":",
"parsed_alleles",
"=",
"[",
"beta",
"]",
"for",
"parsed_allele",
"in",
"parsed_alleles",
":",
"if",
"len",
"(",
"parsed_allele",
".",
"allele_family",
")",
">",
"0",
":",
"normalized_list",
".",
"append",
"(",
"\"%s*%s:%s\"",
"%",
"(",
"parsed_allele",
".",
"gene",
",",
"parsed_allele",
".",
"allele_family",
",",
"parsed_allele",
".",
"allele_code",
")",
")",
"else",
":",
"# mice don't have allele families",
"# e.g. H-2-Kd",
"# species = H-2",
"# gene = K",
"# allele = d",
"normalized_list",
".",
"append",
"(",
"\"%s%s\"",
"%",
"(",
"parsed_allele",
".",
"gene",
",",
"parsed_allele",
".",
"allele_code",
")",
")",
"normalized",
"=",
"\"-\"",
".",
"join",
"(",
"normalized_list",
")",
"_normalized_allele_cache",
"[",
"cache_key",
"]",
"=",
"normalized",
"return",
"normalized"
] | MHC alleles are named with a frustratingly loose system. It's not uncommon
to see dozens of different forms for the same allele.
Note: this function works with both class I and class II allele names (including
alpha/beta pairs).
For example, these all refer to the same MHC sequence:
- HLA-A*02:01
- HLA-A02:01
- HLA-A:02:01
- HLA-A0201
- HLA-A00201
Additionally, for human alleles, the species prefix is often omitted:
- A*02:01
- A*00201
- A*0201
- A02:01
- A:02:01
- A:002:01
- A0201
- A00201
We might also encounter "6 digit" and "8 digit" MHC types (which specify
variants that don't affect amino acid sequence), for our purposes these
should be truncated to their "4-digit" forms:
- A*02:01:01
- A*02:01:01:01
There are also suffixes which we're going to ignore:
- HLA-A*02:01:01G
And lastly, for human alleles, there are serotypes which we'll treat
as approximately equal to a 4-digit type.
- HLA-A2
- A2
These should all be normalized to:
HLA-A*02:01 | [
"MHC",
"alleles",
"are",
"named",
"with",
"a",
"frustratingly",
"loose",
"system",
".",
"It",
"s",
"not",
"uncommon",
"to",
"see",
"dozens",
"of",
"different",
"forms",
"for",
"the",
"same",
"allele",
"."
] | 71694b9d620db68ceee44da1b8422ff436f15bd3 | https://github.com/openvax/mhcnames/blob/71694b9d620db68ceee44da1b8422ff436f15bd3/mhcnames/normalization.py#L28-L101 | train |
Bystroushaak/bottle-rest | docs/__init__.py | getVersion | def getVersion(data):
"""
Parse version from changelog written in RST format.
"""
data = data.splitlines()
return next((
v
for v, u in zip(data, data[1:]) # v = version, u = underline
if len(v) == len(u) and allSame(u) and hasDigit(v) and "." in v
)) | python | def getVersion(data):
"""
Parse version from changelog written in RST format.
"""
data = data.splitlines()
return next((
v
for v, u in zip(data, data[1:]) # v = version, u = underline
if len(v) == len(u) and allSame(u) and hasDigit(v) and "." in v
)) | [
"def",
"getVersion",
"(",
"data",
")",
":",
"data",
"=",
"data",
".",
"splitlines",
"(",
")",
"return",
"next",
"(",
"(",
"v",
"for",
"v",
",",
"u",
"in",
"zip",
"(",
"data",
",",
"data",
"[",
"1",
":",
"]",
")",
"# v = version, u = underline",
"if",
"len",
"(",
"v",
")",
"==",
"len",
"(",
"u",
")",
"and",
"allSame",
"(",
"u",
")",
"and",
"hasDigit",
"(",
"v",
")",
"and",
"\".\"",
"in",
"v",
")",
")"
] | Parse version from changelog written in RST format. | [
"Parse",
"version",
"from",
"changelog",
"written",
"in",
"RST",
"format",
"."
] | 428ef68a632ac092cdd49e2f03a664dbaccb0b86 | https://github.com/Bystroushaak/bottle-rest/blob/428ef68a632ac092cdd49e2f03a664dbaccb0b86/docs/__init__.py#L16-L25 | train |
openvax/mhcnames | mhcnames/species.py | split_species_prefix | def split_species_prefix(name, seps="-:_ "):
"""
Splits off the species component of the allele name from the rest of it.
Given "HLA-A*02:01", returns ("HLA", "A*02:01").
"""
species = None
name_upper = name.upper()
name_len = len(name)
for curr_prefix in _all_prefixes:
n = len(curr_prefix)
if name_len <= n:
continue
if name_upper.startswith(curr_prefix.upper()):
species = curr_prefix
name = name[n:].strip(seps)
break
return (species, name) | python | def split_species_prefix(name, seps="-:_ "):
"""
Splits off the species component of the allele name from the rest of it.
Given "HLA-A*02:01", returns ("HLA", "A*02:01").
"""
species = None
name_upper = name.upper()
name_len = len(name)
for curr_prefix in _all_prefixes:
n = len(curr_prefix)
if name_len <= n:
continue
if name_upper.startswith(curr_prefix.upper()):
species = curr_prefix
name = name[n:].strip(seps)
break
return (species, name) | [
"def",
"split_species_prefix",
"(",
"name",
",",
"seps",
"=",
"\"-:_ \"",
")",
":",
"species",
"=",
"None",
"name_upper",
"=",
"name",
".",
"upper",
"(",
")",
"name_len",
"=",
"len",
"(",
"name",
")",
"for",
"curr_prefix",
"in",
"_all_prefixes",
":",
"n",
"=",
"len",
"(",
"curr_prefix",
")",
"if",
"name_len",
"<=",
"n",
":",
"continue",
"if",
"name_upper",
".",
"startswith",
"(",
"curr_prefix",
".",
"upper",
"(",
")",
")",
":",
"species",
"=",
"curr_prefix",
"name",
"=",
"name",
"[",
"n",
":",
"]",
".",
"strip",
"(",
"seps",
")",
"break",
"return",
"(",
"species",
",",
"name",
")"
] | Splits off the species component of the allele name from the rest of it.
Given "HLA-A*02:01", returns ("HLA", "A*02:01"). | [
"Splits",
"off",
"the",
"species",
"component",
"of",
"the",
"allele",
"name",
"from",
"the",
"rest",
"of",
"it",
"."
] | 71694b9d620db68ceee44da1b8422ff436f15bd3 | https://github.com/openvax/mhcnames/blob/71694b9d620db68ceee44da1b8422ff436f15bd3/mhcnames/species.py#L93-L110 | train |
SergeySatskiy/cdm-flowparser | utils/run.py | formatFlow | def formatFlow(s):
"""Reformats the control flow output"""
result = ""
shifts = [] # positions of opening '<'
pos = 0 # symbol position in a line
nextIsList = False
def IsNextList(index, maxIndex, buf):
if index == maxIndex:
return False
if buf[index + 1] == '<':
return True
if index < maxIndex - 1:
if buf[index + 1] == '\n' and buf[index + 2] == '<':
return True
return False
maxIndex = len(s) - 1
for index in range(len(s)):
sym = s[index]
if sym == "\n":
lastShift = shifts[-1]
result += sym + lastShift * " "
pos = lastShift
if index < maxIndex:
if s[index + 1] not in "<>":
result += " "
pos += 1
continue
if sym == "<":
if nextIsList == False:
shifts.append(pos)
else:
nextIsList = False
pos += 1
result += sym
continue
if sym == ">":
shift = shifts[-1]
result += '\n'
result += shift * " "
pos = shift
result += sym
pos += 1
if IsNextList(index, maxIndex, s):
nextIsList = True
else:
del shifts[-1]
nextIsList = False
continue
result += sym
pos += 1
return result | python | def formatFlow(s):
"""Reformats the control flow output"""
result = ""
shifts = [] # positions of opening '<'
pos = 0 # symbol position in a line
nextIsList = False
def IsNextList(index, maxIndex, buf):
if index == maxIndex:
return False
if buf[index + 1] == '<':
return True
if index < maxIndex - 1:
if buf[index + 1] == '\n' and buf[index + 2] == '<':
return True
return False
maxIndex = len(s) - 1
for index in range(len(s)):
sym = s[index]
if sym == "\n":
lastShift = shifts[-1]
result += sym + lastShift * " "
pos = lastShift
if index < maxIndex:
if s[index + 1] not in "<>":
result += " "
pos += 1
continue
if sym == "<":
if nextIsList == False:
shifts.append(pos)
else:
nextIsList = False
pos += 1
result += sym
continue
if sym == ">":
shift = shifts[-1]
result += '\n'
result += shift * " "
pos = shift
result += sym
pos += 1
if IsNextList(index, maxIndex, s):
nextIsList = True
else:
del shifts[-1]
nextIsList = False
continue
result += sym
pos += 1
return result | [
"def",
"formatFlow",
"(",
"s",
")",
":",
"result",
"=",
"\"\"",
"shifts",
"=",
"[",
"]",
"# positions of opening '<'",
"pos",
"=",
"0",
"# symbol position in a line",
"nextIsList",
"=",
"False",
"def",
"IsNextList",
"(",
"index",
",",
"maxIndex",
",",
"buf",
")",
":",
"if",
"index",
"==",
"maxIndex",
":",
"return",
"False",
"if",
"buf",
"[",
"index",
"+",
"1",
"]",
"==",
"'<'",
":",
"return",
"True",
"if",
"index",
"<",
"maxIndex",
"-",
"1",
":",
"if",
"buf",
"[",
"index",
"+",
"1",
"]",
"==",
"'\\n'",
"and",
"buf",
"[",
"index",
"+",
"2",
"]",
"==",
"'<'",
":",
"return",
"True",
"return",
"False",
"maxIndex",
"=",
"len",
"(",
"s",
")",
"-",
"1",
"for",
"index",
"in",
"range",
"(",
"len",
"(",
"s",
")",
")",
":",
"sym",
"=",
"s",
"[",
"index",
"]",
"if",
"sym",
"==",
"\"\\n\"",
":",
"lastShift",
"=",
"shifts",
"[",
"-",
"1",
"]",
"result",
"+=",
"sym",
"+",
"lastShift",
"*",
"\" \"",
"pos",
"=",
"lastShift",
"if",
"index",
"<",
"maxIndex",
":",
"if",
"s",
"[",
"index",
"+",
"1",
"]",
"not",
"in",
"\"<>\"",
":",
"result",
"+=",
"\" \"",
"pos",
"+=",
"1",
"continue",
"if",
"sym",
"==",
"\"<\"",
":",
"if",
"nextIsList",
"==",
"False",
":",
"shifts",
".",
"append",
"(",
"pos",
")",
"else",
":",
"nextIsList",
"=",
"False",
"pos",
"+=",
"1",
"result",
"+=",
"sym",
"continue",
"if",
"sym",
"==",
"\">\"",
":",
"shift",
"=",
"shifts",
"[",
"-",
"1",
"]",
"result",
"+=",
"'\\n'",
"result",
"+=",
"shift",
"*",
"\" \"",
"pos",
"=",
"shift",
"result",
"+=",
"sym",
"pos",
"+=",
"1",
"if",
"IsNextList",
"(",
"index",
",",
"maxIndex",
",",
"s",
")",
":",
"nextIsList",
"=",
"True",
"else",
":",
"del",
"shifts",
"[",
"-",
"1",
"]",
"nextIsList",
"=",
"False",
"continue",
"result",
"+=",
"sym",
"pos",
"+=",
"1",
"return",
"result"
] | Reformats the control flow output | [
"Reformats",
"the",
"control",
"flow",
"output"
] | 0af20325eeafd964c684d66a31cd2efd51fd25a6 | https://github.com/SergeySatskiy/cdm-flowparser/blob/0af20325eeafd964c684d66a31cd2efd51fd25a6/utils/run.py#L26-L78 | train |
pqn/neural | neural/neural.py | NeuralNetwork.train | def train(self, training_set, iterations=500):
"""Trains itself using the sequence data."""
if len(training_set) > 2:
self.__X = np.matrix([example[0] for example in training_set])
if self.__num_labels == 1:
self.__y = np.matrix([example[1] for example in training_set]).reshape((-1, 1))
else:
eye = np.eye(self.__num_labels)
self.__y = np.matrix([eye[example[1]] for example in training_set])
else:
self.__X = np.matrix(training_set[0])
if self.__num_labels == 1:
self.__y = np.matrix(training_set[1]).reshape((-1, 1))
else:
eye = np.eye(self.__num_labels)
self.__y = np.matrix([eye[index] for sublist in training_set[1] for index in sublist])
self.__m = self.__X.shape[0]
self.__input_layer_size = self.__X.shape[1]
self.__sizes = [self.__input_layer_size]
self.__sizes.extend(self.__hidden_layers)
self.__sizes.append(self.__num_labels)
initial_theta = []
for count in range(len(self.__sizes) - 1):
epsilon = np.sqrt(6) / np.sqrt(self.__sizes[count]+self.__sizes[count+1])
initial_theta.append(np.random.rand(self.__sizes[count+1],self.__sizes[count]+1)*2*epsilon-epsilon)
initial_theta = self.__unroll(initial_theta)
self.__thetas = self.__roll(fmin_bfgs(self.__cost_function, initial_theta, fprime=self.__cost_grad_function, maxiter=iterations)) | python | def train(self, training_set, iterations=500):
"""Trains itself using the sequence data."""
if len(training_set) > 2:
self.__X = np.matrix([example[0] for example in training_set])
if self.__num_labels == 1:
self.__y = np.matrix([example[1] for example in training_set]).reshape((-1, 1))
else:
eye = np.eye(self.__num_labels)
self.__y = np.matrix([eye[example[1]] for example in training_set])
else:
self.__X = np.matrix(training_set[0])
if self.__num_labels == 1:
self.__y = np.matrix(training_set[1]).reshape((-1, 1))
else:
eye = np.eye(self.__num_labels)
self.__y = np.matrix([eye[index] for sublist in training_set[1] for index in sublist])
self.__m = self.__X.shape[0]
self.__input_layer_size = self.__X.shape[1]
self.__sizes = [self.__input_layer_size]
self.__sizes.extend(self.__hidden_layers)
self.__sizes.append(self.__num_labels)
initial_theta = []
for count in range(len(self.__sizes) - 1):
epsilon = np.sqrt(6) / np.sqrt(self.__sizes[count]+self.__sizes[count+1])
initial_theta.append(np.random.rand(self.__sizes[count+1],self.__sizes[count]+1)*2*epsilon-epsilon)
initial_theta = self.__unroll(initial_theta)
self.__thetas = self.__roll(fmin_bfgs(self.__cost_function, initial_theta, fprime=self.__cost_grad_function, maxiter=iterations)) | [
"def",
"train",
"(",
"self",
",",
"training_set",
",",
"iterations",
"=",
"500",
")",
":",
"if",
"len",
"(",
"training_set",
")",
">",
"2",
":",
"self",
".",
"__X",
"=",
"np",
".",
"matrix",
"(",
"[",
"example",
"[",
"0",
"]",
"for",
"example",
"in",
"training_set",
"]",
")",
"if",
"self",
".",
"__num_labels",
"==",
"1",
":",
"self",
".",
"__y",
"=",
"np",
".",
"matrix",
"(",
"[",
"example",
"[",
"1",
"]",
"for",
"example",
"in",
"training_set",
"]",
")",
".",
"reshape",
"(",
"(",
"-",
"1",
",",
"1",
")",
")",
"else",
":",
"eye",
"=",
"np",
".",
"eye",
"(",
"self",
".",
"__num_labels",
")",
"self",
".",
"__y",
"=",
"np",
".",
"matrix",
"(",
"[",
"eye",
"[",
"example",
"[",
"1",
"]",
"]",
"for",
"example",
"in",
"training_set",
"]",
")",
"else",
":",
"self",
".",
"__X",
"=",
"np",
".",
"matrix",
"(",
"training_set",
"[",
"0",
"]",
")",
"if",
"self",
".",
"__num_labels",
"==",
"1",
":",
"self",
".",
"__y",
"=",
"np",
".",
"matrix",
"(",
"training_set",
"[",
"1",
"]",
")",
".",
"reshape",
"(",
"(",
"-",
"1",
",",
"1",
")",
")",
"else",
":",
"eye",
"=",
"np",
".",
"eye",
"(",
"self",
".",
"__num_labels",
")",
"self",
".",
"__y",
"=",
"np",
".",
"matrix",
"(",
"[",
"eye",
"[",
"index",
"]",
"for",
"sublist",
"in",
"training_set",
"[",
"1",
"]",
"for",
"index",
"in",
"sublist",
"]",
")",
"self",
".",
"__m",
"=",
"self",
".",
"__X",
".",
"shape",
"[",
"0",
"]",
"self",
".",
"__input_layer_size",
"=",
"self",
".",
"__X",
".",
"shape",
"[",
"1",
"]",
"self",
".",
"__sizes",
"=",
"[",
"self",
".",
"__input_layer_size",
"]",
"self",
".",
"__sizes",
".",
"extend",
"(",
"self",
".",
"__hidden_layers",
")",
"self",
".",
"__sizes",
".",
"append",
"(",
"self",
".",
"__num_labels",
")",
"initial_theta",
"=",
"[",
"]",
"for",
"count",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"__sizes",
")",
"-",
"1",
")",
":",
"epsilon",
"=",
"np",
".",
"sqrt",
"(",
"6",
")",
"/",
"np",
".",
"sqrt",
"(",
"self",
".",
"__sizes",
"[",
"count",
"]",
"+",
"self",
".",
"__sizes",
"[",
"count",
"+",
"1",
"]",
")",
"initial_theta",
".",
"append",
"(",
"np",
".",
"random",
".",
"rand",
"(",
"self",
".",
"__sizes",
"[",
"count",
"+",
"1",
"]",
",",
"self",
".",
"__sizes",
"[",
"count",
"]",
"+",
"1",
")",
"*",
"2",
"*",
"epsilon",
"-",
"epsilon",
")",
"initial_theta",
"=",
"self",
".",
"__unroll",
"(",
"initial_theta",
")",
"self",
".",
"__thetas",
"=",
"self",
".",
"__roll",
"(",
"fmin_bfgs",
"(",
"self",
".",
"__cost_function",
",",
"initial_theta",
",",
"fprime",
"=",
"self",
".",
"__cost_grad_function",
",",
"maxiter",
"=",
"iterations",
")",
")"
] | Trains itself using the sequence data. | [
"Trains",
"itself",
"using",
"the",
"sequence",
"data",
"."
] | 505d8fb1c58868a7292c40caab4a22b577615886 | https://github.com/pqn/neural/blob/505d8fb1c58868a7292c40caab4a22b577615886/neural/neural.py#L20-L46 | train |
pqn/neural | neural/neural.py | NeuralNetwork.predict | def predict(self, X):
"""Returns predictions of input test cases."""
return self.__cost(self.__unroll(self.__thetas), 0, np.matrix(X)) | python | def predict(self, X):
"""Returns predictions of input test cases."""
return self.__cost(self.__unroll(self.__thetas), 0, np.matrix(X)) | [
"def",
"predict",
"(",
"self",
",",
"X",
")",
":",
"return",
"self",
".",
"__cost",
"(",
"self",
".",
"__unroll",
"(",
"self",
".",
"__thetas",
")",
",",
"0",
",",
"np",
".",
"matrix",
"(",
"X",
")",
")"
] | Returns predictions of input test cases. | [
"Returns",
"predictions",
"of",
"input",
"test",
"cases",
"."
] | 505d8fb1c58868a7292c40caab4a22b577615886 | https://github.com/pqn/neural/blob/505d8fb1c58868a7292c40caab4a22b577615886/neural/neural.py#L48-L50 | train |
pqn/neural | neural/neural.py | NeuralNetwork.__cost | def __cost(self, params, phase, X):
"""Computes activation, cost function, and derivative."""
params = self.__roll(params)
a = np.concatenate((np.ones((X.shape[0], 1)), X), axis=1) # This is a1
calculated_a = [a] # a1 is at index 0, a_n is at index n-1
calculated_z = [0] # There is no z1, z_n is at index n-1
for i, theta in enumerate(params): # calculated_a now contains a1, a2, a3 if there was only one hidden layer (two theta matrices)
z = calculated_a[-1] * theta.transpose() # z_n = a_n-1 * Theta_n-1'
calculated_z.append(z) # Save the new z_n
a = self.sigmoid(z) # a_n = sigmoid(z_n)
if i != len(params) - 1: # Don't append extra ones for the output layer
a = np.concatenate((np.ones((a.shape[0], 1)), a), axis=1) # Append the extra column of ones for all other layers
calculated_a.append(a) # Save the new a
if phase == 0:
if self.__num_labels > 1:
return np.argmax(calculated_a[-1], axis=1)
return np.round(calculated_a[-1])
J = np.sum(-np.multiply(self.__y, np.log(calculated_a[-1]))-np.multiply(1-self.__y, np.log(1-calculated_a[-1])))/self.__m; # Calculate cost
if self.__lambda != 0: # If we're using regularization...
J += np.sum([np.sum(np.power(theta[:,1:], 2)) for theta in params])*self.__lambda/(2.0*self.__m) # ...add it from all theta matrices
if phase == 1:
return J
reversed_d = []
reversed_theta_grad = []
for i in range(len(params)): # For once per theta matrix...
if i == 0: # ...if it's the first one...
d = calculated_a[-1] - self.__y # ...initialize the error...
else: # ...otherwise d_n-1 = d_n * Theta_n-1[missing ones] .* sigmoid(z_n-1)
d = np.multiply(reversed_d[-1]*params[-i][:,1:], self.sigmoid_grad(calculated_z[-1-i])) # With i=1/1 hidden layer we're getting Theta2 at index -1, and z2 at index -2
reversed_d.append(d)
theta_grad = reversed_d[-1].transpose() * calculated_a[-i-2] / self.__m
if self.__lambda != 0:
theta_grad += np.concatenate((np.zeros((params[-1-i].shape[0], 1)), params[-1-i][:,1:]), axis=1) * self.__lambda / self.__m# regularization
reversed_theta_grad.append(theta_grad)
theta_grad = self.__unroll(reversed(reversed_theta_grad))
return theta_grad | python | def __cost(self, params, phase, X):
"""Computes activation, cost function, and derivative."""
params = self.__roll(params)
a = np.concatenate((np.ones((X.shape[0], 1)), X), axis=1) # This is a1
calculated_a = [a] # a1 is at index 0, a_n is at index n-1
calculated_z = [0] # There is no z1, z_n is at index n-1
for i, theta in enumerate(params): # calculated_a now contains a1, a2, a3 if there was only one hidden layer (two theta matrices)
z = calculated_a[-1] * theta.transpose() # z_n = a_n-1 * Theta_n-1'
calculated_z.append(z) # Save the new z_n
a = self.sigmoid(z) # a_n = sigmoid(z_n)
if i != len(params) - 1: # Don't append extra ones for the output layer
a = np.concatenate((np.ones((a.shape[0], 1)), a), axis=1) # Append the extra column of ones for all other layers
calculated_a.append(a) # Save the new a
if phase == 0:
if self.__num_labels > 1:
return np.argmax(calculated_a[-1], axis=1)
return np.round(calculated_a[-1])
J = np.sum(-np.multiply(self.__y, np.log(calculated_a[-1]))-np.multiply(1-self.__y, np.log(1-calculated_a[-1])))/self.__m; # Calculate cost
if self.__lambda != 0: # If we're using regularization...
J += np.sum([np.sum(np.power(theta[:,1:], 2)) for theta in params])*self.__lambda/(2.0*self.__m) # ...add it from all theta matrices
if phase == 1:
return J
reversed_d = []
reversed_theta_grad = []
for i in range(len(params)): # For once per theta matrix...
if i == 0: # ...if it's the first one...
d = calculated_a[-1] - self.__y # ...initialize the error...
else: # ...otherwise d_n-1 = d_n * Theta_n-1[missing ones] .* sigmoid(z_n-1)
d = np.multiply(reversed_d[-1]*params[-i][:,1:], self.sigmoid_grad(calculated_z[-1-i])) # With i=1/1 hidden layer we're getting Theta2 at index -1, and z2 at index -2
reversed_d.append(d)
theta_grad = reversed_d[-1].transpose() * calculated_a[-i-2] / self.__m
if self.__lambda != 0:
theta_grad += np.concatenate((np.zeros((params[-1-i].shape[0], 1)), params[-1-i][:,1:]), axis=1) * self.__lambda / self.__m# regularization
reversed_theta_grad.append(theta_grad)
theta_grad = self.__unroll(reversed(reversed_theta_grad))
return theta_grad | [
"def",
"__cost",
"(",
"self",
",",
"params",
",",
"phase",
",",
"X",
")",
":",
"params",
"=",
"self",
".",
"__roll",
"(",
"params",
")",
"a",
"=",
"np",
".",
"concatenate",
"(",
"(",
"np",
".",
"ones",
"(",
"(",
"X",
".",
"shape",
"[",
"0",
"]",
",",
"1",
")",
")",
",",
"X",
")",
",",
"axis",
"=",
"1",
")",
"# This is a1",
"calculated_a",
"=",
"[",
"a",
"]",
"# a1 is at index 0, a_n is at index n-1",
"calculated_z",
"=",
"[",
"0",
"]",
"# There is no z1, z_n is at index n-1",
"for",
"i",
",",
"theta",
"in",
"enumerate",
"(",
"params",
")",
":",
"# calculated_a now contains a1, a2, a3 if there was only one hidden layer (two theta matrices)",
"z",
"=",
"calculated_a",
"[",
"-",
"1",
"]",
"*",
"theta",
".",
"transpose",
"(",
")",
"# z_n = a_n-1 * Theta_n-1'",
"calculated_z",
".",
"append",
"(",
"z",
")",
"# Save the new z_n",
"a",
"=",
"self",
".",
"sigmoid",
"(",
"z",
")",
"# a_n = sigmoid(z_n)",
"if",
"i",
"!=",
"len",
"(",
"params",
")",
"-",
"1",
":",
"# Don't append extra ones for the output layer",
"a",
"=",
"np",
".",
"concatenate",
"(",
"(",
"np",
".",
"ones",
"(",
"(",
"a",
".",
"shape",
"[",
"0",
"]",
",",
"1",
")",
")",
",",
"a",
")",
",",
"axis",
"=",
"1",
")",
"# Append the extra column of ones for all other layers",
"calculated_a",
".",
"append",
"(",
"a",
")",
"# Save the new a",
"if",
"phase",
"==",
"0",
":",
"if",
"self",
".",
"__num_labels",
">",
"1",
":",
"return",
"np",
".",
"argmax",
"(",
"calculated_a",
"[",
"-",
"1",
"]",
",",
"axis",
"=",
"1",
")",
"return",
"np",
".",
"round",
"(",
"calculated_a",
"[",
"-",
"1",
"]",
")",
"J",
"=",
"np",
".",
"sum",
"(",
"-",
"np",
".",
"multiply",
"(",
"self",
".",
"__y",
",",
"np",
".",
"log",
"(",
"calculated_a",
"[",
"-",
"1",
"]",
")",
")",
"-",
"np",
".",
"multiply",
"(",
"1",
"-",
"self",
".",
"__y",
",",
"np",
".",
"log",
"(",
"1",
"-",
"calculated_a",
"[",
"-",
"1",
"]",
")",
")",
")",
"/",
"self",
".",
"__m",
"# Calculate cost",
"if",
"self",
".",
"__lambda",
"!=",
"0",
":",
"# If we're using regularization...",
"J",
"+=",
"np",
".",
"sum",
"(",
"[",
"np",
".",
"sum",
"(",
"np",
".",
"power",
"(",
"theta",
"[",
":",
",",
"1",
":",
"]",
",",
"2",
")",
")",
"for",
"theta",
"in",
"params",
"]",
")",
"*",
"self",
".",
"__lambda",
"/",
"(",
"2.0",
"*",
"self",
".",
"__m",
")",
"# ...add it from all theta matrices",
"if",
"phase",
"==",
"1",
":",
"return",
"J",
"reversed_d",
"=",
"[",
"]",
"reversed_theta_grad",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"params",
")",
")",
":",
"# For once per theta matrix...",
"if",
"i",
"==",
"0",
":",
"# ...if it's the first one...",
"d",
"=",
"calculated_a",
"[",
"-",
"1",
"]",
"-",
"self",
".",
"__y",
"# ...initialize the error...",
"else",
":",
"# ...otherwise d_n-1 = d_n * Theta_n-1[missing ones] .* sigmoid(z_n-1)",
"d",
"=",
"np",
".",
"multiply",
"(",
"reversed_d",
"[",
"-",
"1",
"]",
"*",
"params",
"[",
"-",
"i",
"]",
"[",
":",
",",
"1",
":",
"]",
",",
"self",
".",
"sigmoid_grad",
"(",
"calculated_z",
"[",
"-",
"1",
"-",
"i",
"]",
")",
")",
"# With i=1/1 hidden layer we're getting Theta2 at index -1, and z2 at index -2",
"reversed_d",
".",
"append",
"(",
"d",
")",
"theta_grad",
"=",
"reversed_d",
"[",
"-",
"1",
"]",
".",
"transpose",
"(",
")",
"*",
"calculated_a",
"[",
"-",
"i",
"-",
"2",
"]",
"/",
"self",
".",
"__m",
"if",
"self",
".",
"__lambda",
"!=",
"0",
":",
"theta_grad",
"+=",
"np",
".",
"concatenate",
"(",
"(",
"np",
".",
"zeros",
"(",
"(",
"params",
"[",
"-",
"1",
"-",
"i",
"]",
".",
"shape",
"[",
"0",
"]",
",",
"1",
")",
")",
",",
"params",
"[",
"-",
"1",
"-",
"i",
"]",
"[",
":",
",",
"1",
":",
"]",
")",
",",
"axis",
"=",
"1",
")",
"*",
"self",
".",
"__lambda",
"/",
"self",
".",
"__m",
"# regularization",
"reversed_theta_grad",
".",
"append",
"(",
"theta_grad",
")",
"theta_grad",
"=",
"self",
".",
"__unroll",
"(",
"reversed",
"(",
"reversed_theta_grad",
")",
")",
"return",
"theta_grad"
] | Computes activation, cost function, and derivative. | [
"Computes",
"activation",
"cost",
"function",
"and",
"derivative",
"."
] | 505d8fb1c58868a7292c40caab4a22b577615886 | https://github.com/pqn/neural/blob/505d8fb1c58868a7292c40caab4a22b577615886/neural/neural.py#L60-L99 | train |
pqn/neural | neural/neural.py | NeuralNetwork.__roll | def __roll(self, unrolled):
"""Converts parameter array back into matrices."""
rolled = []
index = 0
for count in range(len(self.__sizes) - 1):
in_size = self.__sizes[count]
out_size = self.__sizes[count+1]
theta_unrolled = np.matrix(unrolled[index:index+(in_size+1)*out_size])
theta_rolled = theta_unrolled.reshape((out_size, in_size+1))
rolled.append(theta_rolled)
index += (in_size + 1) * out_size
return rolled | python | def __roll(self, unrolled):
"""Converts parameter array back into matrices."""
rolled = []
index = 0
for count in range(len(self.__sizes) - 1):
in_size = self.__sizes[count]
out_size = self.__sizes[count+1]
theta_unrolled = np.matrix(unrolled[index:index+(in_size+1)*out_size])
theta_rolled = theta_unrolled.reshape((out_size, in_size+1))
rolled.append(theta_rolled)
index += (in_size + 1) * out_size
return rolled | [
"def",
"__roll",
"(",
"self",
",",
"unrolled",
")",
":",
"rolled",
"=",
"[",
"]",
"index",
"=",
"0",
"for",
"count",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"__sizes",
")",
"-",
"1",
")",
":",
"in_size",
"=",
"self",
".",
"__sizes",
"[",
"count",
"]",
"out_size",
"=",
"self",
".",
"__sizes",
"[",
"count",
"+",
"1",
"]",
"theta_unrolled",
"=",
"np",
".",
"matrix",
"(",
"unrolled",
"[",
"index",
":",
"index",
"+",
"(",
"in_size",
"+",
"1",
")",
"*",
"out_size",
"]",
")",
"theta_rolled",
"=",
"theta_unrolled",
".",
"reshape",
"(",
"(",
"out_size",
",",
"in_size",
"+",
"1",
")",
")",
"rolled",
".",
"append",
"(",
"theta_rolled",
")",
"index",
"+=",
"(",
"in_size",
"+",
"1",
")",
"*",
"out_size",
"return",
"rolled"
] | Converts parameter array back into matrices. | [
"Converts",
"parameter",
"array",
"back",
"into",
"matrices",
"."
] | 505d8fb1c58868a7292c40caab4a22b577615886 | https://github.com/pqn/neural/blob/505d8fb1c58868a7292c40caab4a22b577615886/neural/neural.py#L101-L112 | train |
pqn/neural | neural/neural.py | NeuralNetwork.__unroll | def __unroll(self, rolled):
"""Converts parameter matrices into an array."""
return np.array(np.concatenate([matrix.flatten() for matrix in rolled], axis=1)).reshape(-1) | python | def __unroll(self, rolled):
"""Converts parameter matrices into an array."""
return np.array(np.concatenate([matrix.flatten() for matrix in rolled], axis=1)).reshape(-1) | [
"def",
"__unroll",
"(",
"self",
",",
"rolled",
")",
":",
"return",
"np",
".",
"array",
"(",
"np",
".",
"concatenate",
"(",
"[",
"matrix",
".",
"flatten",
"(",
")",
"for",
"matrix",
"in",
"rolled",
"]",
",",
"axis",
"=",
"1",
")",
")",
".",
"reshape",
"(",
"-",
"1",
")"
] | Converts parameter matrices into an array. | [
"Converts",
"parameter",
"matrices",
"into",
"an",
"array",
"."
] | 505d8fb1c58868a7292c40caab4a22b577615886 | https://github.com/pqn/neural/blob/505d8fb1c58868a7292c40caab4a22b577615886/neural/neural.py#L114-L116 | train |
pqn/neural | neural/neural.py | NeuralNetwork.sigmoid_grad | def sigmoid_grad(self, z):
"""Gradient of sigmoid function."""
return np.multiply(self.sigmoid(z), 1-self.sigmoid(z)) | python | def sigmoid_grad(self, z):
"""Gradient of sigmoid function."""
return np.multiply(self.sigmoid(z), 1-self.sigmoid(z)) | [
"def",
"sigmoid_grad",
"(",
"self",
",",
"z",
")",
":",
"return",
"np",
".",
"multiply",
"(",
"self",
".",
"sigmoid",
"(",
"z",
")",
",",
"1",
"-",
"self",
".",
"sigmoid",
"(",
"z",
")",
")"
] | Gradient of sigmoid function. | [
"Gradient",
"of",
"sigmoid",
"function",
"."
] | 505d8fb1c58868a7292c40caab4a22b577615886 | https://github.com/pqn/neural/blob/505d8fb1c58868a7292c40caab4a22b577615886/neural/neural.py#L122-L124 | train |
pqn/neural | neural/neural.py | NeuralNetwork.grad | def grad(self, params, epsilon=0.0001):
"""Used to check gradient estimation through slope approximation."""
grad = []
for x in range(len(params)):
temp = np.copy(params)
temp[x] += epsilon
temp2 = np.copy(params)
temp2[x] -= epsilon
grad.append((self.__cost_function(temp)-self.__cost_function(temp2))/(2*epsilon))
return np.array(grad) | python | def grad(self, params, epsilon=0.0001):
"""Used to check gradient estimation through slope approximation."""
grad = []
for x in range(len(params)):
temp = np.copy(params)
temp[x] += epsilon
temp2 = np.copy(params)
temp2[x] -= epsilon
grad.append((self.__cost_function(temp)-self.__cost_function(temp2))/(2*epsilon))
return np.array(grad) | [
"def",
"grad",
"(",
"self",
",",
"params",
",",
"epsilon",
"=",
"0.0001",
")",
":",
"grad",
"=",
"[",
"]",
"for",
"x",
"in",
"range",
"(",
"len",
"(",
"params",
")",
")",
":",
"temp",
"=",
"np",
".",
"copy",
"(",
"params",
")",
"temp",
"[",
"x",
"]",
"+=",
"epsilon",
"temp2",
"=",
"np",
".",
"copy",
"(",
"params",
")",
"temp2",
"[",
"x",
"]",
"-=",
"epsilon",
"grad",
".",
"append",
"(",
"(",
"self",
".",
"__cost_function",
"(",
"temp",
")",
"-",
"self",
".",
"__cost_function",
"(",
"temp2",
")",
")",
"/",
"(",
"2",
"*",
"epsilon",
")",
")",
"return",
"np",
".",
"array",
"(",
"grad",
")"
] | Used to check gradient estimation through slope approximation. | [
"Used",
"to",
"check",
"gradient",
"estimation",
"through",
"slope",
"approximation",
"."
] | 505d8fb1c58868a7292c40caab4a22b577615886 | https://github.com/pqn/neural/blob/505d8fb1c58868a7292c40caab4a22b577615886/neural/neural.py#L126-L135 | train |
rfverbruggen/rachiopy | rachiopy/notification.py | Notification.postWebhook | def postWebhook(self, dev_id, external_id, url, event_types):
"""Add a webhook to a device.
externalId can be used as opaque data that
is tied to your company, and passed back in each webhook event
response.
"""
path = 'notification/webhook'
payload = {'device': {'id': dev_id}, 'externalId': external_id,
'url': url, 'eventTypes': event_types}
return self.rachio.post(path, payload) | python | def postWebhook(self, dev_id, external_id, url, event_types):
"""Add a webhook to a device.
externalId can be used as opaque data that
is tied to your company, and passed back in each webhook event
response.
"""
path = 'notification/webhook'
payload = {'device': {'id': dev_id}, 'externalId': external_id,
'url': url, 'eventTypes': event_types}
return self.rachio.post(path, payload) | [
"def",
"postWebhook",
"(",
"self",
",",
"dev_id",
",",
"external_id",
",",
"url",
",",
"event_types",
")",
":",
"path",
"=",
"'notification/webhook'",
"payload",
"=",
"{",
"'device'",
":",
"{",
"'id'",
":",
"dev_id",
"}",
",",
"'externalId'",
":",
"external_id",
",",
"'url'",
":",
"url",
",",
"'eventTypes'",
":",
"event_types",
"}",
"return",
"self",
".",
"rachio",
".",
"post",
"(",
"path",
",",
"payload",
")"
] | Add a webhook to a device.
externalId can be used as opaque data that
is tied to your company, and passed back in each webhook event
response. | [
"Add",
"a",
"webhook",
"to",
"a",
"device",
"."
] | c91abc9984f0f453e60fa905285c1b640c3390ae | https://github.com/rfverbruggen/rachiopy/blob/c91abc9984f0f453e60fa905285c1b640c3390ae/rachiopy/notification.py#L24-L34 | train |
rfverbruggen/rachiopy | rachiopy/notification.py | Notification.putWebhook | def putWebhook(self, hook_id, external_id, url, event_types):
"""Update a webhook."""
path = 'notification/webhook'
payload = {'id': hook_id, 'externalId': external_id,
'url': url, 'eventTypes': event_types}
return self.rachio.put(path, payload) | python | def putWebhook(self, hook_id, external_id, url, event_types):
"""Update a webhook."""
path = 'notification/webhook'
payload = {'id': hook_id, 'externalId': external_id,
'url': url, 'eventTypes': event_types}
return self.rachio.put(path, payload) | [
"def",
"putWebhook",
"(",
"self",
",",
"hook_id",
",",
"external_id",
",",
"url",
",",
"event_types",
")",
":",
"path",
"=",
"'notification/webhook'",
"payload",
"=",
"{",
"'id'",
":",
"hook_id",
",",
"'externalId'",
":",
"external_id",
",",
"'url'",
":",
"url",
",",
"'eventTypes'",
":",
"event_types",
"}",
"return",
"self",
".",
"rachio",
".",
"put",
"(",
"path",
",",
"payload",
")"
] | Update a webhook. | [
"Update",
"a",
"webhook",
"."
] | c91abc9984f0f453e60fa905285c1b640c3390ae | https://github.com/rfverbruggen/rachiopy/blob/c91abc9984f0f453e60fa905285c1b640c3390ae/rachiopy/notification.py#L36-L41 | train |
rfverbruggen/rachiopy | rachiopy/notification.py | Notification.deleteWebhook | def deleteWebhook(self, hook_id):
"""Remove a webhook."""
path = '/'.join(['notification', 'webhook', hook_id])
return self.rachio.delete(path) | python | def deleteWebhook(self, hook_id):
"""Remove a webhook."""
path = '/'.join(['notification', 'webhook', hook_id])
return self.rachio.delete(path) | [
"def",
"deleteWebhook",
"(",
"self",
",",
"hook_id",
")",
":",
"path",
"=",
"'/'",
".",
"join",
"(",
"[",
"'notification'",
",",
"'webhook'",
",",
"hook_id",
"]",
")",
"return",
"self",
".",
"rachio",
".",
"delete",
"(",
"path",
")"
] | Remove a webhook. | [
"Remove",
"a",
"webhook",
"."
] | c91abc9984f0f453e60fa905285c1b640c3390ae | https://github.com/rfverbruggen/rachiopy/blob/c91abc9984f0f453e60fa905285c1b640c3390ae/rachiopy/notification.py#L43-L46 | train |
rfverbruggen/rachiopy | rachiopy/notification.py | Notification.get | def get(self, hook_id):
"""Get a webhook."""
path = '/'.join(['notification', 'webhook', hook_id])
return self.rachio.get(path) | python | def get(self, hook_id):
"""Get a webhook."""
path = '/'.join(['notification', 'webhook', hook_id])
return self.rachio.get(path) | [
"def",
"get",
"(",
"self",
",",
"hook_id",
")",
":",
"path",
"=",
"'/'",
".",
"join",
"(",
"[",
"'notification'",
",",
"'webhook'",
",",
"hook_id",
"]",
")",
"return",
"self",
".",
"rachio",
".",
"get",
"(",
"path",
")"
] | Get a webhook. | [
"Get",
"a",
"webhook",
"."
] | c91abc9984f0f453e60fa905285c1b640c3390ae | https://github.com/rfverbruggen/rachiopy/blob/c91abc9984f0f453e60fa905285c1b640c3390ae/rachiopy/notification.py#L48-L51 | train |
OrangeTux/einder | einder/client.py | Client.connect | def connect(self):
""" Connect sets up the connection with the Horizon box. """
self.con = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.con.connect((self.ip, self.port))
log.debug('Connected with set-top box at %s:%s.',
self.ip, self.port) | python | def connect(self):
""" Connect sets up the connection with the Horizon box. """
self.con = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.con.connect((self.ip, self.port))
log.debug('Connected with set-top box at %s:%s.',
self.ip, self.port) | [
"def",
"connect",
"(",
"self",
")",
":",
"self",
".",
"con",
"=",
"socket",
".",
"socket",
"(",
"socket",
".",
"AF_INET",
",",
"socket",
".",
"SOCK_STREAM",
")",
"self",
".",
"con",
".",
"connect",
"(",
"(",
"self",
".",
"ip",
",",
"self",
".",
"port",
")",
")",
"log",
".",
"debug",
"(",
"'Connected with set-top box at %s:%s.'",
",",
"self",
".",
"ip",
",",
"self",
".",
"port",
")"
] | Connect sets up the connection with the Horizon box. | [
"Connect",
"sets",
"up",
"the",
"connection",
"with",
"the",
"Horizon",
"box",
"."
] | deb2c5f79a69b684257fe939659c3bd751556fd5 | https://github.com/OrangeTux/einder/blob/deb2c5f79a69b684257fe939659c3bd751556fd5/einder/client.py#L23-L29 | train |
OrangeTux/einder | einder/client.py | Client.disconnect | def disconnect(self):
""" Disconnect closes the connection to the Horizon box. """
if self.con is not None:
self.con.close()
log.debug('Closed connection with with set-top box at %s:%s.',
self.ip, self.port) | python | def disconnect(self):
""" Disconnect closes the connection to the Horizon box. """
if self.con is not None:
self.con.close()
log.debug('Closed connection with with set-top box at %s:%s.',
self.ip, self.port) | [
"def",
"disconnect",
"(",
"self",
")",
":",
"if",
"self",
".",
"con",
"is",
"not",
"None",
":",
"self",
".",
"con",
".",
"close",
"(",
")",
"log",
".",
"debug",
"(",
"'Closed connection with with set-top box at %s:%s.'",
",",
"self",
".",
"ip",
",",
"self",
".",
"port",
")"
] | Disconnect closes the connection to the Horizon box. | [
"Disconnect",
"closes",
"the",
"connection",
"to",
"the",
"Horizon",
"box",
"."
] | deb2c5f79a69b684257fe939659c3bd751556fd5 | https://github.com/OrangeTux/einder/blob/deb2c5f79a69b684257fe939659c3bd751556fd5/einder/client.py#L31-L36 | train |
OrangeTux/einder | einder/client.py | Client.authorize | def authorize(self):
""" Use the magic of a unicorn and summon the set-top box to listen
to us.
/
,.. /
,' ';
,,.__ _,' /'; .
:',' ~~~~ '. '~
:' ( ) )::,
'. '. .=----=..-~ .;'
' ;' :: ':. '"
(: ': ;)
\\ '" ./
'" '"
Seriously, I've no idea what I'm doing here.
"""
# Read the version of the set-top box and write it back. Why? I've no
# idea.
version = self.con.makefile().readline()
self.con.send(version.encode())
# The set-top box returns with 2 bytes. I've no idea what they mean.
self.con.recv(2)
# The following reads and writes are used to authenticate. But I don't
# fully understand what is going on.
self.con.send(struct.pack('>B', 1))
msg = self.con.recv(4)
response = struct.unpack(">I", msg)
if response[0] != 0:
log.debug("Failed to authorize with set-top at %s:%s.",
self.ip, self.port)
raise AuthenticationError()
# Dunno where this is good for. But otherwise the client doesn't work.
self.con.send(b'0')
log.debug('Authorized succesfully with set-top box at %s:%s.',
self.ip, self.port) | python | def authorize(self):
""" Use the magic of a unicorn and summon the set-top box to listen
to us.
/
,.. /
,' ';
,,.__ _,' /'; .
:',' ~~~~ '. '~
:' ( ) )::,
'. '. .=----=..-~ .;'
' ;' :: ':. '"
(: ': ;)
\\ '" ./
'" '"
Seriously, I've no idea what I'm doing here.
"""
# Read the version of the set-top box and write it back. Why? I've no
# idea.
version = self.con.makefile().readline()
self.con.send(version.encode())
# The set-top box returns with 2 bytes. I've no idea what they mean.
self.con.recv(2)
# The following reads and writes are used to authenticate. But I don't
# fully understand what is going on.
self.con.send(struct.pack('>B', 1))
msg = self.con.recv(4)
response = struct.unpack(">I", msg)
if response[0] != 0:
log.debug("Failed to authorize with set-top at %s:%s.",
self.ip, self.port)
raise AuthenticationError()
# Dunno where this is good for. But otherwise the client doesn't work.
self.con.send(b'0')
log.debug('Authorized succesfully with set-top box at %s:%s.',
self.ip, self.port) | [
"def",
"authorize",
"(",
"self",
")",
":",
"# Read the version of the set-top box and write it back. Why? I've no",
"# idea.",
"version",
"=",
"self",
".",
"con",
".",
"makefile",
"(",
")",
".",
"readline",
"(",
")",
"self",
".",
"con",
".",
"send",
"(",
"version",
".",
"encode",
"(",
")",
")",
"# The set-top box returns with 2 bytes. I've no idea what they mean.",
"self",
".",
"con",
".",
"recv",
"(",
"2",
")",
"# The following reads and writes are used to authenticate. But I don't",
"# fully understand what is going on.",
"self",
".",
"con",
".",
"send",
"(",
"struct",
".",
"pack",
"(",
"'>B'",
",",
"1",
")",
")",
"msg",
"=",
"self",
".",
"con",
".",
"recv",
"(",
"4",
")",
"response",
"=",
"struct",
".",
"unpack",
"(",
"\">I\"",
",",
"msg",
")",
"if",
"response",
"[",
"0",
"]",
"!=",
"0",
":",
"log",
".",
"debug",
"(",
"\"Failed to authorize with set-top at %s:%s.\"",
",",
"self",
".",
"ip",
",",
"self",
".",
"port",
")",
"raise",
"AuthenticationError",
"(",
")",
"# Dunno where this is good for. But otherwise the client doesn't work.",
"self",
".",
"con",
".",
"send",
"(",
"b'0'",
")",
"log",
".",
"debug",
"(",
"'Authorized succesfully with set-top box at %s:%s.'",
",",
"self",
".",
"ip",
",",
"self",
".",
"port",
")"
] | Use the magic of a unicorn and summon the set-top box to listen
to us.
/
,.. /
,' ';
,,.__ _,' /'; .
:',' ~~~~ '. '~
:' ( ) )::,
'. '. .=----=..-~ .;'
' ;' :: ':. '"
(: ': ;)
\\ '" ./
'" '"
Seriously, I've no idea what I'm doing here. | [
"Use",
"the",
"magic",
"of",
"a",
"unicorn",
"and",
"summon",
"the",
"set",
"-",
"top",
"box",
"to",
"listen",
"to",
"us",
"."
] | deb2c5f79a69b684257fe939659c3bd751556fd5 | https://github.com/OrangeTux/einder/blob/deb2c5f79a69b684257fe939659c3bd751556fd5/einder/client.py#L38-L78 | train |
OrangeTux/einder | einder/client.py | Client.send_key | def send_key(self, key):
""" Send a key to the Horizon box. """
cmd = struct.pack(">BBBBBBH", 4, 1, 0, 0, 0, 0, key)
self.con.send(cmd)
cmd = struct.pack(">BBBBBBH", 4, 0, 0, 0, 0, 0, key)
self.con.send(cmd) | python | def send_key(self, key):
""" Send a key to the Horizon box. """
cmd = struct.pack(">BBBBBBH", 4, 1, 0, 0, 0, 0, key)
self.con.send(cmd)
cmd = struct.pack(">BBBBBBH", 4, 0, 0, 0, 0, 0, key)
self.con.send(cmd) | [
"def",
"send_key",
"(",
"self",
",",
"key",
")",
":",
"cmd",
"=",
"struct",
".",
"pack",
"(",
"\">BBBBBBH\"",
",",
"4",
",",
"1",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"key",
")",
"self",
".",
"con",
".",
"send",
"(",
"cmd",
")",
"cmd",
"=",
"struct",
".",
"pack",
"(",
"\">BBBBBBH\"",
",",
"4",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"key",
")",
"self",
".",
"con",
".",
"send",
"(",
"cmd",
")"
] | Send a key to the Horizon box. | [
"Send",
"a",
"key",
"to",
"the",
"Horizon",
"box",
"."
] | deb2c5f79a69b684257fe939659c3bd751556fd5 | https://github.com/OrangeTux/einder/blob/deb2c5f79a69b684257fe939659c3bd751556fd5/einder/client.py#L80-L86 | train |
OrangeTux/einder | einder/client.py | Client.is_powered_on | def is_powered_on(self):
""" Get power status of device.
The set-top box can't explicitly powered on or powered off the device.
The power can only be toggled.
To find out the power status of the device a little trick is used.
When the set-top box is powered a web server is running on port 62137
of the device server a file at /DeviceDescription.xml. By checking if
this file is available the power status can be determined.
:return: Boolean indicitation if device is powered on.
"""
host = '{0}:62137'.format(self.ip)
try:
HTTPConnection(host, timeout=2).\
request('GET', '/DeviceDescription.xml')
except (ConnectionRefusedError, socket.timeout):
log.debug('Set-top box at %s:%s is powered off.',
self.ip, self.port)
return False
log.debug('Set-top box at %s:%s is powered on.', self.ip, self.port)
return True | python | def is_powered_on(self):
""" Get power status of device.
The set-top box can't explicitly powered on or powered off the device.
The power can only be toggled.
To find out the power status of the device a little trick is used.
When the set-top box is powered a web server is running on port 62137
of the device server a file at /DeviceDescription.xml. By checking if
this file is available the power status can be determined.
:return: Boolean indicitation if device is powered on.
"""
host = '{0}:62137'.format(self.ip)
try:
HTTPConnection(host, timeout=2).\
request('GET', '/DeviceDescription.xml')
except (ConnectionRefusedError, socket.timeout):
log.debug('Set-top box at %s:%s is powered off.',
self.ip, self.port)
return False
log.debug('Set-top box at %s:%s is powered on.', self.ip, self.port)
return True | [
"def",
"is_powered_on",
"(",
"self",
")",
":",
"host",
"=",
"'{0}:62137'",
".",
"format",
"(",
"self",
".",
"ip",
")",
"try",
":",
"HTTPConnection",
"(",
"host",
",",
"timeout",
"=",
"2",
")",
".",
"request",
"(",
"'GET'",
",",
"'/DeviceDescription.xml'",
")",
"except",
"(",
"ConnectionRefusedError",
",",
"socket",
".",
"timeout",
")",
":",
"log",
".",
"debug",
"(",
"'Set-top box at %s:%s is powered off.'",
",",
"self",
".",
"ip",
",",
"self",
".",
"port",
")",
"return",
"False",
"log",
".",
"debug",
"(",
"'Set-top box at %s:%s is powered on.'",
",",
"self",
".",
"ip",
",",
"self",
".",
"port",
")",
"return",
"True"
] | Get power status of device.
The set-top box can't explicitly powered on or powered off the device.
The power can only be toggled.
To find out the power status of the device a little trick is used.
When the set-top box is powered a web server is running on port 62137
of the device server a file at /DeviceDescription.xml. By checking if
this file is available the power status can be determined.
:return: Boolean indicitation if device is powered on. | [
"Get",
"power",
"status",
"of",
"device",
"."
] | deb2c5f79a69b684257fe939659c3bd751556fd5 | https://github.com/OrangeTux/einder/blob/deb2c5f79a69b684257fe939659c3bd751556fd5/einder/client.py#L88-L112 | train |
OrangeTux/einder | einder/client.py | Client.power_on | def power_on(self):
""" Power on the set-top box. """
if not self.is_powered_on():
log.debug('Powering on set-top box at %s:%s.', self.ip, self.port)
self.send_key(keys.POWER) | python | def power_on(self):
""" Power on the set-top box. """
if not self.is_powered_on():
log.debug('Powering on set-top box at %s:%s.', self.ip, self.port)
self.send_key(keys.POWER) | [
"def",
"power_on",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_powered_on",
"(",
")",
":",
"log",
".",
"debug",
"(",
"'Powering on set-top box at %s:%s.'",
",",
"self",
".",
"ip",
",",
"self",
".",
"port",
")",
"self",
".",
"send_key",
"(",
"keys",
".",
"POWER",
")"
] | Power on the set-top box. | [
"Power",
"on",
"the",
"set",
"-",
"top",
"box",
"."
] | deb2c5f79a69b684257fe939659c3bd751556fd5 | https://github.com/OrangeTux/einder/blob/deb2c5f79a69b684257fe939659c3bd751556fd5/einder/client.py#L114-L118 | train |
OrangeTux/einder | einder/client.py | Client.select_channel | def select_channel(self, channel):
""" Select a channel.
:param channel: Number of channel.
"""
for i in str(channel):
key = int(i) + 0xe300
self.send_key(key) | python | def select_channel(self, channel):
""" Select a channel.
:param channel: Number of channel.
"""
for i in str(channel):
key = int(i) + 0xe300
self.send_key(key) | [
"def",
"select_channel",
"(",
"self",
",",
"channel",
")",
":",
"for",
"i",
"in",
"str",
"(",
"channel",
")",
":",
"key",
"=",
"int",
"(",
"i",
")",
"+",
"0xe300",
"self",
".",
"send_key",
"(",
"key",
")"
] | Select a channel.
:param channel: Number of channel. | [
"Select",
"a",
"channel",
"."
] | deb2c5f79a69b684257fe939659c3bd751556fd5 | https://github.com/OrangeTux/einder/blob/deb2c5f79a69b684257fe939659c3bd751556fd5/einder/client.py#L126-L133 | train |
inveniosoftware/invenio-webhooks | invenio_webhooks/signatures.py | get_hmac | def get_hmac(message):
"""Calculate HMAC value of message using ``WEBHOOKS_SECRET_KEY``.
:param message: String to calculate HMAC for.
"""
key = current_app.config['WEBHOOKS_SECRET_KEY']
hmac_value = hmac.new(
key.encode('utf-8') if hasattr(key, 'encode') else key,
message.encode('utf-8') if hasattr(message, 'encode') else message,
sha1
).hexdigest()
return hmac_value | python | def get_hmac(message):
"""Calculate HMAC value of message using ``WEBHOOKS_SECRET_KEY``.
:param message: String to calculate HMAC for.
"""
key = current_app.config['WEBHOOKS_SECRET_KEY']
hmac_value = hmac.new(
key.encode('utf-8') if hasattr(key, 'encode') else key,
message.encode('utf-8') if hasattr(message, 'encode') else message,
sha1
).hexdigest()
return hmac_value | [
"def",
"get_hmac",
"(",
"message",
")",
":",
"key",
"=",
"current_app",
".",
"config",
"[",
"'WEBHOOKS_SECRET_KEY'",
"]",
"hmac_value",
"=",
"hmac",
".",
"new",
"(",
"key",
".",
"encode",
"(",
"'utf-8'",
")",
"if",
"hasattr",
"(",
"key",
",",
"'encode'",
")",
"else",
"key",
",",
"message",
".",
"encode",
"(",
"'utf-8'",
")",
"if",
"hasattr",
"(",
"message",
",",
"'encode'",
")",
"else",
"message",
",",
"sha1",
")",
".",
"hexdigest",
"(",
")",
"return",
"hmac_value"
] | Calculate HMAC value of message using ``WEBHOOKS_SECRET_KEY``.
:param message: String to calculate HMAC for. | [
"Calculate",
"HMAC",
"value",
"of",
"message",
"using",
"WEBHOOKS_SECRET_KEY",
"."
] | f407cb2245464543ee474a81189fb9d3978bdde5 | https://github.com/inveniosoftware/invenio-webhooks/blob/f407cb2245464543ee474a81189fb9d3978bdde5/invenio_webhooks/signatures.py#L33-L44 | train |
inveniosoftware/invenio-webhooks | invenio_webhooks/signatures.py | check_x_hub_signature | def check_x_hub_signature(signature, message):
"""Check X-Hub-Signature used by GitHub to sign requests.
:param signature: HMAC signature extracted from request.
:param message: Request message.
"""
hmac_value = get_hmac(message)
if hmac_value == signature or \
(signature.find('=') > -1 and
hmac_value == signature[signature.find('=') + 1:]):
return True
return False | python | def check_x_hub_signature(signature, message):
"""Check X-Hub-Signature used by GitHub to sign requests.
:param signature: HMAC signature extracted from request.
:param message: Request message.
"""
hmac_value = get_hmac(message)
if hmac_value == signature or \
(signature.find('=') > -1 and
hmac_value == signature[signature.find('=') + 1:]):
return True
return False | [
"def",
"check_x_hub_signature",
"(",
"signature",
",",
"message",
")",
":",
"hmac_value",
"=",
"get_hmac",
"(",
"message",
")",
"if",
"hmac_value",
"==",
"signature",
"or",
"(",
"signature",
".",
"find",
"(",
"'='",
")",
">",
"-",
"1",
"and",
"hmac_value",
"==",
"signature",
"[",
"signature",
".",
"find",
"(",
"'='",
")",
"+",
"1",
":",
"]",
")",
":",
"return",
"True",
"return",
"False"
] | Check X-Hub-Signature used by GitHub to sign requests.
:param signature: HMAC signature extracted from request.
:param message: Request message. | [
"Check",
"X",
"-",
"Hub",
"-",
"Signature",
"used",
"by",
"GitHub",
"to",
"sign",
"requests",
"."
] | f407cb2245464543ee474a81189fb9d3978bdde5 | https://github.com/inveniosoftware/invenio-webhooks/blob/f407cb2245464543ee474a81189fb9d3978bdde5/invenio_webhooks/signatures.py#L47-L58 | train |
spotify/gordon-gcp | src/gordon_gcp/clients/gcrm.py | GCRMClient.list_all_active_projects | async def list_all_active_projects(self, page_size=1000):
"""Get all active projects.
You can find the endpoint documentation `here <https://cloud.
google.com/resource-manager/reference/rest/v1/projects/list>`__.
Args:
page_size (int): hint for the client to only retrieve up to
this number of results per API call.
Returns:
list(dicts): all active projects
"""
url = f'{self.BASE_URL}/{self.api_version}/projects'
params = {'pageSize': page_size}
responses = await self.list_all(url, params)
projects = self._parse_rsps_for_projects(responses)
return [
project for project in projects
if project.get('lifecycleState', '').lower() == 'active'
] | python | async def list_all_active_projects(self, page_size=1000):
"""Get all active projects.
You can find the endpoint documentation `here <https://cloud.
google.com/resource-manager/reference/rest/v1/projects/list>`__.
Args:
page_size (int): hint for the client to only retrieve up to
this number of results per API call.
Returns:
list(dicts): all active projects
"""
url = f'{self.BASE_URL}/{self.api_version}/projects'
params = {'pageSize': page_size}
responses = await self.list_all(url, params)
projects = self._parse_rsps_for_projects(responses)
return [
project for project in projects
if project.get('lifecycleState', '').lower() == 'active'
] | [
"async",
"def",
"list_all_active_projects",
"(",
"self",
",",
"page_size",
"=",
"1000",
")",
":",
"url",
"=",
"f'{self.BASE_URL}/{self.api_version}/projects'",
"params",
"=",
"{",
"'pageSize'",
":",
"page_size",
"}",
"responses",
"=",
"await",
"self",
".",
"list_all",
"(",
"url",
",",
"params",
")",
"projects",
"=",
"self",
".",
"_parse_rsps_for_projects",
"(",
"responses",
")",
"return",
"[",
"project",
"for",
"project",
"in",
"projects",
"if",
"project",
".",
"get",
"(",
"'lifecycleState'",
",",
"''",
")",
".",
"lower",
"(",
")",
"==",
"'active'",
"]"
] | Get all active projects.
You can find the endpoint documentation `here <https://cloud.
google.com/resource-manager/reference/rest/v1/projects/list>`__.
Args:
page_size (int): hint for the client to only retrieve up to
this number of results per API call.
Returns:
list(dicts): all active projects | [
"Get",
"all",
"active",
"projects",
"."
] | 5ab19e3c2fe6ace72ee91e2ef1a1326f90b805da | https://github.com/spotify/gordon-gcp/blob/5ab19e3c2fe6ace72ee91e2ef1a1326f90b805da/src/gordon_gcp/clients/gcrm.py#L85-L105 | train |
dstanek/snake-guice | snakeguice/modules.py | Module.install | def install(self, binder, module):
"""Add another module's bindings to a binder."""
ModuleAdapter(module, self._injector).configure(binder) | python | def install(self, binder, module):
"""Add another module's bindings to a binder."""
ModuleAdapter(module, self._injector).configure(binder) | [
"def",
"install",
"(",
"self",
",",
"binder",
",",
"module",
")",
":",
"ModuleAdapter",
"(",
"module",
",",
"self",
".",
"_injector",
")",
".",
"configure",
"(",
"binder",
")"
] | Add another module's bindings to a binder. | [
"Add",
"another",
"module",
"s",
"bindings",
"to",
"a",
"binder",
"."
] | d20b62de3ee31e84119c801756398c35ed803fb3 | https://github.com/dstanek/snake-guice/blob/d20b62de3ee31e84119c801756398c35ed803fb3/snakeguice/modules.py#L23-L25 | train |
dstanek/snake-guice | snakeguice/modules.py | PrivateModule.expose | def expose(self, binder, interface, annotation=None):
"""Expose the child injector to the parent inject for a binding."""
private_module = self
class Provider(object):
def get(self):
return private_module.private_injector.get_instance(
interface, annotation)
self.original_binder.bind(interface, annotated_with=annotation,
to_provider=Provider) | python | def expose(self, binder, interface, annotation=None):
"""Expose the child injector to the parent inject for a binding."""
private_module = self
class Provider(object):
def get(self):
return private_module.private_injector.get_instance(
interface, annotation)
self.original_binder.bind(interface, annotated_with=annotation,
to_provider=Provider) | [
"def",
"expose",
"(",
"self",
",",
"binder",
",",
"interface",
",",
"annotation",
"=",
"None",
")",
":",
"private_module",
"=",
"self",
"class",
"Provider",
"(",
"object",
")",
":",
"def",
"get",
"(",
"self",
")",
":",
"return",
"private_module",
".",
"private_injector",
".",
"get_instance",
"(",
"interface",
",",
"annotation",
")",
"self",
".",
"original_binder",
".",
"bind",
"(",
"interface",
",",
"annotated_with",
"=",
"annotation",
",",
"to_provider",
"=",
"Provider",
")"
] | Expose the child injector to the parent inject for a binding. | [
"Expose",
"the",
"child",
"injector",
"to",
"the",
"parent",
"inject",
"for",
"a",
"binding",
"."
] | d20b62de3ee31e84119c801756398c35ed803fb3 | https://github.com/dstanek/snake-guice/blob/d20b62de3ee31e84119c801756398c35ed803fb3/snakeguice/modules.py#L57-L66 | train |
spotify/gordon-gcp | src/gordon_gcp/plugins/service/enricher.py | GCEEnricherBuilder._call_validators | def _call_validators(self):
"""Actually run all the validations.
Returns:
list(str): Error messages from the validators.
"""
msg = []
msg.extend(self._validate_keyfile())
msg.extend(self._validate_dns_zone())
msg.extend(self._validate_retries())
msg.extend(self._validate_project())
return msg | python | def _call_validators(self):
"""Actually run all the validations.
Returns:
list(str): Error messages from the validators.
"""
msg = []
msg.extend(self._validate_keyfile())
msg.extend(self._validate_dns_zone())
msg.extend(self._validate_retries())
msg.extend(self._validate_project())
return msg | [
"def",
"_call_validators",
"(",
"self",
")",
":",
"msg",
"=",
"[",
"]",
"msg",
".",
"extend",
"(",
"self",
".",
"_validate_keyfile",
"(",
")",
")",
"msg",
".",
"extend",
"(",
"self",
".",
"_validate_dns_zone",
"(",
")",
")",
"msg",
".",
"extend",
"(",
"self",
".",
"_validate_retries",
"(",
")",
")",
"msg",
".",
"extend",
"(",
"self",
".",
"_validate_project",
"(",
")",
")",
"return",
"msg"
] | Actually run all the validations.
Returns:
list(str): Error messages from the validators. | [
"Actually",
"run",
"all",
"the",
"validations",
"."
] | 5ab19e3c2fe6ace72ee91e2ef1a1326f90b805da | https://github.com/spotify/gordon-gcp/blob/5ab19e3c2fe6ace72ee91e2ef1a1326f90b805da/src/gordon_gcp/plugins/service/enricher.py#L93-L104 | train |
gitenberg-dev/gitberg | gitenberg/util/catalog.py | BookMetadata.parse_rdf | def parse_rdf(self):
""" Parses the relevant PG rdf file
"""
try:
self.metadata = pg_rdf_to_json(self.rdf_path)
except IOError as e:
raise NoRDFError(e)
if not self.authnames():
self.author = ''
elif len(self.authnames()) == 1:
self.author = self.authnames()[0]
else:
self.author = "Various" | python | def parse_rdf(self):
""" Parses the relevant PG rdf file
"""
try:
self.metadata = pg_rdf_to_json(self.rdf_path)
except IOError as e:
raise NoRDFError(e)
if not self.authnames():
self.author = ''
elif len(self.authnames()) == 1:
self.author = self.authnames()[0]
else:
self.author = "Various" | [
"def",
"parse_rdf",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"metadata",
"=",
"pg_rdf_to_json",
"(",
"self",
".",
"rdf_path",
")",
"except",
"IOError",
"as",
"e",
":",
"raise",
"NoRDFError",
"(",
"e",
")",
"if",
"not",
"self",
".",
"authnames",
"(",
")",
":",
"self",
".",
"author",
"=",
"''",
"elif",
"len",
"(",
"self",
".",
"authnames",
"(",
")",
")",
"==",
"1",
":",
"self",
".",
"author",
"=",
"self",
".",
"authnames",
"(",
")",
"[",
"0",
"]",
"else",
":",
"self",
".",
"author",
"=",
"\"Various\""
] | Parses the relevant PG rdf file | [
"Parses",
"the",
"relevant",
"PG",
"rdf",
"file"
] | 3f6db8b5a22ccdd2110d3199223c30db4e558b5c | https://github.com/gitenberg-dev/gitberg/blob/3f6db8b5a22ccdd2110d3199223c30db4e558b5c/gitenberg/util/catalog.py#L93-L106 | train |
gitenberg-dev/gitberg | gitenberg/util/catalog.py | Rdfcache.download_rdf | def download_rdf(self, force=False):
"""Ensures a fresh-enough RDF file is downloaded and extracted.
Returns True on error."""
if self.downloading:
return True
if not force and (os.path.exists(RDF_PATH) and
(time.time() - os.path.getmtime(RDF_PATH)) < RDF_MAX_AGE):
return False
self.downloading = True
logging.info('Re-downloading RDF library from %s' % RDF_URL)
try:
shutil.rmtree(os.path.join(self.rdf_library_dir, 'cache'))
except OSError as e:
# Ignore not finding the directory to remove.
if e.errno != errno.ENOENT:
raise
try:
with open(RDF_PATH, 'w') as f:
with requests.get(RDF_URL, stream=True) as r:
shutil.copyfileobj(r.raw, f)
except requests.exceptions.RequestException as e:
logging.error(e)
return True
try:
with tarfile.open(RDF_PATH, 'r') as f:
f.extractall(self.rdf_library_dir)
except tarfile.TarError as e:
logging.error(e)
try:
os.unlink(RDF_PATH)
except:
pass
return True
self.downloading = False
return False | python | def download_rdf(self, force=False):
"""Ensures a fresh-enough RDF file is downloaded and extracted.
Returns True on error."""
if self.downloading:
return True
if not force and (os.path.exists(RDF_PATH) and
(time.time() - os.path.getmtime(RDF_PATH)) < RDF_MAX_AGE):
return False
self.downloading = True
logging.info('Re-downloading RDF library from %s' % RDF_URL)
try:
shutil.rmtree(os.path.join(self.rdf_library_dir, 'cache'))
except OSError as e:
# Ignore not finding the directory to remove.
if e.errno != errno.ENOENT:
raise
try:
with open(RDF_PATH, 'w') as f:
with requests.get(RDF_URL, stream=True) as r:
shutil.copyfileobj(r.raw, f)
except requests.exceptions.RequestException as e:
logging.error(e)
return True
try:
with tarfile.open(RDF_PATH, 'r') as f:
f.extractall(self.rdf_library_dir)
except tarfile.TarError as e:
logging.error(e)
try:
os.unlink(RDF_PATH)
except:
pass
return True
self.downloading = False
return False | [
"def",
"download_rdf",
"(",
"self",
",",
"force",
"=",
"False",
")",
":",
"if",
"self",
".",
"downloading",
":",
"return",
"True",
"if",
"not",
"force",
"and",
"(",
"os",
".",
"path",
".",
"exists",
"(",
"RDF_PATH",
")",
"and",
"(",
"time",
".",
"time",
"(",
")",
"-",
"os",
".",
"path",
".",
"getmtime",
"(",
"RDF_PATH",
")",
")",
"<",
"RDF_MAX_AGE",
")",
":",
"return",
"False",
"self",
".",
"downloading",
"=",
"True",
"logging",
".",
"info",
"(",
"'Re-downloading RDF library from %s'",
"%",
"RDF_URL",
")",
"try",
":",
"shutil",
".",
"rmtree",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"rdf_library_dir",
",",
"'cache'",
")",
")",
"except",
"OSError",
"as",
"e",
":",
"# Ignore not finding the directory to remove.",
"if",
"e",
".",
"errno",
"!=",
"errno",
".",
"ENOENT",
":",
"raise",
"try",
":",
"with",
"open",
"(",
"RDF_PATH",
",",
"'w'",
")",
"as",
"f",
":",
"with",
"requests",
".",
"get",
"(",
"RDF_URL",
",",
"stream",
"=",
"True",
")",
"as",
"r",
":",
"shutil",
".",
"copyfileobj",
"(",
"r",
".",
"raw",
",",
"f",
")",
"except",
"requests",
".",
"exceptions",
".",
"RequestException",
"as",
"e",
":",
"logging",
".",
"error",
"(",
"e",
")",
"return",
"True",
"try",
":",
"with",
"tarfile",
".",
"open",
"(",
"RDF_PATH",
",",
"'r'",
")",
"as",
"f",
":",
"f",
".",
"extractall",
"(",
"self",
".",
"rdf_library_dir",
")",
"except",
"tarfile",
".",
"TarError",
"as",
"e",
":",
"logging",
".",
"error",
"(",
"e",
")",
"try",
":",
"os",
".",
"unlink",
"(",
"RDF_PATH",
")",
"except",
":",
"pass",
"return",
"True",
"self",
".",
"downloading",
"=",
"False",
"return",
"False"
] | Ensures a fresh-enough RDF file is downloaded and extracted.
Returns True on error. | [
"Ensures",
"a",
"fresh",
"-",
"enough",
"RDF",
"file",
"is",
"downloaded",
"and",
"extracted",
"."
] | 3f6db8b5a22ccdd2110d3199223c30db4e558b5c | https://github.com/gitenberg-dev/gitberg/blob/3f6db8b5a22ccdd2110d3199223c30db4e558b5c/gitenberg/util/catalog.py#L134-L172 | train |
Scille/autobahn-sync | autobahn_sync/core.py | AutobahnSync.run | def run(self, url=DEFAULT_AUTOBAHN_ROUTER, realm=DEFAULT_AUTOBAHN_REALM,
authmethods=None, authid=None, authrole=None, authextra=None,
blocking=False, callback=None, **kwargs):
"""
Start the background twisted thread and create the WAMP connection
:param blocking: If ``False`` (default) this method will spawn a new
thread that will be used to run the callback events (e.i. registered and
subscribed functions). If ``True`` this method will not returns and
use the current thread to run the callbacks.
:param callback: This callback will be called once init is done, use it
with ``blocking=True`` to put your WAMP related init
"""
_init_crochet(in_twisted=False)
self._bootstrap(blocking, url=url, realm=realm,
authmethods=authmethods, authid=authid, authrole=authrole,
authextra=authextra, **kwargs)
if callback:
callback()
self._callbacks_runner.start() | python | def run(self, url=DEFAULT_AUTOBAHN_ROUTER, realm=DEFAULT_AUTOBAHN_REALM,
authmethods=None, authid=None, authrole=None, authextra=None,
blocking=False, callback=None, **kwargs):
"""
Start the background twisted thread and create the WAMP connection
:param blocking: If ``False`` (default) this method will spawn a new
thread that will be used to run the callback events (e.i. registered and
subscribed functions). If ``True`` this method will not returns and
use the current thread to run the callbacks.
:param callback: This callback will be called once init is done, use it
with ``blocking=True`` to put your WAMP related init
"""
_init_crochet(in_twisted=False)
self._bootstrap(blocking, url=url, realm=realm,
authmethods=authmethods, authid=authid, authrole=authrole,
authextra=authextra, **kwargs)
if callback:
callback()
self._callbacks_runner.start() | [
"def",
"run",
"(",
"self",
",",
"url",
"=",
"DEFAULT_AUTOBAHN_ROUTER",
",",
"realm",
"=",
"DEFAULT_AUTOBAHN_REALM",
",",
"authmethods",
"=",
"None",
",",
"authid",
"=",
"None",
",",
"authrole",
"=",
"None",
",",
"authextra",
"=",
"None",
",",
"blocking",
"=",
"False",
",",
"callback",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"_init_crochet",
"(",
"in_twisted",
"=",
"False",
")",
"self",
".",
"_bootstrap",
"(",
"blocking",
",",
"url",
"=",
"url",
",",
"realm",
"=",
"realm",
",",
"authmethods",
"=",
"authmethods",
",",
"authid",
"=",
"authid",
",",
"authrole",
"=",
"authrole",
",",
"authextra",
"=",
"authextra",
",",
"*",
"*",
"kwargs",
")",
"if",
"callback",
":",
"callback",
"(",
")",
"self",
".",
"_callbacks_runner",
".",
"start",
"(",
")"
] | Start the background twisted thread and create the WAMP connection
:param blocking: If ``False`` (default) this method will spawn a new
thread that will be used to run the callback events (e.i. registered and
subscribed functions). If ``True`` this method will not returns and
use the current thread to run the callbacks.
:param callback: This callback will be called once init is done, use it
with ``blocking=True`` to put your WAMP related init | [
"Start",
"the",
"background",
"twisted",
"thread",
"and",
"create",
"the",
"WAMP",
"connection"
] | d75fceff0d1aee61fa6dd0168eb1cd40794ad827 | https://github.com/Scille/autobahn-sync/blob/d75fceff0d1aee61fa6dd0168eb1cd40794ad827/autobahn_sync/core.py#L91-L110 | train |
Scille/autobahn-sync | autobahn_sync/core.py | AutobahnSync.stop | def stop(self):
"""
Terminate the WAMP session
.. note::
If the :meth:`AutobahnSync.run` has been run with ``blocking=True``,
it will returns then.
"""
if not self._started:
raise NotRunningError("This AutobahnSync instance is not started")
self._callbacks_runner.stop()
self._started = False | python | def stop(self):
"""
Terminate the WAMP session
.. note::
If the :meth:`AutobahnSync.run` has been run with ``blocking=True``,
it will returns then.
"""
if not self._started:
raise NotRunningError("This AutobahnSync instance is not started")
self._callbacks_runner.stop()
self._started = False | [
"def",
"stop",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_started",
":",
"raise",
"NotRunningError",
"(",
"\"This AutobahnSync instance is not started\"",
")",
"self",
".",
"_callbacks_runner",
".",
"stop",
"(",
")",
"self",
".",
"_started",
"=",
"False"
] | Terminate the WAMP session
.. note::
If the :meth:`AutobahnSync.run` has been run with ``blocking=True``,
it will returns then. | [
"Terminate",
"the",
"WAMP",
"session"
] | d75fceff0d1aee61fa6dd0168eb1cd40794ad827 | https://github.com/Scille/autobahn-sync/blob/d75fceff0d1aee61fa6dd0168eb1cd40794ad827/autobahn_sync/core.py#L112-L123 | train |
inveniosoftware/invenio-webhooks | invenio_webhooks/models.py | process_event | def process_event(self, event_id):
"""Process event in Celery."""
with db.session.begin_nested():
event = Event.query.get(event_id)
event._celery_task = self # internal binding to a Celery task
event.receiver.run(event) # call run directly to avoid circular calls
flag_modified(event, 'response')
flag_modified(event, 'response_headers')
db.session.add(event)
db.session.commit() | python | def process_event(self, event_id):
"""Process event in Celery."""
with db.session.begin_nested():
event = Event.query.get(event_id)
event._celery_task = self # internal binding to a Celery task
event.receiver.run(event) # call run directly to avoid circular calls
flag_modified(event, 'response')
flag_modified(event, 'response_headers')
db.session.add(event)
db.session.commit() | [
"def",
"process_event",
"(",
"self",
",",
"event_id",
")",
":",
"with",
"db",
".",
"session",
".",
"begin_nested",
"(",
")",
":",
"event",
"=",
"Event",
".",
"query",
".",
"get",
"(",
"event_id",
")",
"event",
".",
"_celery_task",
"=",
"self",
"# internal binding to a Celery task",
"event",
".",
"receiver",
".",
"run",
"(",
"event",
")",
"# call run directly to avoid circular calls",
"flag_modified",
"(",
"event",
",",
"'response'",
")",
"flag_modified",
"(",
"event",
",",
"'response_headers'",
")",
"db",
".",
"session",
".",
"add",
"(",
"event",
")",
"db",
".",
"session",
".",
"commit",
"(",
")"
] | Process event in Celery. | [
"Process",
"event",
"in",
"Celery",
"."
] | f407cb2245464543ee474a81189fb9d3978bdde5 | https://github.com/inveniosoftware/invenio-webhooks/blob/f407cb2245464543ee474a81189fb9d3978bdde5/invenio_webhooks/models.py#L143-L152 | train |
inveniosoftware/invenio-webhooks | invenio_webhooks/models.py | _json_column | def _json_column(**kwargs):
"""Return JSON column."""
return db.Column(
JSONType().with_variant(
postgresql.JSON(none_as_null=True),
'postgresql',
),
nullable=True,
**kwargs
) | python | def _json_column(**kwargs):
"""Return JSON column."""
return db.Column(
JSONType().with_variant(
postgresql.JSON(none_as_null=True),
'postgresql',
),
nullable=True,
**kwargs
) | [
"def",
"_json_column",
"(",
"*",
"*",
"kwargs",
")",
":",
"return",
"db",
".",
"Column",
"(",
"JSONType",
"(",
")",
".",
"with_variant",
"(",
"postgresql",
".",
"JSON",
"(",
"none_as_null",
"=",
"True",
")",
",",
"'postgresql'",
",",
")",
",",
"nullable",
"=",
"True",
",",
"*",
"*",
"kwargs",
")"
] | Return JSON column. | [
"Return",
"JSON",
"column",
"."
] | f407cb2245464543ee474a81189fb9d3978bdde5 | https://github.com/inveniosoftware/invenio-webhooks/blob/f407cb2245464543ee474a81189fb9d3978bdde5/invenio_webhooks/models.py#L197-L206 | train |
inveniosoftware/invenio-webhooks | invenio_webhooks/models.py | Receiver.delete | def delete(self, event):
"""Mark event as deleted."""
assert self.receiver_id == event.receiver_id
event.response = {'status': 410, 'message': 'Gone.'}
event.response_code = 410 | python | def delete(self, event):
"""Mark event as deleted."""
assert self.receiver_id == event.receiver_id
event.response = {'status': 410, 'message': 'Gone.'}
event.response_code = 410 | [
"def",
"delete",
"(",
"self",
",",
"event",
")",
":",
"assert",
"self",
".",
"receiver_id",
"==",
"event",
".",
"receiver_id",
"event",
".",
"response",
"=",
"{",
"'status'",
":",
"410",
",",
"'message'",
":",
"'Gone.'",
"}",
"event",
".",
"response_code",
"=",
"410"
] | Mark event as deleted. | [
"Mark",
"event",
"as",
"deleted",
"."
] | f407cb2245464543ee474a81189fb9d3978bdde5 | https://github.com/inveniosoftware/invenio-webhooks/blob/f407cb2245464543ee474a81189fb9d3978bdde5/invenio_webhooks/models.py#L81-L85 | train |
inveniosoftware/invenio-webhooks | invenio_webhooks/models.py | Receiver.get_hook_url | def get_hook_url(self, access_token):
"""Get URL for webhook.
In debug and testing mode the hook URL can be overwritten using
``WEBHOOKS_DEBUG_RECEIVER_URLS`` configuration variable to allow
testing webhooks via services such as e.g. Ultrahook.
.. code-block:: python
WEBHOOKS_DEBUG_RECEIVER_URLS = dict(
github='http://github.userid.ultrahook.com',
)
"""
# Allow overwriting hook URL in debug mode.
if (current_app.debug or current_app.testing) and \
current_app.config.get('WEBHOOKS_DEBUG_RECEIVER_URLS', None):
url_pattern = current_app.config[
'WEBHOOKS_DEBUG_RECEIVER_URLS'].get(self.receiver_id, None)
if url_pattern:
return url_pattern % dict(token=access_token)
return url_for(
'invenio_webhooks.event_list',
receiver_id=self.receiver_id,
access_token=access_token,
_external=True
) | python | def get_hook_url(self, access_token):
"""Get URL for webhook.
In debug and testing mode the hook URL can be overwritten using
``WEBHOOKS_DEBUG_RECEIVER_URLS`` configuration variable to allow
testing webhooks via services such as e.g. Ultrahook.
.. code-block:: python
WEBHOOKS_DEBUG_RECEIVER_URLS = dict(
github='http://github.userid.ultrahook.com',
)
"""
# Allow overwriting hook URL in debug mode.
if (current_app.debug or current_app.testing) and \
current_app.config.get('WEBHOOKS_DEBUG_RECEIVER_URLS', None):
url_pattern = current_app.config[
'WEBHOOKS_DEBUG_RECEIVER_URLS'].get(self.receiver_id, None)
if url_pattern:
return url_pattern % dict(token=access_token)
return url_for(
'invenio_webhooks.event_list',
receiver_id=self.receiver_id,
access_token=access_token,
_external=True
) | [
"def",
"get_hook_url",
"(",
"self",
",",
"access_token",
")",
":",
"# Allow overwriting hook URL in debug mode.",
"if",
"(",
"current_app",
".",
"debug",
"or",
"current_app",
".",
"testing",
")",
"and",
"current_app",
".",
"config",
".",
"get",
"(",
"'WEBHOOKS_DEBUG_RECEIVER_URLS'",
",",
"None",
")",
":",
"url_pattern",
"=",
"current_app",
".",
"config",
"[",
"'WEBHOOKS_DEBUG_RECEIVER_URLS'",
"]",
".",
"get",
"(",
"self",
".",
"receiver_id",
",",
"None",
")",
"if",
"url_pattern",
":",
"return",
"url_pattern",
"%",
"dict",
"(",
"token",
"=",
"access_token",
")",
"return",
"url_for",
"(",
"'invenio_webhooks.event_list'",
",",
"receiver_id",
"=",
"self",
".",
"receiver_id",
",",
"access_token",
"=",
"access_token",
",",
"_external",
"=",
"True",
")"
] | Get URL for webhook.
In debug and testing mode the hook URL can be overwritten using
``WEBHOOKS_DEBUG_RECEIVER_URLS`` configuration variable to allow
testing webhooks via services such as e.g. Ultrahook.
.. code-block:: python
WEBHOOKS_DEBUG_RECEIVER_URLS = dict(
github='http://github.userid.ultrahook.com',
) | [
"Get",
"URL",
"for",
"webhook",
"."
] | f407cb2245464543ee474a81189fb9d3978bdde5 | https://github.com/inveniosoftware/invenio-webhooks/blob/f407cb2245464543ee474a81189fb9d3978bdde5/invenio_webhooks/models.py#L87-L112 | train |
inveniosoftware/invenio-webhooks | invenio_webhooks/models.py | Receiver.check_signature | def check_signature(self):
"""Check signature of signed request."""
if not self.signature:
return True
signature_value = request.headers.get(self.signature, None)
if signature_value:
validator = 'check_' + re.sub(r'[-]', '_', self.signature).lower()
check_signature = getattr(signatures, validator)
if check_signature(signature_value, request.data):
return True
return False | python | def check_signature(self):
"""Check signature of signed request."""
if not self.signature:
return True
signature_value = request.headers.get(self.signature, None)
if signature_value:
validator = 'check_' + re.sub(r'[-]', '_', self.signature).lower()
check_signature = getattr(signatures, validator)
if check_signature(signature_value, request.data):
return True
return False | [
"def",
"check_signature",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"signature",
":",
"return",
"True",
"signature_value",
"=",
"request",
".",
"headers",
".",
"get",
"(",
"self",
".",
"signature",
",",
"None",
")",
"if",
"signature_value",
":",
"validator",
"=",
"'check_'",
"+",
"re",
".",
"sub",
"(",
"r'[-]'",
",",
"'_'",
",",
"self",
".",
"signature",
")",
".",
"lower",
"(",
")",
"check_signature",
"=",
"getattr",
"(",
"signatures",
",",
"validator",
")",
"if",
"check_signature",
"(",
"signature_value",
",",
"request",
".",
"data",
")",
":",
"return",
"True",
"return",
"False"
] | Check signature of signed request. | [
"Check",
"signature",
"of",
"signed",
"request",
"."
] | f407cb2245464543ee474a81189fb9d3978bdde5 | https://github.com/inveniosoftware/invenio-webhooks/blob/f407cb2245464543ee474a81189fb9d3978bdde5/invenio_webhooks/models.py#L117-L127 | train |
inveniosoftware/invenio-webhooks | invenio_webhooks/models.py | Receiver.extract_payload | def extract_payload(self):
"""Extract payload from request."""
if not self.check_signature():
raise InvalidSignature('Invalid Signature')
if request.is_json:
# Request.get_json() could be first called with silent=True.
delete_cached_json_for(request)
return request.get_json(silent=False, cache=False)
elif request.content_type == 'application/x-www-form-urlencoded':
return dict(request.form)
raise InvalidPayload(request.content_type) | python | def extract_payload(self):
"""Extract payload from request."""
if not self.check_signature():
raise InvalidSignature('Invalid Signature')
if request.is_json:
# Request.get_json() could be first called with silent=True.
delete_cached_json_for(request)
return request.get_json(silent=False, cache=False)
elif request.content_type == 'application/x-www-form-urlencoded':
return dict(request.form)
raise InvalidPayload(request.content_type) | [
"def",
"extract_payload",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"check_signature",
"(",
")",
":",
"raise",
"InvalidSignature",
"(",
"'Invalid Signature'",
")",
"if",
"request",
".",
"is_json",
":",
"# Request.get_json() could be first called with silent=True.",
"delete_cached_json_for",
"(",
"request",
")",
"return",
"request",
".",
"get_json",
"(",
"silent",
"=",
"False",
",",
"cache",
"=",
"False",
")",
"elif",
"request",
".",
"content_type",
"==",
"'application/x-www-form-urlencoded'",
":",
"return",
"dict",
"(",
"request",
".",
"form",
")",
"raise",
"InvalidPayload",
"(",
"request",
".",
"content_type",
")"
] | Extract payload from request. | [
"Extract",
"payload",
"from",
"request",
"."
] | f407cb2245464543ee474a81189fb9d3978bdde5 | https://github.com/inveniosoftware/invenio-webhooks/blob/f407cb2245464543ee474a81189fb9d3978bdde5/invenio_webhooks/models.py#L129-L139 | train |
inveniosoftware/invenio-webhooks | invenio_webhooks/models.py | CeleryReceiver.delete | def delete(self, event):
"""Abort running task if it exists."""
super(CeleryReceiver, self).delete(event)
AsyncResult(event.id).revoke(terminate=True) | python | def delete(self, event):
"""Abort running task if it exists."""
super(CeleryReceiver, self).delete(event)
AsyncResult(event.id).revoke(terminate=True) | [
"def",
"delete",
"(",
"self",
",",
"event",
")",
":",
"super",
"(",
"CeleryReceiver",
",",
"self",
")",
".",
"delete",
"(",
"event",
")",
"AsyncResult",
"(",
"event",
".",
"id",
")",
".",
"revoke",
"(",
"terminate",
"=",
"True",
")"
] | Abort running task if it exists. | [
"Abort",
"running",
"task",
"if",
"it",
"exists",
"."
] | f407cb2245464543ee474a81189fb9d3978bdde5 | https://github.com/inveniosoftware/invenio-webhooks/blob/f407cb2245464543ee474a81189fb9d3978bdde5/invenio_webhooks/models.py#L191-L194 | train |
inveniosoftware/invenio-webhooks | invenio_webhooks/models.py | Event.validate_receiver | def validate_receiver(self, key, value):
"""Validate receiver identifier."""
if value not in current_webhooks.receivers:
raise ReceiverDoesNotExist(self.receiver_id)
return value | python | def validate_receiver(self, key, value):
"""Validate receiver identifier."""
if value not in current_webhooks.receivers:
raise ReceiverDoesNotExist(self.receiver_id)
return value | [
"def",
"validate_receiver",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"if",
"value",
"not",
"in",
"current_webhooks",
".",
"receivers",
":",
"raise",
"ReceiverDoesNotExist",
"(",
"self",
".",
"receiver_id",
")",
"return",
"value"
] | Validate receiver identifier. | [
"Validate",
"receiver",
"identifier",
"."
] | f407cb2245464543ee474a81189fb9d3978bdde5 | https://github.com/inveniosoftware/invenio-webhooks/blob/f407cb2245464543ee474a81189fb9d3978bdde5/invenio_webhooks/models.py#L251-L255 | train |
inveniosoftware/invenio-webhooks | invenio_webhooks/models.py | Event.create | def create(cls, receiver_id, user_id=None):
"""Create an event instance."""
event = cls(id=uuid.uuid4(), receiver_id=receiver_id, user_id=user_id)
event.payload = event.receiver.extract_payload()
return event | python | def create(cls, receiver_id, user_id=None):
"""Create an event instance."""
event = cls(id=uuid.uuid4(), receiver_id=receiver_id, user_id=user_id)
event.payload = event.receiver.extract_payload()
return event | [
"def",
"create",
"(",
"cls",
",",
"receiver_id",
",",
"user_id",
"=",
"None",
")",
":",
"event",
"=",
"cls",
"(",
"id",
"=",
"uuid",
".",
"uuid4",
"(",
")",
",",
"receiver_id",
"=",
"receiver_id",
",",
"user_id",
"=",
"user_id",
")",
"event",
".",
"payload",
"=",
"event",
".",
"receiver",
".",
"extract_payload",
"(",
")",
"return",
"event"
] | Create an event instance. | [
"Create",
"an",
"event",
"instance",
"."
] | f407cb2245464543ee474a81189fb9d3978bdde5 | https://github.com/inveniosoftware/invenio-webhooks/blob/f407cb2245464543ee474a81189fb9d3978bdde5/invenio_webhooks/models.py#L258-L262 | train |
inveniosoftware/invenio-webhooks | invenio_webhooks/models.py | Event.receiver | def receiver(self):
"""Return registered receiver."""
try:
return current_webhooks.receivers[self.receiver_id]
except KeyError:
raise ReceiverDoesNotExist(self.receiver_id) | python | def receiver(self):
"""Return registered receiver."""
try:
return current_webhooks.receivers[self.receiver_id]
except KeyError:
raise ReceiverDoesNotExist(self.receiver_id) | [
"def",
"receiver",
"(",
"self",
")",
":",
"try",
":",
"return",
"current_webhooks",
".",
"receivers",
"[",
"self",
".",
"receiver_id",
"]",
"except",
"KeyError",
":",
"raise",
"ReceiverDoesNotExist",
"(",
"self",
".",
"receiver_id",
")"
] | Return registered receiver. | [
"Return",
"registered",
"receiver",
"."
] | f407cb2245464543ee474a81189fb9d3978bdde5 | https://github.com/inveniosoftware/invenio-webhooks/blob/f407cb2245464543ee474a81189fb9d3978bdde5/invenio_webhooks/models.py#L265-L270 | train |
inveniosoftware/invenio-webhooks | invenio_webhooks/models.py | Event.receiver | def receiver(self, value):
"""Set receiver instance."""
assert isinstance(value, Receiver)
self.receiver_id = value.receiver_id | python | def receiver(self, value):
"""Set receiver instance."""
assert isinstance(value, Receiver)
self.receiver_id = value.receiver_id | [
"def",
"receiver",
"(",
"self",
",",
"value",
")",
":",
"assert",
"isinstance",
"(",
"value",
",",
"Receiver",
")",
"self",
".",
"receiver_id",
"=",
"value",
".",
"receiver_id"
] | Set receiver instance. | [
"Set",
"receiver",
"instance",
"."
] | f407cb2245464543ee474a81189fb9d3978bdde5 | https://github.com/inveniosoftware/invenio-webhooks/blob/f407cb2245464543ee474a81189fb9d3978bdde5/invenio_webhooks/models.py#L273-L276 | train |
inveniosoftware/invenio-webhooks | invenio_webhooks/models.py | Event.process | def process(self):
"""Process current event."""
try:
self.receiver(self)
# TODO RESTException
except Exception as e:
current_app.logger.exception('Could not process event.')
self.response_code = 500
self.response = dict(status=500, message=str(e))
return self | python | def process(self):
"""Process current event."""
try:
self.receiver(self)
# TODO RESTException
except Exception as e:
current_app.logger.exception('Could not process event.')
self.response_code = 500
self.response = dict(status=500, message=str(e))
return self | [
"def",
"process",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"receiver",
"(",
"self",
")",
"# TODO RESTException",
"except",
"Exception",
"as",
"e",
":",
"current_app",
".",
"logger",
".",
"exception",
"(",
"'Could not process event.'",
")",
"self",
".",
"response_code",
"=",
"500",
"self",
".",
"response",
"=",
"dict",
"(",
"status",
"=",
"500",
",",
"message",
"=",
"str",
"(",
"e",
")",
")",
"return",
"self"
] | Process current event. | [
"Process",
"current",
"event",
"."
] | f407cb2245464543ee474a81189fb9d3978bdde5 | https://github.com/inveniosoftware/invenio-webhooks/blob/f407cb2245464543ee474a81189fb9d3978bdde5/invenio_webhooks/models.py#L278-L287 | train |
GrahamDumpleton/autowrapt | src/bootstrap.py | register_bootstrap_functions | def register_bootstrap_functions():
'''Discover and register all post import hooks named in the
'AUTOWRAPT_BOOTSTRAP' environment variable. The value of the
environment variable must be a comma separated list.
'''
# This can be called twice if '.pth' file bootstrapping works and
# the 'autowrapt' wrapper script is still also used. We therefore
# protect ourselves just in case it is called a second time as we
# only want to force registration once.
global _registered
if _registered:
return
_registered = True
# It should be safe to import wrapt at this point as this code will
# be executed after all Python module search directories have been
# added to the module search path.
from wrapt import discover_post_import_hooks
for name in os.environ.get('AUTOWRAPT_BOOTSTRAP', '').split(','):
discover_post_import_hooks(name) | python | def register_bootstrap_functions():
'''Discover and register all post import hooks named in the
'AUTOWRAPT_BOOTSTRAP' environment variable. The value of the
environment variable must be a comma separated list.
'''
# This can be called twice if '.pth' file bootstrapping works and
# the 'autowrapt' wrapper script is still also used. We therefore
# protect ourselves just in case it is called a second time as we
# only want to force registration once.
global _registered
if _registered:
return
_registered = True
# It should be safe to import wrapt at this point as this code will
# be executed after all Python module search directories have been
# added to the module search path.
from wrapt import discover_post_import_hooks
for name in os.environ.get('AUTOWRAPT_BOOTSTRAP', '').split(','):
discover_post_import_hooks(name) | [
"def",
"register_bootstrap_functions",
"(",
")",
":",
"# This can be called twice if '.pth' file bootstrapping works and",
"# the 'autowrapt' wrapper script is still also used. We therefore",
"# protect ourselves just in case it is called a second time as we",
"# only want to force registration once.",
"global",
"_registered",
"if",
"_registered",
":",
"return",
"_registered",
"=",
"True",
"# It should be safe to import wrapt at this point as this code will",
"# be executed after all Python module search directories have been",
"# added to the module search path.",
"from",
"wrapt",
"import",
"discover_post_import_hooks",
"for",
"name",
"in",
"os",
".",
"environ",
".",
"get",
"(",
"'AUTOWRAPT_BOOTSTRAP'",
",",
"''",
")",
".",
"split",
"(",
"','",
")",
":",
"discover_post_import_hooks",
"(",
"name",
")"
] | Discover and register all post import hooks named in the
'AUTOWRAPT_BOOTSTRAP' environment variable. The value of the
environment variable must be a comma separated list. | [
"Discover",
"and",
"register",
"all",
"post",
"import",
"hooks",
"named",
"in",
"the",
"AUTOWRAPT_BOOTSTRAP",
"environment",
"variable",
".",
"The",
"value",
"of",
"the",
"environment",
"variable",
"must",
"be",
"a",
"comma",
"separated",
"list",
"."
] | d4770e4f511c19012055deaab68ef0ec8aa54ba4 | https://github.com/GrahamDumpleton/autowrapt/blob/d4770e4f511c19012055deaab68ef0ec8aa54ba4/src/bootstrap.py#L13-L39 | train |
GrahamDumpleton/autowrapt | src/bootstrap.py | bootstrap | def bootstrap():
'''Patches the 'site' module such that the bootstrap functions for
registering the post import hook callback functions are called as
the last thing done when initialising the Python interpreter. This
function would normally be called from the special '.pth' file.
'''
global _patched
if _patched:
return
_patched = True
# We want to do our real work as the very last thing in the 'site'
# module when it is being imported so that the module search path is
# initialised properly. What is the last thing executed depends on
# whether the 'usercustomize' module support is enabled. Support for
# the 'usercustomize' module will not be enabled in Python virtual
# enviromments. We therefore wrap the functions for the loading of
# both the 'sitecustomize' and 'usercustomize' modules but detect
# when 'usercustomize' support is disabled and in that case do what
# we need to after the 'sitecustomize' module is loaded.
#
# In wrapping these functions though, we can't actually use wrapt to
# do so. This is because depending on how wrapt was installed it may
# technically be dependent on '.pth' evaluation for Python to know
# where to import it from. The addition of the directory which
# contains wrapt may not yet have been done. We thus use a simple
# function wrapper instead.
site.execsitecustomize = _execsitecustomize_wrapper(site.execsitecustomize)
site.execusercustomize = _execusercustomize_wrapper(site.execusercustomize) | python | def bootstrap():
'''Patches the 'site' module such that the bootstrap functions for
registering the post import hook callback functions are called as
the last thing done when initialising the Python interpreter. This
function would normally be called from the special '.pth' file.
'''
global _patched
if _patched:
return
_patched = True
# We want to do our real work as the very last thing in the 'site'
# module when it is being imported so that the module search path is
# initialised properly. What is the last thing executed depends on
# whether the 'usercustomize' module support is enabled. Support for
# the 'usercustomize' module will not be enabled in Python virtual
# enviromments. We therefore wrap the functions for the loading of
# both the 'sitecustomize' and 'usercustomize' modules but detect
# when 'usercustomize' support is disabled and in that case do what
# we need to after the 'sitecustomize' module is loaded.
#
# In wrapping these functions though, we can't actually use wrapt to
# do so. This is because depending on how wrapt was installed it may
# technically be dependent on '.pth' evaluation for Python to know
# where to import it from. The addition of the directory which
# contains wrapt may not yet have been done. We thus use a simple
# function wrapper instead.
site.execsitecustomize = _execsitecustomize_wrapper(site.execsitecustomize)
site.execusercustomize = _execusercustomize_wrapper(site.execusercustomize) | [
"def",
"bootstrap",
"(",
")",
":",
"global",
"_patched",
"if",
"_patched",
":",
"return",
"_patched",
"=",
"True",
"# We want to do our real work as the very last thing in the 'site'",
"# module when it is being imported so that the module search path is",
"# initialised properly. What is the last thing executed depends on",
"# whether the 'usercustomize' module support is enabled. Support for",
"# the 'usercustomize' module will not be enabled in Python virtual",
"# enviromments. We therefore wrap the functions for the loading of",
"# both the 'sitecustomize' and 'usercustomize' modules but detect",
"# when 'usercustomize' support is disabled and in that case do what",
"# we need to after the 'sitecustomize' module is loaded.",
"#",
"# In wrapping these functions though, we can't actually use wrapt to",
"# do so. This is because depending on how wrapt was installed it may",
"# technically be dependent on '.pth' evaluation for Python to know",
"# where to import it from. The addition of the directory which",
"# contains wrapt may not yet have been done. We thus use a simple",
"# function wrapper instead.",
"site",
".",
"execsitecustomize",
"=",
"_execsitecustomize_wrapper",
"(",
"site",
".",
"execsitecustomize",
")",
"site",
".",
"execusercustomize",
"=",
"_execusercustomize_wrapper",
"(",
"site",
".",
"execusercustomize",
")"
] | Patches the 'site' module such that the bootstrap functions for
registering the post import hook callback functions are called as
the last thing done when initialising the Python interpreter. This
function would normally be called from the special '.pth' file. | [
"Patches",
"the",
"site",
"module",
"such",
"that",
"the",
"bootstrap",
"functions",
"for",
"registering",
"the",
"post",
"import",
"hook",
"callback",
"functions",
"are",
"called",
"as",
"the",
"last",
"thing",
"done",
"when",
"initialising",
"the",
"Python",
"interpreter",
".",
"This",
"function",
"would",
"normally",
"be",
"called",
"from",
"the",
"special",
".",
"pth",
"file",
"."
] | d4770e4f511c19012055deaab68ef0ec8aa54ba4 | https://github.com/GrahamDumpleton/autowrapt/blob/d4770e4f511c19012055deaab68ef0ec8aa54ba4/src/bootstrap.py#L67-L100 | train |
architv/harvey | harvey/get_tldr.py | get_rules | def get_rules(license):
"""Gets can, cannot and must rules from github license API"""
can = []
cannot = []
must = []
req = requests.get("{base_url}/licenses/{license}".format(
base_url=BASE_URL, license=license), headers=_HEADERS)
if req.status_code == requests.codes.ok:
data = req.json()
can = data["permitted"]
cannot = data["forbidden"]
must = data["required"]
return can, cannot, must | python | def get_rules(license):
"""Gets can, cannot and must rules from github license API"""
can = []
cannot = []
must = []
req = requests.get("{base_url}/licenses/{license}".format(
base_url=BASE_URL, license=license), headers=_HEADERS)
if req.status_code == requests.codes.ok:
data = req.json()
can = data["permitted"]
cannot = data["forbidden"]
must = data["required"]
return can, cannot, must | [
"def",
"get_rules",
"(",
"license",
")",
":",
"can",
"=",
"[",
"]",
"cannot",
"=",
"[",
"]",
"must",
"=",
"[",
"]",
"req",
"=",
"requests",
".",
"get",
"(",
"\"{base_url}/licenses/{license}\"",
".",
"format",
"(",
"base_url",
"=",
"BASE_URL",
",",
"license",
"=",
"license",
")",
",",
"headers",
"=",
"_HEADERS",
")",
"if",
"req",
".",
"status_code",
"==",
"requests",
".",
"codes",
".",
"ok",
":",
"data",
"=",
"req",
".",
"json",
"(",
")",
"can",
"=",
"data",
"[",
"\"permitted\"",
"]",
"cannot",
"=",
"data",
"[",
"\"forbidden\"",
"]",
"must",
"=",
"data",
"[",
"\"required\"",
"]",
"return",
"can",
",",
"cannot",
",",
"must"
] | Gets can, cannot and must rules from github license API | [
"Gets",
"can",
"cannot",
"and",
"must",
"rules",
"from",
"github",
"license",
"API"
] | 2b96d57b7a1e0dd706f1f00aba3d92a7ae702960 | https://github.com/architv/harvey/blob/2b96d57b7a1e0dd706f1f00aba3d92a7ae702960/harvey/get_tldr.py#L26-L41 | train |
architv/harvey | harvey/get_tldr.py | main | def main():
"""Gets all the license information and stores it in json format"""
all_summary = {}
for license in RESOURCES:
req = requests.get(RESOURCES[license])
if req.status_code == requests.codes.ok:
summary = get_summary(req.text)
can, cannot, must = get_rules(license)
all_summary[license] = {
"summary": summary,
"source": RESOURCES[license],
"can": can,
"cannot": cannot,
"must": must
}
with open('summary.json', 'w+') as f:
f.write(json.dumps(all_summary, indent=4)) | python | def main():
"""Gets all the license information and stores it in json format"""
all_summary = {}
for license in RESOURCES:
req = requests.get(RESOURCES[license])
if req.status_code == requests.codes.ok:
summary = get_summary(req.text)
can, cannot, must = get_rules(license)
all_summary[license] = {
"summary": summary,
"source": RESOURCES[license],
"can": can,
"cannot": cannot,
"must": must
}
with open('summary.json', 'w+') as f:
f.write(json.dumps(all_summary, indent=4)) | [
"def",
"main",
"(",
")",
":",
"all_summary",
"=",
"{",
"}",
"for",
"license",
"in",
"RESOURCES",
":",
"req",
"=",
"requests",
".",
"get",
"(",
"RESOURCES",
"[",
"license",
"]",
")",
"if",
"req",
".",
"status_code",
"==",
"requests",
".",
"codes",
".",
"ok",
":",
"summary",
"=",
"get_summary",
"(",
"req",
".",
"text",
")",
"can",
",",
"cannot",
",",
"must",
"=",
"get_rules",
"(",
"license",
")",
"all_summary",
"[",
"license",
"]",
"=",
"{",
"\"summary\"",
":",
"summary",
",",
"\"source\"",
":",
"RESOURCES",
"[",
"license",
"]",
",",
"\"can\"",
":",
"can",
",",
"\"cannot\"",
":",
"cannot",
",",
"\"must\"",
":",
"must",
"}",
"with",
"open",
"(",
"'summary.json'",
",",
"'w+'",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"json",
".",
"dumps",
"(",
"all_summary",
",",
"indent",
"=",
"4",
")",
")"
] | Gets all the license information and stores it in json format | [
"Gets",
"all",
"the",
"license",
"information",
"and",
"stores",
"it",
"in",
"json",
"format"
] | 2b96d57b7a1e0dd706f1f00aba3d92a7ae702960 | https://github.com/architv/harvey/blob/2b96d57b7a1e0dd706f1f00aba3d92a7ae702960/harvey/get_tldr.py#L44-L66 | train |
costastf/toonlib | _CI/bin/bump.py | get_arguments | def get_arguments():
"""
This get us the cli arguments.
Returns the args as parsed from the argsparser.
"""
# https://docs.python.org/3/library/argparse.html
parser = argparse.ArgumentParser(
description='Handles bumping of the artifact version')
parser.add_argument('--log-config',
'-l',
action='store',
dest='logger_config',
help='The location of the logging config json file',
default='')
parser.add_argument('--log-level',
'-L',
help='Provide the log level. Defaults to INFO.',
dest='log_level',
action='store',
default='INFO',
choices=['DEBUG',
'INFO',
'WARNING',
'ERROR',
'CRITICAL'])
parser.add_argument('--major',
help='Bump the major version',
dest='bump_major',
action='store_true',
default=False)
parser.add_argument('--minor',
help='Bump the minor version',
dest='bump_minor',
action='store_true',
default=False)
parser.add_argument('--patch',
help='Bump the patch version',
dest='bump_patch',
action='store_true',
default=False)
parser.add_argument('--version',
help='Set the version',
dest='version',
action='store',
default=False)
args = parser.parse_args()
return args | python | def get_arguments():
"""
This get us the cli arguments.
Returns the args as parsed from the argsparser.
"""
# https://docs.python.org/3/library/argparse.html
parser = argparse.ArgumentParser(
description='Handles bumping of the artifact version')
parser.add_argument('--log-config',
'-l',
action='store',
dest='logger_config',
help='The location of the logging config json file',
default='')
parser.add_argument('--log-level',
'-L',
help='Provide the log level. Defaults to INFO.',
dest='log_level',
action='store',
default='INFO',
choices=['DEBUG',
'INFO',
'WARNING',
'ERROR',
'CRITICAL'])
parser.add_argument('--major',
help='Bump the major version',
dest='bump_major',
action='store_true',
default=False)
parser.add_argument('--minor',
help='Bump the minor version',
dest='bump_minor',
action='store_true',
default=False)
parser.add_argument('--patch',
help='Bump the patch version',
dest='bump_patch',
action='store_true',
default=False)
parser.add_argument('--version',
help='Set the version',
dest='version',
action='store',
default=False)
args = parser.parse_args()
return args | [
"def",
"get_arguments",
"(",
")",
":",
"# https://docs.python.org/3/library/argparse.html",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"'Handles bumping of the artifact version'",
")",
"parser",
".",
"add_argument",
"(",
"'--log-config'",
",",
"'-l'",
",",
"action",
"=",
"'store'",
",",
"dest",
"=",
"'logger_config'",
",",
"help",
"=",
"'The location of the logging config json file'",
",",
"default",
"=",
"''",
")",
"parser",
".",
"add_argument",
"(",
"'--log-level'",
",",
"'-L'",
",",
"help",
"=",
"'Provide the log level. Defaults to INFO.'",
",",
"dest",
"=",
"'log_level'",
",",
"action",
"=",
"'store'",
",",
"default",
"=",
"'INFO'",
",",
"choices",
"=",
"[",
"'DEBUG'",
",",
"'INFO'",
",",
"'WARNING'",
",",
"'ERROR'",
",",
"'CRITICAL'",
"]",
")",
"parser",
".",
"add_argument",
"(",
"'--major'",
",",
"help",
"=",
"'Bump the major version'",
",",
"dest",
"=",
"'bump_major'",
",",
"action",
"=",
"'store_true'",
",",
"default",
"=",
"False",
")",
"parser",
".",
"add_argument",
"(",
"'--minor'",
",",
"help",
"=",
"'Bump the minor version'",
",",
"dest",
"=",
"'bump_minor'",
",",
"action",
"=",
"'store_true'",
",",
"default",
"=",
"False",
")",
"parser",
".",
"add_argument",
"(",
"'--patch'",
",",
"help",
"=",
"'Bump the patch version'",
",",
"dest",
"=",
"'bump_patch'",
",",
"action",
"=",
"'store_true'",
",",
"default",
"=",
"False",
")",
"parser",
".",
"add_argument",
"(",
"'--version'",
",",
"help",
"=",
"'Set the version'",
",",
"dest",
"=",
"'version'",
",",
"action",
"=",
"'store'",
",",
"default",
"=",
"False",
")",
"args",
"=",
"parser",
".",
"parse_args",
"(",
")",
"return",
"args"
] | This get us the cli arguments.
Returns the args as parsed from the argsparser. | [
"This",
"get",
"us",
"the",
"cli",
"arguments",
"."
] | 2fa95430240d1a1c2a85a8827aecfcb1ca41c18c | https://github.com/costastf/toonlib/blob/2fa95430240d1a1c2a85a8827aecfcb1ca41c18c/_CI/bin/bump.py#L21-L68 | train |
costastf/toonlib | _CI/bin/bump.py | setup_logging | def setup_logging(args):
"""
This sets up the logging.
Needs the args to get the log level supplied
:param args: The command line arguments
"""
handler = logging.StreamHandler()
handler.setLevel(args.log_level)
formatter = logging.Formatter(('%(asctime)s - '
'%(name)s - '
'%(levelname)s - '
'%(message)s'))
handler.setFormatter(formatter)
LOGGER.addHandler(handler) | python | def setup_logging(args):
"""
This sets up the logging.
Needs the args to get the log level supplied
:param args: The command line arguments
"""
handler = logging.StreamHandler()
handler.setLevel(args.log_level)
formatter = logging.Formatter(('%(asctime)s - '
'%(name)s - '
'%(levelname)s - '
'%(message)s'))
handler.setFormatter(formatter)
LOGGER.addHandler(handler) | [
"def",
"setup_logging",
"(",
"args",
")",
":",
"handler",
"=",
"logging",
".",
"StreamHandler",
"(",
")",
"handler",
".",
"setLevel",
"(",
"args",
".",
"log_level",
")",
"formatter",
"=",
"logging",
".",
"Formatter",
"(",
"(",
"'%(asctime)s - '",
"'%(name)s - '",
"'%(levelname)s - '",
"'%(message)s'",
")",
")",
"handler",
".",
"setFormatter",
"(",
"formatter",
")",
"LOGGER",
".",
"addHandler",
"(",
"handler",
")"
] | This sets up the logging.
Needs the args to get the log level supplied
:param args: The command line arguments | [
"This",
"sets",
"up",
"the",
"logging",
"."
] | 2fa95430240d1a1c2a85a8827aecfcb1ca41c18c | https://github.com/costastf/toonlib/blob/2fa95430240d1a1c2a85a8827aecfcb1ca41c18c/_CI/bin/bump.py#L71-L85 | train |
inveniosoftware/invenio-webhooks | invenio_webhooks/views.py | make_response | def make_response(event):
"""Make a response from webhook event."""
code, message = event.status
response = jsonify(**event.response)
response.headers['X-Hub-Event'] = event.receiver_id
response.headers['X-Hub-Delivery'] = event.id
if message:
response.headers['X-Hub-Info'] = message
add_link_header(response, {'self': url_for(
'.event_item', receiver_id=event.receiver_id, event_id=event.id,
_external=True
)})
return response, code | python | def make_response(event):
"""Make a response from webhook event."""
code, message = event.status
response = jsonify(**event.response)
response.headers['X-Hub-Event'] = event.receiver_id
response.headers['X-Hub-Delivery'] = event.id
if message:
response.headers['X-Hub-Info'] = message
add_link_header(response, {'self': url_for(
'.event_item', receiver_id=event.receiver_id, event_id=event.id,
_external=True
)})
return response, code | [
"def",
"make_response",
"(",
"event",
")",
":",
"code",
",",
"message",
"=",
"event",
".",
"status",
"response",
"=",
"jsonify",
"(",
"*",
"*",
"event",
".",
"response",
")",
"response",
".",
"headers",
"[",
"'X-Hub-Event'",
"]",
"=",
"event",
".",
"receiver_id",
"response",
".",
"headers",
"[",
"'X-Hub-Delivery'",
"]",
"=",
"event",
".",
"id",
"if",
"message",
":",
"response",
".",
"headers",
"[",
"'X-Hub-Info'",
"]",
"=",
"message",
"add_link_header",
"(",
"response",
",",
"{",
"'self'",
":",
"url_for",
"(",
"'.event_item'",
",",
"receiver_id",
"=",
"event",
".",
"receiver_id",
",",
"event_id",
"=",
"event",
".",
"id",
",",
"_external",
"=",
"True",
")",
"}",
")",
"return",
"response",
",",
"code"
] | Make a response from webhook event. | [
"Make",
"a",
"response",
"from",
"webhook",
"event",
"."
] | f407cb2245464543ee474a81189fb9d3978bdde5 | https://github.com/inveniosoftware/invenio-webhooks/blob/f407cb2245464543ee474a81189fb9d3978bdde5/invenio_webhooks/views.py#L69-L81 | train |
inveniosoftware/invenio-webhooks | invenio_webhooks/views.py | error_handler | def error_handler(f):
"""Return a json payload and appropriate status code on expection."""
@wraps(f)
def inner(*args, **kwargs):
try:
return f(*args, **kwargs)
except ReceiverDoesNotExist:
return jsonify(
status=404,
description='Receiver does not exists.'
), 404
except InvalidPayload as e:
return jsonify(
status=415,
description='Receiver does not support the'
' content-type "%s".' % e.args[0]
), 415
except WebhooksError:
return jsonify(
status=500,
description='Internal server error'
), 500
return inner | python | def error_handler(f):
"""Return a json payload and appropriate status code on expection."""
@wraps(f)
def inner(*args, **kwargs):
try:
return f(*args, **kwargs)
except ReceiverDoesNotExist:
return jsonify(
status=404,
description='Receiver does not exists.'
), 404
except InvalidPayload as e:
return jsonify(
status=415,
description='Receiver does not support the'
' content-type "%s".' % e.args[0]
), 415
except WebhooksError:
return jsonify(
status=500,
description='Internal server error'
), 500
return inner | [
"def",
"error_handler",
"(",
"f",
")",
":",
"@",
"wraps",
"(",
"f",
")",
"def",
"inner",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"return",
"f",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"except",
"ReceiverDoesNotExist",
":",
"return",
"jsonify",
"(",
"status",
"=",
"404",
",",
"description",
"=",
"'Receiver does not exists.'",
")",
",",
"404",
"except",
"InvalidPayload",
"as",
"e",
":",
"return",
"jsonify",
"(",
"status",
"=",
"415",
",",
"description",
"=",
"'Receiver does not support the'",
"' content-type \"%s\".'",
"%",
"e",
".",
"args",
"[",
"0",
"]",
")",
",",
"415",
"except",
"WebhooksError",
":",
"return",
"jsonify",
"(",
"status",
"=",
"500",
",",
"description",
"=",
"'Internal server error'",
")",
",",
"500",
"return",
"inner"
] | Return a json payload and appropriate status code on expection. | [
"Return",
"a",
"json",
"payload",
"and",
"appropriate",
"status",
"code",
"on",
"expection",
"."
] | f407cb2245464543ee474a81189fb9d3978bdde5 | https://github.com/inveniosoftware/invenio-webhooks/blob/f407cb2245464543ee474a81189fb9d3978bdde5/invenio_webhooks/views.py#L87-L109 | train |
inveniosoftware/invenio-webhooks | invenio_webhooks/views.py | ReceiverEventListResource.post | def post(self, receiver_id=None):
"""Handle POST request."""
try:
user_id = request.oauth.access_token.user_id
except AttributeError:
user_id = current_user.get_id()
event = Event.create(
receiver_id=receiver_id,
user_id=user_id
)
db.session.add(event)
db.session.commit()
# db.session.begin(subtransactions=True)
event.process()
db.session.commit()
return make_response(event) | python | def post(self, receiver_id=None):
"""Handle POST request."""
try:
user_id = request.oauth.access_token.user_id
except AttributeError:
user_id = current_user.get_id()
event = Event.create(
receiver_id=receiver_id,
user_id=user_id
)
db.session.add(event)
db.session.commit()
# db.session.begin(subtransactions=True)
event.process()
db.session.commit()
return make_response(event) | [
"def",
"post",
"(",
"self",
",",
"receiver_id",
"=",
"None",
")",
":",
"try",
":",
"user_id",
"=",
"request",
".",
"oauth",
".",
"access_token",
".",
"user_id",
"except",
"AttributeError",
":",
"user_id",
"=",
"current_user",
".",
"get_id",
"(",
")",
"event",
"=",
"Event",
".",
"create",
"(",
"receiver_id",
"=",
"receiver_id",
",",
"user_id",
"=",
"user_id",
")",
"db",
".",
"session",
".",
"add",
"(",
"event",
")",
"db",
".",
"session",
".",
"commit",
"(",
")",
"# db.session.begin(subtransactions=True)",
"event",
".",
"process",
"(",
")",
"db",
".",
"session",
".",
"commit",
"(",
")",
"return",
"make_response",
"(",
"event",
")"
] | Handle POST request. | [
"Handle",
"POST",
"request",
"."
] | f407cb2245464543ee474a81189fb9d3978bdde5 | https://github.com/inveniosoftware/invenio-webhooks/blob/f407cb2245464543ee474a81189fb9d3978bdde5/invenio_webhooks/views.py#L121-L138 | train |
inveniosoftware/invenio-webhooks | invenio_webhooks/views.py | ReceiverEventResource._get_event | def _get_event(receiver_id, event_id):
"""Find event and check access rights."""
event = Event.query.filter_by(
receiver_id=receiver_id, id=event_id
).first_or_404()
try:
user_id = request.oauth.access_token.user_id
except AttributeError:
user_id = current_user.get_id()
if event.user_id != int(user_id):
abort(401)
return event | python | def _get_event(receiver_id, event_id):
"""Find event and check access rights."""
event = Event.query.filter_by(
receiver_id=receiver_id, id=event_id
).first_or_404()
try:
user_id = request.oauth.access_token.user_id
except AttributeError:
user_id = current_user.get_id()
if event.user_id != int(user_id):
abort(401)
return event | [
"def",
"_get_event",
"(",
"receiver_id",
",",
"event_id",
")",
":",
"event",
"=",
"Event",
".",
"query",
".",
"filter_by",
"(",
"receiver_id",
"=",
"receiver_id",
",",
"id",
"=",
"event_id",
")",
".",
"first_or_404",
"(",
")",
"try",
":",
"user_id",
"=",
"request",
".",
"oauth",
".",
"access_token",
".",
"user_id",
"except",
"AttributeError",
":",
"user_id",
"=",
"current_user",
".",
"get_id",
"(",
")",
"if",
"event",
".",
"user_id",
"!=",
"int",
"(",
"user_id",
")",
":",
"abort",
"(",
"401",
")",
"return",
"event"
] | Find event and check access rights. | [
"Find",
"event",
"and",
"check",
"access",
"rights",
"."
] | f407cb2245464543ee474a81189fb9d3978bdde5 | https://github.com/inveniosoftware/invenio-webhooks/blob/f407cb2245464543ee474a81189fb9d3978bdde5/invenio_webhooks/views.py#L149-L163 | train |
inveniosoftware/invenio-webhooks | invenio_webhooks/views.py | ReceiverEventResource.get | def get(self, receiver_id=None, event_id=None):
"""Handle GET request."""
event = self._get_event(receiver_id, event_id)
return make_response(event) | python | def get(self, receiver_id=None, event_id=None):
"""Handle GET request."""
event = self._get_event(receiver_id, event_id)
return make_response(event) | [
"def",
"get",
"(",
"self",
",",
"receiver_id",
"=",
"None",
",",
"event_id",
"=",
"None",
")",
":",
"event",
"=",
"self",
".",
"_get_event",
"(",
"receiver_id",
",",
"event_id",
")",
"return",
"make_response",
"(",
"event",
")"
] | Handle GET request. | [
"Handle",
"GET",
"request",
"."
] | f407cb2245464543ee474a81189fb9d3978bdde5 | https://github.com/inveniosoftware/invenio-webhooks/blob/f407cb2245464543ee474a81189fb9d3978bdde5/invenio_webhooks/views.py#L168-L171 | train |
inveniosoftware/invenio-webhooks | invenio_webhooks/views.py | ReceiverEventResource.delete | def delete(self, receiver_id=None, event_id=None):
"""Handle DELETE request."""
event = self._get_event(receiver_id, event_id)
event.delete()
db.session.commit()
return make_response(event) | python | def delete(self, receiver_id=None, event_id=None):
"""Handle DELETE request."""
event = self._get_event(receiver_id, event_id)
event.delete()
db.session.commit()
return make_response(event) | [
"def",
"delete",
"(",
"self",
",",
"receiver_id",
"=",
"None",
",",
"event_id",
"=",
"None",
")",
":",
"event",
"=",
"self",
".",
"_get_event",
"(",
"receiver_id",
",",
"event_id",
")",
"event",
".",
"delete",
"(",
")",
"db",
".",
"session",
".",
"commit",
"(",
")",
"return",
"make_response",
"(",
"event",
")"
] | Handle DELETE request. | [
"Handle",
"DELETE",
"request",
"."
] | f407cb2245464543ee474a81189fb9d3978bdde5 | https://github.com/inveniosoftware/invenio-webhooks/blob/f407cb2245464543ee474a81189fb9d3978bdde5/invenio_webhooks/views.py#L176-L181 | train |
architv/harvey | harvey/harvey.py | _stripslashes | def _stripslashes(s):
'''Removes trailing and leading backslashes from string'''
r = re.sub(r"\\(n|r)", "\n", s)
r = re.sub(r"\\", "", r)
return r | python | def _stripslashes(s):
'''Removes trailing and leading backslashes from string'''
r = re.sub(r"\\(n|r)", "\n", s)
r = re.sub(r"\\", "", r)
return r | [
"def",
"_stripslashes",
"(",
"s",
")",
":",
"r",
"=",
"re",
".",
"sub",
"(",
"r\"\\\\(n|r)\"",
",",
"\"\\n\"",
",",
"s",
")",
"r",
"=",
"re",
".",
"sub",
"(",
"r\"\\\\\"",
",",
"\"\"",
",",
"r",
")",
"return",
"r"
] | Removes trailing and leading backslashes from string | [
"Removes",
"trailing",
"and",
"leading",
"backslashes",
"from",
"string"
] | 2b96d57b7a1e0dd706f1f00aba3d92a7ae702960 | https://github.com/architv/harvey/blob/2b96d57b7a1e0dd706f1f00aba3d92a7ae702960/harvey/harvey.py#L46-L50 | train |
architv/harvey | harvey/harvey.py | _get_config_name | def _get_config_name():
'''Get git config user name'''
p = subprocess.Popen('git config --get user.name', shell=True,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
output = p.stdout.readlines()
return _stripslashes(output[0]) | python | def _get_config_name():
'''Get git config user name'''
p = subprocess.Popen('git config --get user.name', shell=True,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
output = p.stdout.readlines()
return _stripslashes(output[0]) | [
"def",
"_get_config_name",
"(",
")",
":",
"p",
"=",
"subprocess",
".",
"Popen",
"(",
"'git config --get user.name'",
",",
"shell",
"=",
"True",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"stderr",
"=",
"subprocess",
".",
"STDOUT",
")",
"output",
"=",
"p",
".",
"stdout",
".",
"readlines",
"(",
")",
"return",
"_stripslashes",
"(",
"output",
"[",
"0",
"]",
")"
] | Get git config user name | [
"Get",
"git",
"config",
"user",
"name"
] | 2b96d57b7a1e0dd706f1f00aba3d92a7ae702960 | https://github.com/architv/harvey/blob/2b96d57b7a1e0dd706f1f00aba3d92a7ae702960/harvey/harvey.py#L53-L58 | train |
architv/harvey | harvey/harvey.py | _get_licences | def _get_licences():
""" Lists all the licenses on command line """
licenses = _LICENSES
for license in licenses:
print("{license_name} [{license_code}]".format(
license_name=licenses[license], license_code=license)) | python | def _get_licences():
""" Lists all the licenses on command line """
licenses = _LICENSES
for license in licenses:
print("{license_name} [{license_code}]".format(
license_name=licenses[license], license_code=license)) | [
"def",
"_get_licences",
"(",
")",
":",
"licenses",
"=",
"_LICENSES",
"for",
"license",
"in",
"licenses",
":",
"print",
"(",
"\"{license_name} [{license_code}]\"",
".",
"format",
"(",
"license_name",
"=",
"licenses",
"[",
"license",
"]",
",",
"license_code",
"=",
"license",
")",
")"
] | Lists all the licenses on command line | [
"Lists",
"all",
"the",
"licenses",
"on",
"command",
"line"
] | 2b96d57b7a1e0dd706f1f00aba3d92a7ae702960 | https://github.com/architv/harvey/blob/2b96d57b7a1e0dd706f1f00aba3d92a7ae702960/harvey/harvey.py#L61-L67 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.