repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1 value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
sk-/git-lint | gitlint/utils.py | save_output_in_cache | def save_output_in_cache(name, filename, output):
"""Saves output in the cache location.
Args:
name: string: name of the linter.
filename: string: path of the filename for which we are saving the output.
output: string: full output (not yet filetered) of the lint command.
"""
cache_filename = _get_cache_filename(name, filename)
with _open_for_write(cache_filename) as f:
f.write(output) | python | def save_output_in_cache(name, filename, output):
"""Saves output in the cache location.
Args:
name: string: name of the linter.
filename: string: path of the filename for which we are saving the output.
output: string: full output (not yet filetered) of the lint command.
"""
cache_filename = _get_cache_filename(name, filename)
with _open_for_write(cache_filename) as f:
f.write(output) | [
"def",
"save_output_in_cache",
"(",
"name",
",",
"filename",
",",
"output",
")",
":",
"cache_filename",
"=",
"_get_cache_filename",
"(",
"name",
",",
"filename",
")",
"with",
"_open_for_write",
"(",
"cache_filename",
")",
"as",
"f",
":",
"f",
".",
"write",
"... | Saves output in the cache location.
Args:
name: string: name of the linter.
filename: string: path of the filename for which we are saving the output.
output: string: full output (not yet filetered) of the lint command. | [
"Saves",
"output",
"in",
"the",
"cache",
"location",
"."
] | 4f19ec88bfa1b6670ff37ccbfc53c6b67251b027 | https://github.com/sk-/git-lint/blob/4f19ec88bfa1b6670ff37ccbfc53c6b67251b027/gitlint/utils.py#L106-L116 | train | 34,700 |
pylast/pylast | src/pylast/__init__.py | md5 | def md5(text):
"""Returns the md5 hash of a string."""
h = hashlib.md5()
h.update(_unicode(text).encode("utf-8"))
return h.hexdigest() | python | def md5(text):
"""Returns the md5 hash of a string."""
h = hashlib.md5()
h.update(_unicode(text).encode("utf-8"))
return h.hexdigest() | [
"def",
"md5",
"(",
"text",
")",
":",
"h",
"=",
"hashlib",
".",
"md5",
"(",
")",
"h",
".",
"update",
"(",
"_unicode",
"(",
"text",
")",
".",
"encode",
"(",
"\"utf-8\"",
")",
")",
"return",
"h",
".",
"hexdigest",
"(",
")"
] | Returns the md5 hash of a string. | [
"Returns",
"the",
"md5",
"hash",
"of",
"a",
"string",
"."
] | a52f66d316797fc819b5f1d186d77f18ba97b4ff | https://github.com/pylast/pylast/blob/a52f66d316797fc819b5f1d186d77f18ba97b4ff/src/pylast/__init__.py#L2766-L2772 | train | 34,701 |
pylast/pylast | src/pylast/__init__.py | cleanup_nodes | def cleanup_nodes(doc):
"""
Remove text nodes containing only whitespace
"""
for node in doc.documentElement.childNodes:
if node.nodeType == Node.TEXT_NODE and node.nodeValue.isspace():
doc.documentElement.removeChild(node)
return doc | python | def cleanup_nodes(doc):
"""
Remove text nodes containing only whitespace
"""
for node in doc.documentElement.childNodes:
if node.nodeType == Node.TEXT_NODE and node.nodeValue.isspace():
doc.documentElement.removeChild(node)
return doc | [
"def",
"cleanup_nodes",
"(",
"doc",
")",
":",
"for",
"node",
"in",
"doc",
".",
"documentElement",
".",
"childNodes",
":",
"if",
"node",
".",
"nodeType",
"==",
"Node",
".",
"TEXT_NODE",
"and",
"node",
".",
"nodeValue",
".",
"isspace",
"(",
")",
":",
"do... | Remove text nodes containing only whitespace | [
"Remove",
"text",
"nodes",
"containing",
"only",
"whitespace"
] | a52f66d316797fc819b5f1d186d77f18ba97b4ff | https://github.com/pylast/pylast/blob/a52f66d316797fc819b5f1d186d77f18ba97b4ff/src/pylast/__init__.py#L2790-L2797 | train | 34,702 |
pylast/pylast | src/pylast/__init__.py | _collect_nodes | def _collect_nodes(limit, sender, method_name, cacheable, params=None):
"""
Returns a sequence of dom.Node objects about as close to limit as possible
"""
if not params:
params = sender._get_params()
nodes = []
page = 1
end_of_pages = False
while not end_of_pages and (not limit or (limit and len(nodes) < limit)):
params["page"] = str(page)
tries = 1
while True:
try:
doc = sender._request(method_name, cacheable, params)
break # success
except Exception as e:
if tries >= 3:
raise e
# Wait and try again
time.sleep(1)
tries += 1
doc = cleanup_nodes(doc)
# break if there are no child nodes
if not doc.documentElement.childNodes:
break
main = doc.documentElement.childNodes[0]
if main.hasAttribute("totalPages"):
total_pages = _number(main.getAttribute("totalPages"))
elif main.hasAttribute("totalpages"):
total_pages = _number(main.getAttribute("totalpages"))
else:
raise Exception("No total pages attribute")
for node in main.childNodes:
if not node.nodeType == xml.dom.Node.TEXT_NODE and (
not limit or (len(nodes) < limit)
):
nodes.append(node)
if page >= total_pages:
end_of_pages = True
page += 1
return nodes | python | def _collect_nodes(limit, sender, method_name, cacheable, params=None):
"""
Returns a sequence of dom.Node objects about as close to limit as possible
"""
if not params:
params = sender._get_params()
nodes = []
page = 1
end_of_pages = False
while not end_of_pages and (not limit or (limit and len(nodes) < limit)):
params["page"] = str(page)
tries = 1
while True:
try:
doc = sender._request(method_name, cacheable, params)
break # success
except Exception as e:
if tries >= 3:
raise e
# Wait and try again
time.sleep(1)
tries += 1
doc = cleanup_nodes(doc)
# break if there are no child nodes
if not doc.documentElement.childNodes:
break
main = doc.documentElement.childNodes[0]
if main.hasAttribute("totalPages"):
total_pages = _number(main.getAttribute("totalPages"))
elif main.hasAttribute("totalpages"):
total_pages = _number(main.getAttribute("totalpages"))
else:
raise Exception("No total pages attribute")
for node in main.childNodes:
if not node.nodeType == xml.dom.Node.TEXT_NODE and (
not limit or (len(nodes) < limit)
):
nodes.append(node)
if page >= total_pages:
end_of_pages = True
page += 1
return nodes | [
"def",
"_collect_nodes",
"(",
"limit",
",",
"sender",
",",
"method_name",
",",
"cacheable",
",",
"params",
"=",
"None",
")",
":",
"if",
"not",
"params",
":",
"params",
"=",
"sender",
".",
"_get_params",
"(",
")",
"nodes",
"=",
"[",
"]",
"page",
"=",
... | Returns a sequence of dom.Node objects about as close to limit as possible | [
"Returns",
"a",
"sequence",
"of",
"dom",
".",
"Node",
"objects",
"about",
"as",
"close",
"to",
"limit",
"as",
"possible"
] | a52f66d316797fc819b5f1d186d77f18ba97b4ff | https://github.com/pylast/pylast/blob/a52f66d316797fc819b5f1d186d77f18ba97b4ff/src/pylast/__init__.py#L2800-L2852 | train | 34,703 |
pylast/pylast | src/pylast/__init__.py | _extract | def _extract(node, name, index=0):
"""Extracts a value from the xml string"""
nodes = node.getElementsByTagName(name)
if len(nodes):
if nodes[index].firstChild:
return _unescape_htmlentity(nodes[index].firstChild.data.strip())
else:
return None | python | def _extract(node, name, index=0):
"""Extracts a value from the xml string"""
nodes = node.getElementsByTagName(name)
if len(nodes):
if nodes[index].firstChild:
return _unescape_htmlentity(nodes[index].firstChild.data.strip())
else:
return None | [
"def",
"_extract",
"(",
"node",
",",
"name",
",",
"index",
"=",
"0",
")",
":",
"nodes",
"=",
"node",
".",
"getElementsByTagName",
"(",
"name",
")",
"if",
"len",
"(",
"nodes",
")",
":",
"if",
"nodes",
"[",
"index",
"]",
".",
"firstChild",
":",
"retu... | Extracts a value from the xml string | [
"Extracts",
"a",
"value",
"from",
"the",
"xml",
"string"
] | a52f66d316797fc819b5f1d186d77f18ba97b4ff | https://github.com/pylast/pylast/blob/a52f66d316797fc819b5f1d186d77f18ba97b4ff/src/pylast/__init__.py#L2855-L2864 | train | 34,704 |
pylast/pylast | src/pylast/__init__.py | _extract_all | def _extract_all(node, name, limit_count=None):
"""Extracts all the values from the xml string. returning a list."""
seq = []
for i in range(0, len(node.getElementsByTagName(name))):
if len(seq) == limit_count:
break
seq.append(_extract(node, name, i))
return seq | python | def _extract_all(node, name, limit_count=None):
"""Extracts all the values from the xml string. returning a list."""
seq = []
for i in range(0, len(node.getElementsByTagName(name))):
if len(seq) == limit_count:
break
seq.append(_extract(node, name, i))
return seq | [
"def",
"_extract_all",
"(",
"node",
",",
"name",
",",
"limit_count",
"=",
"None",
")",
":",
"seq",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"node",
".",
"getElementsByTagName",
"(",
"name",
")",
")",
")",
":",
"if",
"l... | Extracts all the values from the xml string. returning a list. | [
"Extracts",
"all",
"the",
"values",
"from",
"the",
"xml",
"string",
".",
"returning",
"a",
"list",
"."
] | a52f66d316797fc819b5f1d186d77f18ba97b4ff | https://github.com/pylast/pylast/blob/a52f66d316797fc819b5f1d186d77f18ba97b4ff/src/pylast/__init__.py#L2867-L2878 | train | 34,705 |
pylast/pylast | src/pylast/__init__.py | _Network._delay_call | def _delay_call(self):
"""
Makes sure that web service calls are at least 0.2 seconds apart.
"""
now = time.time()
time_since_last = now - self.last_call_time
if time_since_last < DELAY_TIME:
time.sleep(DELAY_TIME - time_since_last)
self.last_call_time = now | python | def _delay_call(self):
"""
Makes sure that web service calls are at least 0.2 seconds apart.
"""
now = time.time()
time_since_last = now - self.last_call_time
if time_since_last < DELAY_TIME:
time.sleep(DELAY_TIME - time_since_last)
self.last_call_time = now | [
"def",
"_delay_call",
"(",
"self",
")",
":",
"now",
"=",
"time",
".",
"time",
"(",
")",
"time_since_last",
"=",
"now",
"-",
"self",
".",
"last_call_time",
"if",
"time_since_last",
"<",
"DELAY_TIME",
":",
"time",
".",
"sleep",
"(",
"DELAY_TIME",
"-",
"tim... | Makes sure that web service calls are at least 0.2 seconds apart. | [
"Makes",
"sure",
"that",
"web",
"service",
"calls",
"are",
"at",
"least",
"0",
".",
"2",
"seconds",
"apart",
"."
] | a52f66d316797fc819b5f1d186d77f18ba97b4ff | https://github.com/pylast/pylast/blob/a52f66d316797fc819b5f1d186d77f18ba97b4ff/src/pylast/__init__.py#L309-L320 | train | 34,706 |
pylast/pylast | src/pylast/__init__.py | _Network.get_top_artists | def get_top_artists(self, limit=None, cacheable=True):
"""Returns the most played artists as a sequence of TopItem objects."""
params = {}
if limit:
params["limit"] = limit
doc = _Request(self, "chart.getTopArtists", params).execute(cacheable)
return _extract_top_artists(doc, self) | python | def get_top_artists(self, limit=None, cacheable=True):
"""Returns the most played artists as a sequence of TopItem objects."""
params = {}
if limit:
params["limit"] = limit
doc = _Request(self, "chart.getTopArtists", params).execute(cacheable)
return _extract_top_artists(doc, self) | [
"def",
"get_top_artists",
"(",
"self",
",",
"limit",
"=",
"None",
",",
"cacheable",
"=",
"True",
")",
":",
"params",
"=",
"{",
"}",
"if",
"limit",
":",
"params",
"[",
"\"limit\"",
"]",
"=",
"limit",
"doc",
"=",
"_Request",
"(",
"self",
",",
"\"chart.... | Returns the most played artists as a sequence of TopItem objects. | [
"Returns",
"the",
"most",
"played",
"artists",
"as",
"a",
"sequence",
"of",
"TopItem",
"objects",
"."
] | a52f66d316797fc819b5f1d186d77f18ba97b4ff | https://github.com/pylast/pylast/blob/a52f66d316797fc819b5f1d186d77f18ba97b4ff/src/pylast/__init__.py#L322-L331 | train | 34,707 |
pylast/pylast | src/pylast/__init__.py | _Network.get_top_tracks | def get_top_tracks(self, limit=None, cacheable=True):
"""Returns the most played tracks as a sequence of TopItem objects."""
params = {}
if limit:
params["limit"] = limit
doc = _Request(self, "chart.getTopTracks", params).execute(cacheable)
seq = []
for node in doc.getElementsByTagName("track"):
title = _extract(node, "name")
artist = _extract(node, "name", 1)
track = Track(artist, title, self)
weight = _number(_extract(node, "playcount"))
seq.append(TopItem(track, weight))
return seq | python | def get_top_tracks(self, limit=None, cacheable=True):
"""Returns the most played tracks as a sequence of TopItem objects."""
params = {}
if limit:
params["limit"] = limit
doc = _Request(self, "chart.getTopTracks", params).execute(cacheable)
seq = []
for node in doc.getElementsByTagName("track"):
title = _extract(node, "name")
artist = _extract(node, "name", 1)
track = Track(artist, title, self)
weight = _number(_extract(node, "playcount"))
seq.append(TopItem(track, weight))
return seq | [
"def",
"get_top_tracks",
"(",
"self",
",",
"limit",
"=",
"None",
",",
"cacheable",
"=",
"True",
")",
":",
"params",
"=",
"{",
"}",
"if",
"limit",
":",
"params",
"[",
"\"limit\"",
"]",
"=",
"limit",
"doc",
"=",
"_Request",
"(",
"self",
",",
"\"chart.g... | Returns the most played tracks as a sequence of TopItem objects. | [
"Returns",
"the",
"most",
"played",
"tracks",
"as",
"a",
"sequence",
"of",
"TopItem",
"objects",
"."
] | a52f66d316797fc819b5f1d186d77f18ba97b4ff | https://github.com/pylast/pylast/blob/a52f66d316797fc819b5f1d186d77f18ba97b4ff/src/pylast/__init__.py#L333-L350 | train | 34,708 |
pylast/pylast | src/pylast/__init__.py | _Network.get_top_tags | def get_top_tags(self, limit=None, cacheable=True):
"""Returns the most used tags as a sequence of TopItem objects."""
# Last.fm has no "limit" parameter for tag.getTopTags
# so we need to get all (250) and then limit locally
doc = _Request(self, "tag.getTopTags").execute(cacheable)
seq = []
for node in doc.getElementsByTagName("tag"):
if limit and len(seq) >= limit:
break
tag = Tag(_extract(node, "name"), self)
weight = _number(_extract(node, "count"))
seq.append(TopItem(tag, weight))
return seq | python | def get_top_tags(self, limit=None, cacheable=True):
"""Returns the most used tags as a sequence of TopItem objects."""
# Last.fm has no "limit" parameter for tag.getTopTags
# so we need to get all (250) and then limit locally
doc = _Request(self, "tag.getTopTags").execute(cacheable)
seq = []
for node in doc.getElementsByTagName("tag"):
if limit and len(seq) >= limit:
break
tag = Tag(_extract(node, "name"), self)
weight = _number(_extract(node, "count"))
seq.append(TopItem(tag, weight))
return seq | [
"def",
"get_top_tags",
"(",
"self",
",",
"limit",
"=",
"None",
",",
"cacheable",
"=",
"True",
")",
":",
"# Last.fm has no \"limit\" parameter for tag.getTopTags",
"# so we need to get all (250) and then limit locally",
"doc",
"=",
"_Request",
"(",
"self",
",",
"\"tag.getT... | Returns the most used tags as a sequence of TopItem objects. | [
"Returns",
"the",
"most",
"used",
"tags",
"as",
"a",
"sequence",
"of",
"TopItem",
"objects",
"."
] | a52f66d316797fc819b5f1d186d77f18ba97b4ff | https://github.com/pylast/pylast/blob/a52f66d316797fc819b5f1d186d77f18ba97b4ff/src/pylast/__init__.py#L352-L367 | train | 34,709 |
pylast/pylast | src/pylast/__init__.py | _Network.enable_proxy | def enable_proxy(self, host, port):
"""Enable a default web proxy"""
self.proxy = [host, _number(port)]
self.proxy_enabled = True | python | def enable_proxy(self, host, port):
"""Enable a default web proxy"""
self.proxy = [host, _number(port)]
self.proxy_enabled = True | [
"def",
"enable_proxy",
"(",
"self",
",",
"host",
",",
"port",
")",
":",
"self",
".",
"proxy",
"=",
"[",
"host",
",",
"_number",
"(",
"port",
")",
"]",
"self",
".",
"proxy_enabled",
"=",
"True"
] | Enable a default web proxy | [
"Enable",
"a",
"default",
"web",
"proxy"
] | a52f66d316797fc819b5f1d186d77f18ba97b4ff | https://github.com/pylast/pylast/blob/a52f66d316797fc819b5f1d186d77f18ba97b4ff/src/pylast/__init__.py#L417-L421 | train | 34,710 |
pylast/pylast | src/pylast/__init__.py | _Network.enable_caching | def enable_caching(self, file_path=None):
"""Enables caching request-wide for all cacheable calls.
* file_path: A file path for the backend storage file. If
None set, a temp file would probably be created, according the backend.
"""
if not file_path:
file_path = tempfile.mktemp(prefix="pylast_tmp_")
self.cache_backend = _ShelfCacheBackend(file_path) | python | def enable_caching(self, file_path=None):
"""Enables caching request-wide for all cacheable calls.
* file_path: A file path for the backend storage file. If
None set, a temp file would probably be created, according the backend.
"""
if not file_path:
file_path = tempfile.mktemp(prefix="pylast_tmp_")
self.cache_backend = _ShelfCacheBackend(file_path) | [
"def",
"enable_caching",
"(",
"self",
",",
"file_path",
"=",
"None",
")",
":",
"if",
"not",
"file_path",
":",
"file_path",
"=",
"tempfile",
".",
"mktemp",
"(",
"prefix",
"=",
"\"pylast_tmp_\"",
")",
"self",
".",
"cache_backend",
"=",
"_ShelfCacheBackend",
"(... | Enables caching request-wide for all cacheable calls.
* file_path: A file path for the backend storage file. If
None set, a temp file would probably be created, according the backend. | [
"Enables",
"caching",
"request",
"-",
"wide",
"for",
"all",
"cacheable",
"calls",
"."
] | a52f66d316797fc819b5f1d186d77f18ba97b4ff | https://github.com/pylast/pylast/blob/a52f66d316797fc819b5f1d186d77f18ba97b4ff/src/pylast/__init__.py#L450-L460 | train | 34,711 |
pylast/pylast | src/pylast/__init__.py | _Network.get_track_by_mbid | def get_track_by_mbid(self, mbid):
"""Looks up a track by its MusicBrainz ID"""
params = {"mbid": mbid}
doc = _Request(self, "track.getInfo", params).execute(True)
return Track(_extract(doc, "name", 1), _extract(doc, "name"), self) | python | def get_track_by_mbid(self, mbid):
"""Looks up a track by its MusicBrainz ID"""
params = {"mbid": mbid}
doc = _Request(self, "track.getInfo", params).execute(True)
return Track(_extract(doc, "name", 1), _extract(doc, "name"), self) | [
"def",
"get_track_by_mbid",
"(",
"self",
",",
"mbid",
")",
":",
"params",
"=",
"{",
"\"mbid\"",
":",
"mbid",
"}",
"doc",
"=",
"_Request",
"(",
"self",
",",
"\"track.getInfo\"",
",",
"params",
")",
".",
"execute",
"(",
"True",
")",
"return",
"Track",
"(... | Looks up a track by its MusicBrainz ID | [
"Looks",
"up",
"a",
"track",
"by",
"its",
"MusicBrainz",
"ID"
] | a52f66d316797fc819b5f1d186d77f18ba97b4ff | https://github.com/pylast/pylast/blob/a52f66d316797fc819b5f1d186d77f18ba97b4ff/src/pylast/__init__.py#L496-L503 | train | 34,712 |
pylast/pylast | src/pylast/__init__.py | _Network.get_artist_by_mbid | def get_artist_by_mbid(self, mbid):
"""Looks up an artist by its MusicBrainz ID"""
params = {"mbid": mbid}
doc = _Request(self, "artist.getInfo", params).execute(True)
return Artist(_extract(doc, "name"), self) | python | def get_artist_by_mbid(self, mbid):
"""Looks up an artist by its MusicBrainz ID"""
params = {"mbid": mbid}
doc = _Request(self, "artist.getInfo", params).execute(True)
return Artist(_extract(doc, "name"), self) | [
"def",
"get_artist_by_mbid",
"(",
"self",
",",
"mbid",
")",
":",
"params",
"=",
"{",
"\"mbid\"",
":",
"mbid",
"}",
"doc",
"=",
"_Request",
"(",
"self",
",",
"\"artist.getInfo\"",
",",
"params",
")",
".",
"execute",
"(",
"True",
")",
"return",
"Artist",
... | Looks up an artist by its MusicBrainz ID | [
"Looks",
"up",
"an",
"artist",
"by",
"its",
"MusicBrainz",
"ID"
] | a52f66d316797fc819b5f1d186d77f18ba97b4ff | https://github.com/pylast/pylast/blob/a52f66d316797fc819b5f1d186d77f18ba97b4ff/src/pylast/__init__.py#L505-L512 | train | 34,713 |
pylast/pylast | src/pylast/__init__.py | _Network.get_album_by_mbid | def get_album_by_mbid(self, mbid):
"""Looks up an album by its MusicBrainz ID"""
params = {"mbid": mbid}
doc = _Request(self, "album.getInfo", params).execute(True)
return Album(_extract(doc, "artist"), _extract(doc, "name"), self) | python | def get_album_by_mbid(self, mbid):
"""Looks up an album by its MusicBrainz ID"""
params = {"mbid": mbid}
doc = _Request(self, "album.getInfo", params).execute(True)
return Album(_extract(doc, "artist"), _extract(doc, "name"), self) | [
"def",
"get_album_by_mbid",
"(",
"self",
",",
"mbid",
")",
":",
"params",
"=",
"{",
"\"mbid\"",
":",
"mbid",
"}",
"doc",
"=",
"_Request",
"(",
"self",
",",
"\"album.getInfo\"",
",",
"params",
")",
".",
"execute",
"(",
"True",
")",
"return",
"Album",
"(... | Looks up an album by its MusicBrainz ID | [
"Looks",
"up",
"an",
"album",
"by",
"its",
"MusicBrainz",
"ID"
] | a52f66d316797fc819b5f1d186d77f18ba97b4ff | https://github.com/pylast/pylast/blob/a52f66d316797fc819b5f1d186d77f18ba97b4ff/src/pylast/__init__.py#L514-L521 | train | 34,714 |
pylast/pylast | src/pylast/__init__.py | _Network.update_now_playing | def update_now_playing(
self,
artist,
title,
album=None,
album_artist=None,
duration=None,
track_number=None,
mbid=None,
context=None,
):
"""
Used to notify Last.fm that a user has started listening to a track.
Parameters:
artist (Required) : The artist name
title (Required) : The track title
album (Optional) : The album name.
album_artist (Optional) : The album artist - if this differs
from the track artist.
duration (Optional) : The length of the track in seconds.
track_number (Optional) : The track number of the track on the
album.
mbid (Optional) : The MusicBrainz Track ID.
context (Optional) : Sub-client version
(not public, only enabled for certain API keys)
"""
params = {"track": title, "artist": artist}
if album:
params["album"] = album
if album_artist:
params["albumArtist"] = album_artist
if context:
params["context"] = context
if track_number:
params["trackNumber"] = track_number
if mbid:
params["mbid"] = mbid
if duration:
params["duration"] = duration
_Request(self, "track.updateNowPlaying", params).execute() | python | def update_now_playing(
self,
artist,
title,
album=None,
album_artist=None,
duration=None,
track_number=None,
mbid=None,
context=None,
):
"""
Used to notify Last.fm that a user has started listening to a track.
Parameters:
artist (Required) : The artist name
title (Required) : The track title
album (Optional) : The album name.
album_artist (Optional) : The album artist - if this differs
from the track artist.
duration (Optional) : The length of the track in seconds.
track_number (Optional) : The track number of the track on the
album.
mbid (Optional) : The MusicBrainz Track ID.
context (Optional) : Sub-client version
(not public, only enabled for certain API keys)
"""
params = {"track": title, "artist": artist}
if album:
params["album"] = album
if album_artist:
params["albumArtist"] = album_artist
if context:
params["context"] = context
if track_number:
params["trackNumber"] = track_number
if mbid:
params["mbid"] = mbid
if duration:
params["duration"] = duration
_Request(self, "track.updateNowPlaying", params).execute() | [
"def",
"update_now_playing",
"(",
"self",
",",
"artist",
",",
"title",
",",
"album",
"=",
"None",
",",
"album_artist",
"=",
"None",
",",
"duration",
"=",
"None",
",",
"track_number",
"=",
"None",
",",
"mbid",
"=",
"None",
",",
"context",
"=",
"None",
"... | Used to notify Last.fm that a user has started listening to a track.
Parameters:
artist (Required) : The artist name
title (Required) : The track title
album (Optional) : The album name.
album_artist (Optional) : The album artist - if this differs
from the track artist.
duration (Optional) : The length of the track in seconds.
track_number (Optional) : The track number of the track on the
album.
mbid (Optional) : The MusicBrainz Track ID.
context (Optional) : Sub-client version
(not public, only enabled for certain API keys) | [
"Used",
"to",
"notify",
"Last",
".",
"fm",
"that",
"a",
"user",
"has",
"started",
"listening",
"to",
"a",
"track",
"."
] | a52f66d316797fc819b5f1d186d77f18ba97b4ff | https://github.com/pylast/pylast/blob/a52f66d316797fc819b5f1d186d77f18ba97b4ff/src/pylast/__init__.py#L523-L566 | train | 34,715 |
pylast/pylast | src/pylast/__init__.py | _Network.scrobble | def scrobble(
self,
artist,
title,
timestamp,
album=None,
album_artist=None,
track_number=None,
duration=None,
stream_id=None,
context=None,
mbid=None,
):
"""Used to add a track-play to a user's profile.
Parameters:
artist (Required) : The artist name.
title (Required) : The track name.
timestamp (Required) : The time the track started playing, in UNIX
timestamp format (integer number of seconds since 00:00:00,
January 1st 1970 UTC). This must be in the UTC time zone.
album (Optional) : The album name.
album_artist (Optional) : The album artist - if this differs from
the track artist.
context (Optional) : Sub-client version (not public, only enabled
for certain API keys)
stream_id (Optional) : The stream id for this track received from
the radio.getPlaylist service.
track_number (Optional) : The track number of the track on the
album.
mbid (Optional) : The MusicBrainz Track ID.
duration (Optional) : The length of the track in seconds.
"""
return self.scrobble_many(
(
{
"artist": artist,
"title": title,
"timestamp": timestamp,
"album": album,
"album_artist": album_artist,
"track_number": track_number,
"duration": duration,
"stream_id": stream_id,
"context": context,
"mbid": mbid,
},
)
) | python | def scrobble(
self,
artist,
title,
timestamp,
album=None,
album_artist=None,
track_number=None,
duration=None,
stream_id=None,
context=None,
mbid=None,
):
"""Used to add a track-play to a user's profile.
Parameters:
artist (Required) : The artist name.
title (Required) : The track name.
timestamp (Required) : The time the track started playing, in UNIX
timestamp format (integer number of seconds since 00:00:00,
January 1st 1970 UTC). This must be in the UTC time zone.
album (Optional) : The album name.
album_artist (Optional) : The album artist - if this differs from
the track artist.
context (Optional) : Sub-client version (not public, only enabled
for certain API keys)
stream_id (Optional) : The stream id for this track received from
the radio.getPlaylist service.
track_number (Optional) : The track number of the track on the
album.
mbid (Optional) : The MusicBrainz Track ID.
duration (Optional) : The length of the track in seconds.
"""
return self.scrobble_many(
(
{
"artist": artist,
"title": title,
"timestamp": timestamp,
"album": album,
"album_artist": album_artist,
"track_number": track_number,
"duration": duration,
"stream_id": stream_id,
"context": context,
"mbid": mbid,
},
)
) | [
"def",
"scrobble",
"(",
"self",
",",
"artist",
",",
"title",
",",
"timestamp",
",",
"album",
"=",
"None",
",",
"album_artist",
"=",
"None",
",",
"track_number",
"=",
"None",
",",
"duration",
"=",
"None",
",",
"stream_id",
"=",
"None",
",",
"context",
"... | Used to add a track-play to a user's profile.
Parameters:
artist (Required) : The artist name.
title (Required) : The track name.
timestamp (Required) : The time the track started playing, in UNIX
timestamp format (integer number of seconds since 00:00:00,
January 1st 1970 UTC). This must be in the UTC time zone.
album (Optional) : The album name.
album_artist (Optional) : The album artist - if this differs from
the track artist.
context (Optional) : Sub-client version (not public, only enabled
for certain API keys)
stream_id (Optional) : The stream id for this track received from
the radio.getPlaylist service.
track_number (Optional) : The track number of the track on the
album.
mbid (Optional) : The MusicBrainz Track ID.
duration (Optional) : The length of the track in seconds. | [
"Used",
"to",
"add",
"a",
"track",
"-",
"play",
"to",
"a",
"user",
"s",
"profile",
"."
] | a52f66d316797fc819b5f1d186d77f18ba97b4ff | https://github.com/pylast/pylast/blob/a52f66d316797fc819b5f1d186d77f18ba97b4ff/src/pylast/__init__.py#L568-L618 | train | 34,716 |
pylast/pylast | src/pylast/__init__.py | _Request._get_signature | def _get_signature(self):
"""
Returns a 32-character hexadecimal md5 hash of the signature string.
"""
keys = list(self.params.keys())
keys.sort()
string = ""
for name in keys:
string += name
string += self.params[name]
string += self.api_secret
return md5(string) | python | def _get_signature(self):
"""
Returns a 32-character hexadecimal md5 hash of the signature string.
"""
keys = list(self.params.keys())
keys.sort()
string = ""
for name in keys:
string += name
string += self.params[name]
string += self.api_secret
return md5(string) | [
"def",
"_get_signature",
"(",
"self",
")",
":",
"keys",
"=",
"list",
"(",
"self",
".",
"params",
".",
"keys",
"(",
")",
")",
"keys",
".",
"sort",
"(",
")",
"string",
"=",
"\"\"",
"for",
"name",
"in",
"keys",
":",
"string",
"+=",
"name",
"string",
... | Returns a 32-character hexadecimal md5 hash of the signature string. | [
"Returns",
"a",
"32",
"-",
"character",
"hexadecimal",
"md5",
"hash",
"of",
"the",
"signature",
"string",
"."
] | a52f66d316797fc819b5f1d186d77f18ba97b4ff | https://github.com/pylast/pylast/blob/a52f66d316797fc819b5f1d186d77f18ba97b4ff/src/pylast/__init__.py#L872-L889 | train | 34,717 |
pylast/pylast | src/pylast/__init__.py | _Request._get_cache_key | def _get_cache_key(self):
"""
The cache key is a string of concatenated sorted names and values.
"""
keys = list(self.params.keys())
keys.sort()
cache_key = str()
for key in keys:
if key != "api_sig" and key != "api_key" and key != "sk":
cache_key += key + self.params[key]
return hashlib.sha1(cache_key.encode("utf-8")).hexdigest() | python | def _get_cache_key(self):
"""
The cache key is a string of concatenated sorted names and values.
"""
keys = list(self.params.keys())
keys.sort()
cache_key = str()
for key in keys:
if key != "api_sig" and key != "api_key" and key != "sk":
cache_key += key + self.params[key]
return hashlib.sha1(cache_key.encode("utf-8")).hexdigest() | [
"def",
"_get_cache_key",
"(",
"self",
")",
":",
"keys",
"=",
"list",
"(",
"self",
".",
"params",
".",
"keys",
"(",
")",
")",
"keys",
".",
"sort",
"(",
")",
"cache_key",
"=",
"str",
"(",
")",
"for",
"key",
"in",
"keys",
":",
"if",
"key",
"!=",
"... | The cache key is a string of concatenated sorted names and values. | [
"The",
"cache",
"key",
"is",
"a",
"string",
"of",
"concatenated",
"sorted",
"names",
"and",
"values",
"."
] | a52f66d316797fc819b5f1d186d77f18ba97b4ff | https://github.com/pylast/pylast/blob/a52f66d316797fc819b5f1d186d77f18ba97b4ff/src/pylast/__init__.py#L891-L905 | train | 34,718 |
pylast/pylast | src/pylast/__init__.py | _Request._get_cached_response | def _get_cached_response(self):
"""Returns a file object of the cached response."""
if not self._is_cached():
response = self._download_response()
self.cache.set_xml(self._get_cache_key(), response)
return self.cache.get_xml(self._get_cache_key()) | python | def _get_cached_response(self):
"""Returns a file object of the cached response."""
if not self._is_cached():
response = self._download_response()
self.cache.set_xml(self._get_cache_key(), response)
return self.cache.get_xml(self._get_cache_key()) | [
"def",
"_get_cached_response",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_is_cached",
"(",
")",
":",
"response",
"=",
"self",
".",
"_download_response",
"(",
")",
"self",
".",
"cache",
".",
"set_xml",
"(",
"self",
".",
"_get_cache_key",
"(",
")",... | Returns a file object of the cached response. | [
"Returns",
"a",
"file",
"object",
"of",
"the",
"cached",
"response",
"."
] | a52f66d316797fc819b5f1d186d77f18ba97b4ff | https://github.com/pylast/pylast/blob/a52f66d316797fc819b5f1d186d77f18ba97b4ff/src/pylast/__init__.py#L907-L914 | train | 34,719 |
pylast/pylast | src/pylast/__init__.py | _Request._download_response | def _download_response(self):
"""Returns a response body string from the server."""
if self.network.limit_rate:
self.network._delay_call()
data = []
for name in self.params.keys():
data.append("=".join((name, url_quote_plus(_string(self.params[name])))))
data = "&".join(data)
headers = {
"Content-type": "application/x-www-form-urlencoded",
"Accept-Charset": "utf-8",
"User-Agent": "pylast" + "/" + __version__,
}
(host_name, host_subdir) = self.network.ws_server
if self.network.is_proxy_enabled():
conn = HTTPSConnection(
context=SSL_CONTEXT,
host=self.network._get_proxy()[0],
port=self.network._get_proxy()[1],
)
try:
conn.request(
method="POST",
url="https://" + host_name + host_subdir,
body=data,
headers=headers,
)
except Exception as e:
raise NetworkError(self.network, e)
else:
conn = HTTPSConnection(context=SSL_CONTEXT, host=host_name)
try:
conn.request(method="POST", url=host_subdir, body=data, headers=headers)
except Exception as e:
raise NetworkError(self.network, e)
try:
response_text = _unicode(conn.getresponse().read())
except Exception as e:
raise MalformedResponseError(self.network, e)
try:
self._check_response_for_errors(response_text)
finally:
conn.close()
return response_text | python | def _download_response(self):
"""Returns a response body string from the server."""
if self.network.limit_rate:
self.network._delay_call()
data = []
for name in self.params.keys():
data.append("=".join((name, url_quote_plus(_string(self.params[name])))))
data = "&".join(data)
headers = {
"Content-type": "application/x-www-form-urlencoded",
"Accept-Charset": "utf-8",
"User-Agent": "pylast" + "/" + __version__,
}
(host_name, host_subdir) = self.network.ws_server
if self.network.is_proxy_enabled():
conn = HTTPSConnection(
context=SSL_CONTEXT,
host=self.network._get_proxy()[0],
port=self.network._get_proxy()[1],
)
try:
conn.request(
method="POST",
url="https://" + host_name + host_subdir,
body=data,
headers=headers,
)
except Exception as e:
raise NetworkError(self.network, e)
else:
conn = HTTPSConnection(context=SSL_CONTEXT, host=host_name)
try:
conn.request(method="POST", url=host_subdir, body=data, headers=headers)
except Exception as e:
raise NetworkError(self.network, e)
try:
response_text = _unicode(conn.getresponse().read())
except Exception as e:
raise MalformedResponseError(self.network, e)
try:
self._check_response_for_errors(response_text)
finally:
conn.close()
return response_text | [
"def",
"_download_response",
"(",
"self",
")",
":",
"if",
"self",
".",
"network",
".",
"limit_rate",
":",
"self",
".",
"network",
".",
"_delay_call",
"(",
")",
"data",
"=",
"[",
"]",
"for",
"name",
"in",
"self",
".",
"params",
".",
"keys",
"(",
")",
... | Returns a response body string from the server. | [
"Returns",
"a",
"response",
"body",
"string",
"from",
"the",
"server",
"."
] | a52f66d316797fc819b5f1d186d77f18ba97b4ff | https://github.com/pylast/pylast/blob/a52f66d316797fc819b5f1d186d77f18ba97b4ff/src/pylast/__init__.py#L921-L974 | train | 34,720 |
pylast/pylast | src/pylast/__init__.py | _Request.execute | def execute(self, cacheable=False):
"""Returns the XML DOM response of the POST Request from the server"""
if self.network.is_caching_enabled() and cacheable:
response = self._get_cached_response()
else:
response = self._download_response()
return minidom.parseString(_string(response).replace("opensearch:", "")) | python | def execute(self, cacheable=False):
"""Returns the XML DOM response of the POST Request from the server"""
if self.network.is_caching_enabled() and cacheable:
response = self._get_cached_response()
else:
response = self._download_response()
return minidom.parseString(_string(response).replace("opensearch:", "")) | [
"def",
"execute",
"(",
"self",
",",
"cacheable",
"=",
"False",
")",
":",
"if",
"self",
".",
"network",
".",
"is_caching_enabled",
"(",
")",
"and",
"cacheable",
":",
"response",
"=",
"self",
".",
"_get_cached_response",
"(",
")",
"else",
":",
"response",
... | Returns the XML DOM response of the POST Request from the server | [
"Returns",
"the",
"XML",
"DOM",
"response",
"of",
"the",
"POST",
"Request",
"from",
"the",
"server"
] | a52f66d316797fc819b5f1d186d77f18ba97b4ff | https://github.com/pylast/pylast/blob/a52f66d316797fc819b5f1d186d77f18ba97b4ff/src/pylast/__init__.py#L976-L984 | train | 34,721 |
pylast/pylast | src/pylast/__init__.py | _Request._check_response_for_errors | def _check_response_for_errors(self, response):
"""Checks the response for errors and raises one if any exists."""
try:
doc = minidom.parseString(_string(response).replace("opensearch:", ""))
except Exception as e:
raise MalformedResponseError(self.network, e)
e = doc.getElementsByTagName("lfm")[0]
# logger.debug(doc.toprettyxml())
if e.getAttribute("status") != "ok":
e = doc.getElementsByTagName("error")[0]
status = e.getAttribute("code")
details = e.firstChild.data.strip()
raise WSError(self.network, status, details) | python | def _check_response_for_errors(self, response):
"""Checks the response for errors and raises one if any exists."""
try:
doc = minidom.parseString(_string(response).replace("opensearch:", ""))
except Exception as e:
raise MalformedResponseError(self.network, e)
e = doc.getElementsByTagName("lfm")[0]
# logger.debug(doc.toprettyxml())
if e.getAttribute("status") != "ok":
e = doc.getElementsByTagName("error")[0]
status = e.getAttribute("code")
details = e.firstChild.data.strip()
raise WSError(self.network, status, details) | [
"def",
"_check_response_for_errors",
"(",
"self",
",",
"response",
")",
":",
"try",
":",
"doc",
"=",
"minidom",
".",
"parseString",
"(",
"_string",
"(",
"response",
")",
".",
"replace",
"(",
"\"opensearch:\"",
",",
"\"\"",
")",
")",
"except",
"Exception",
... | Checks the response for errors and raises one if any exists. | [
"Checks",
"the",
"response",
"for",
"errors",
"and",
"raises",
"one",
"if",
"any",
"exists",
"."
] | a52f66d316797fc819b5f1d186d77f18ba97b4ff | https://github.com/pylast/pylast/blob/a52f66d316797fc819b5f1d186d77f18ba97b4ff/src/pylast/__init__.py#L986-L1001 | train | 34,722 |
pylast/pylast | src/pylast/__init__.py | SessionKeyGenerator._get_web_auth_token | def _get_web_auth_token(self):
"""
Retrieves a token from the network for web authentication.
The token then has to be authorized from getAuthURL before creating
session.
"""
request = _Request(self.network, "auth.getToken")
# default action is that a request is signed only when
# a session key is provided.
request.sign_it()
doc = request.execute()
e = doc.getElementsByTagName("token")[0]
return e.firstChild.data | python | def _get_web_auth_token(self):
"""
Retrieves a token from the network for web authentication.
The token then has to be authorized from getAuthURL before creating
session.
"""
request = _Request(self.network, "auth.getToken")
# default action is that a request is signed only when
# a session key is provided.
request.sign_it()
doc = request.execute()
e = doc.getElementsByTagName("token")[0]
return e.firstChild.data | [
"def",
"_get_web_auth_token",
"(",
"self",
")",
":",
"request",
"=",
"_Request",
"(",
"self",
".",
"network",
",",
"\"auth.getToken\"",
")",
"# default action is that a request is signed only when",
"# a session key is provided.",
"request",
".",
"sign_it",
"(",
")",
"d... | Retrieves a token from the network for web authentication.
The token then has to be authorized from getAuthURL before creating
session. | [
"Retrieves",
"a",
"token",
"from",
"the",
"network",
"for",
"web",
"authentication",
".",
"The",
"token",
"then",
"has",
"to",
"be",
"authorized",
"from",
"getAuthURL",
"before",
"creating",
"session",
"."
] | a52f66d316797fc819b5f1d186d77f18ba97b4ff | https://github.com/pylast/pylast/blob/a52f66d316797fc819b5f1d186d77f18ba97b4ff/src/pylast/__init__.py#L1032-L1048 | train | 34,723 |
pylast/pylast | src/pylast/__init__.py | SessionKeyGenerator.get_web_auth_session_key | def get_web_auth_session_key(self, url, token=""):
"""
Retrieves the session key of a web authorization process by its URL.
"""
session_key, _username = self.get_web_auth_session_key_username(url, token)
return session_key | python | def get_web_auth_session_key(self, url, token=""):
"""
Retrieves the session key of a web authorization process by its URL.
"""
session_key, _username = self.get_web_auth_session_key_username(url, token)
return session_key | [
"def",
"get_web_auth_session_key",
"(",
"self",
",",
"url",
",",
"token",
"=",
"\"\"",
")",
":",
"session_key",
",",
"_username",
"=",
"self",
".",
"get_web_auth_session_key_username",
"(",
"url",
",",
"token",
")",
"return",
"session_key"
] | Retrieves the session key of a web authorization process by its URL. | [
"Retrieves",
"the",
"session",
"key",
"of",
"a",
"web",
"authorization",
"process",
"by",
"its",
"URL",
"."
] | a52f66d316797fc819b5f1d186d77f18ba97b4ff | https://github.com/pylast/pylast/blob/a52f66d316797fc819b5f1d186d77f18ba97b4ff/src/pylast/__init__.py#L1089-L1094 | train | 34,724 |
pylast/pylast | src/pylast/__init__.py | SessionKeyGenerator.get_session_key | def get_session_key(self, username, password_hash):
"""
Retrieve a session key with a username and a md5 hash of the user's
password.
"""
params = {"username": username, "authToken": md5(username + password_hash)}
request = _Request(self.network, "auth.getMobileSession", params)
# default action is that a request is signed only when
# a session key is provided.
request.sign_it()
doc = request.execute()
return _extract(doc, "key") | python | def get_session_key(self, username, password_hash):
"""
Retrieve a session key with a username and a md5 hash of the user's
password.
"""
params = {"username": username, "authToken": md5(username + password_hash)}
request = _Request(self.network, "auth.getMobileSession", params)
# default action is that a request is signed only when
# a session key is provided.
request.sign_it()
doc = request.execute()
return _extract(doc, "key") | [
"def",
"get_session_key",
"(",
"self",
",",
"username",
",",
"password_hash",
")",
":",
"params",
"=",
"{",
"\"username\"",
":",
"username",
",",
"\"authToken\"",
":",
"md5",
"(",
"username",
"+",
"password_hash",
")",
"}",
"request",
"=",
"_Request",
"(",
... | Retrieve a session key with a username and a md5 hash of the user's
password. | [
"Retrieve",
"a",
"session",
"key",
"with",
"a",
"username",
"and",
"a",
"md5",
"hash",
"of",
"the",
"user",
"s",
"password",
"."
] | a52f66d316797fc819b5f1d186d77f18ba97b4ff | https://github.com/pylast/pylast/blob/a52f66d316797fc819b5f1d186d77f18ba97b4ff/src/pylast/__init__.py#L1096-L1111 | train | 34,725 |
pylast/pylast | src/pylast/__init__.py | _BaseObject._get_things | def _get_things(self, method, thing, thing_type, params=None, cacheable=True):
"""Returns a list of the most played thing_types by this thing."""
limit = params.get("limit", 1)
seq = []
for node in _collect_nodes(
limit, self, self.ws_prefix + "." + method, cacheable, params
):
title = _extract(node, "name")
artist = _extract(node, "name", 1)
playcount = _number(_extract(node, "playcount"))
seq.append(TopItem(thing_type(artist, title, self.network), playcount))
return seq | python | def _get_things(self, method, thing, thing_type, params=None, cacheable=True):
"""Returns a list of the most played thing_types by this thing."""
limit = params.get("limit", 1)
seq = []
for node in _collect_nodes(
limit, self, self.ws_prefix + "." + method, cacheable, params
):
title = _extract(node, "name")
artist = _extract(node, "name", 1)
playcount = _number(_extract(node, "playcount"))
seq.append(TopItem(thing_type(artist, title, self.network), playcount))
return seq | [
"def",
"_get_things",
"(",
"self",
",",
"method",
",",
"thing",
",",
"thing_type",
",",
"params",
"=",
"None",
",",
"cacheable",
"=",
"True",
")",
":",
"limit",
"=",
"params",
".",
"get",
"(",
"\"limit\"",
",",
"1",
")",
"seq",
"=",
"[",
"]",
"for"... | Returns a list of the most played thing_types by this thing. | [
"Returns",
"a",
"list",
"of",
"the",
"most",
"played",
"thing_types",
"by",
"this",
"thing",
"."
] | a52f66d316797fc819b5f1d186d77f18ba97b4ff | https://github.com/pylast/pylast/blob/a52f66d316797fc819b5f1d186d77f18ba97b4ff/src/pylast/__init__.py#L1170-L1184 | train | 34,726 |
pylast/pylast | src/pylast/__init__.py | _Chartable.get_weekly_chart_dates | def get_weekly_chart_dates(self):
"""Returns a list of From and To tuples for the available charts."""
doc = self._request(self.ws_prefix + ".getWeeklyChartList", True)
seq = []
for node in doc.getElementsByTagName("chart"):
seq.append((node.getAttribute("from"), node.getAttribute("to")))
return seq | python | def get_weekly_chart_dates(self):
"""Returns a list of From and To tuples for the available charts."""
doc = self._request(self.ws_prefix + ".getWeeklyChartList", True)
seq = []
for node in doc.getElementsByTagName("chart"):
seq.append((node.getAttribute("from"), node.getAttribute("to")))
return seq | [
"def",
"get_weekly_chart_dates",
"(",
"self",
")",
":",
"doc",
"=",
"self",
".",
"_request",
"(",
"self",
".",
"ws_prefix",
"+",
"\".getWeeklyChartList\"",
",",
"True",
")",
"seq",
"=",
"[",
"]",
"for",
"node",
"in",
"doc",
".",
"getElementsByTagName",
"("... | Returns a list of From and To tuples for the available charts. | [
"Returns",
"a",
"list",
"of",
"From",
"and",
"To",
"tuples",
"for",
"the",
"available",
"charts",
"."
] | a52f66d316797fc819b5f1d186d77f18ba97b4ff | https://github.com/pylast/pylast/blob/a52f66d316797fc819b5f1d186d77f18ba97b4ff/src/pylast/__init__.py#L1231-L1240 | train | 34,727 |
pylast/pylast | src/pylast/__init__.py | _Chartable.get_weekly_charts | def get_weekly_charts(self, chart_kind, from_date=None, to_date=None):
"""
Returns the weekly charts for the week starting from the
from_date value to the to_date value.
chart_kind should be one of "album", "artist" or "track"
"""
method = ".getWeekly" + chart_kind.title() + "Chart"
chart_type = eval(chart_kind.title()) # string to type
params = self._get_params()
if from_date and to_date:
params["from"] = from_date
params["to"] = to_date
doc = self._request(self.ws_prefix + method, True, params)
seq = []
for node in doc.getElementsByTagName(chart_kind.lower()):
if chart_kind == "artist":
item = chart_type(_extract(node, "name"), self.network)
else:
item = chart_type(
_extract(node, "artist"), _extract(node, "name"), self.network
)
weight = _number(_extract(node, "playcount"))
seq.append(TopItem(item, weight))
return seq | python | def get_weekly_charts(self, chart_kind, from_date=None, to_date=None):
"""
Returns the weekly charts for the week starting from the
from_date value to the to_date value.
chart_kind should be one of "album", "artist" or "track"
"""
method = ".getWeekly" + chart_kind.title() + "Chart"
chart_type = eval(chart_kind.title()) # string to type
params = self._get_params()
if from_date and to_date:
params["from"] = from_date
params["to"] = to_date
doc = self._request(self.ws_prefix + method, True, params)
seq = []
for node in doc.getElementsByTagName(chart_kind.lower()):
if chart_kind == "artist":
item = chart_type(_extract(node, "name"), self.network)
else:
item = chart_type(
_extract(node, "artist"), _extract(node, "name"), self.network
)
weight = _number(_extract(node, "playcount"))
seq.append(TopItem(item, weight))
return seq | [
"def",
"get_weekly_charts",
"(",
"self",
",",
"chart_kind",
",",
"from_date",
"=",
"None",
",",
"to_date",
"=",
"None",
")",
":",
"method",
"=",
"\".getWeekly\"",
"+",
"chart_kind",
".",
"title",
"(",
")",
"+",
"\"Chart\"",
"chart_type",
"=",
"eval",
"(",
... | Returns the weekly charts for the week starting from the
from_date value to the to_date value.
chart_kind should be one of "album", "artist" or "track" | [
"Returns",
"the",
"weekly",
"charts",
"for",
"the",
"week",
"starting",
"from",
"the",
"from_date",
"value",
"to",
"the",
"to_date",
"value",
".",
"chart_kind",
"should",
"be",
"one",
"of",
"album",
"artist",
"or",
"track"
] | a52f66d316797fc819b5f1d186d77f18ba97b4ff | https://github.com/pylast/pylast/blob/a52f66d316797fc819b5f1d186d77f18ba97b4ff/src/pylast/__init__.py#L1266-L1293 | train | 34,728 |
pylast/pylast | src/pylast/__init__.py | _Taggable.remove_tag | def remove_tag(self, tag):
"""Remove a user's tag from this object."""
if isinstance(tag, Tag):
tag = tag.get_name()
params = self._get_params()
params["tag"] = tag
self._request(self.ws_prefix + ".removeTag", False, params) | python | def remove_tag(self, tag):
"""Remove a user's tag from this object."""
if isinstance(tag, Tag):
tag = tag.get_name()
params = self._get_params()
params["tag"] = tag
self._request(self.ws_prefix + ".removeTag", False, params) | [
"def",
"remove_tag",
"(",
"self",
",",
"tag",
")",
":",
"if",
"isinstance",
"(",
"tag",
",",
"Tag",
")",
":",
"tag",
"=",
"tag",
".",
"get_name",
"(",
")",
"params",
"=",
"self",
".",
"_get_params",
"(",
")",
"params",
"[",
"\"tag\"",
"]",
"=",
"... | Remove a user's tag from this object. | [
"Remove",
"a",
"user",
"s",
"tag",
"from",
"this",
"object",
"."
] | a52f66d316797fc819b5f1d186d77f18ba97b4ff | https://github.com/pylast/pylast/blob/a52f66d316797fc819b5f1d186d77f18ba97b4ff/src/pylast/__init__.py#L1323-L1332 | train | 34,729 |
pylast/pylast | src/pylast/__init__.py | _Taggable.get_tags | def get_tags(self):
"""Returns a list of the tags set by the user to this object."""
# Uncacheable because it can be dynamically changed by the user.
params = self._get_params()
doc = self._request(self.ws_prefix + ".getTags", False, params)
tag_names = _extract_all(doc, "name")
tags = []
for tag in tag_names:
tags.append(Tag(tag, self.network))
return tags | python | def get_tags(self):
"""Returns a list of the tags set by the user to this object."""
# Uncacheable because it can be dynamically changed by the user.
params = self._get_params()
doc = self._request(self.ws_prefix + ".getTags", False, params)
tag_names = _extract_all(doc, "name")
tags = []
for tag in tag_names:
tags.append(Tag(tag, self.network))
return tags | [
"def",
"get_tags",
"(",
"self",
")",
":",
"# Uncacheable because it can be dynamically changed by the user.",
"params",
"=",
"self",
".",
"_get_params",
"(",
")",
"doc",
"=",
"self",
".",
"_request",
"(",
"self",
".",
"ws_prefix",
"+",
"\".getTags\"",
",",
"False"... | Returns a list of the tags set by the user to this object. | [
"Returns",
"a",
"list",
"of",
"the",
"tags",
"set",
"by",
"the",
"user",
"to",
"this",
"object",
"."
] | a52f66d316797fc819b5f1d186d77f18ba97b4ff | https://github.com/pylast/pylast/blob/a52f66d316797fc819b5f1d186d77f18ba97b4ff/src/pylast/__init__.py#L1334-L1346 | train | 34,730 |
pylast/pylast | src/pylast/__init__.py | _Taggable.get_top_tags | def get_top_tags(self, limit=None):
"""Returns a list of the most frequently used Tags on this object."""
doc = self._request(self.ws_prefix + ".getTopTags", True)
elements = doc.getElementsByTagName("tag")
seq = []
for element in elements:
tag_name = _extract(element, "name")
tagcount = _extract(element, "count")
seq.append(TopItem(Tag(tag_name, self.network), tagcount))
if limit:
seq = seq[:limit]
return seq | python | def get_top_tags(self, limit=None):
"""Returns a list of the most frequently used Tags on this object."""
doc = self._request(self.ws_prefix + ".getTopTags", True)
elements = doc.getElementsByTagName("tag")
seq = []
for element in elements:
tag_name = _extract(element, "name")
tagcount = _extract(element, "count")
seq.append(TopItem(Tag(tag_name, self.network), tagcount))
if limit:
seq = seq[:limit]
return seq | [
"def",
"get_top_tags",
"(",
"self",
",",
"limit",
"=",
"None",
")",
":",
"doc",
"=",
"self",
".",
"_request",
"(",
"self",
".",
"ws_prefix",
"+",
"\".getTopTags\"",
",",
"True",
")",
"elements",
"=",
"doc",
".",
"getElementsByTagName",
"(",
"\"tag\"",
")... | Returns a list of the most frequently used Tags on this object. | [
"Returns",
"a",
"list",
"of",
"the",
"most",
"frequently",
"used",
"Tags",
"on",
"this",
"object",
"."
] | a52f66d316797fc819b5f1d186d77f18ba97b4ff | https://github.com/pylast/pylast/blob/a52f66d316797fc819b5f1d186d77f18ba97b4ff/src/pylast/__init__.py#L1395-L1412 | train | 34,731 |
pylast/pylast | src/pylast/__init__.py | _Opus.get_title | def get_title(self, properly_capitalized=False):
"""Returns the artist or track title."""
if properly_capitalized:
self.title = _extract(
self._request(self.ws_prefix + ".getInfo", True), "name"
)
return self.title | python | def get_title(self, properly_capitalized=False):
"""Returns the artist or track title."""
if properly_capitalized:
self.title = _extract(
self._request(self.ws_prefix + ".getInfo", True), "name"
)
return self.title | [
"def",
"get_title",
"(",
"self",
",",
"properly_capitalized",
"=",
"False",
")",
":",
"if",
"properly_capitalized",
":",
"self",
".",
"title",
"=",
"_extract",
"(",
"self",
".",
"_request",
"(",
"self",
".",
"ws_prefix",
"+",
"\".getInfo\"",
",",
"True",
"... | Returns the artist or track title. | [
"Returns",
"the",
"artist",
"or",
"track",
"title",
"."
] | a52f66d316797fc819b5f1d186d77f18ba97b4ff | https://github.com/pylast/pylast/blob/a52f66d316797fc819b5f1d186d77f18ba97b4ff/src/pylast/__init__.py#L1566-L1573 | train | 34,732 |
pylast/pylast | src/pylast/__init__.py | _Opus.get_playcount | def get_playcount(self):
"""Returns the number of plays on the network"""
return _number(
_extract(
self._request(self.ws_prefix + ".getInfo", cacheable=True), "playcount"
)
) | python | def get_playcount(self):
"""Returns the number of plays on the network"""
return _number(
_extract(
self._request(self.ws_prefix + ".getInfo", cacheable=True), "playcount"
)
) | [
"def",
"get_playcount",
"(",
"self",
")",
":",
"return",
"_number",
"(",
"_extract",
"(",
"self",
".",
"_request",
"(",
"self",
".",
"ws_prefix",
"+",
"\".getInfo\"",
",",
"cacheable",
"=",
"True",
")",
",",
"\"playcount\"",
")",
")"
] | Returns the number of plays on the network | [
"Returns",
"the",
"number",
"of",
"plays",
"on",
"the",
"network"
] | a52f66d316797fc819b5f1d186d77f18ba97b4ff | https://github.com/pylast/pylast/blob/a52f66d316797fc819b5f1d186d77f18ba97b4ff/src/pylast/__init__.py#L1580-L1587 | train | 34,733 |
pylast/pylast | src/pylast/__init__.py | _Opus.get_userplaycount | def get_userplaycount(self):
"""Returns the number of plays by a given username"""
if not self.username:
return
params = self._get_params()
params["username"] = self.username
doc = self._request(self.ws_prefix + ".getInfo", True, params)
return _number(_extract(doc, "userplaycount")) | python | def get_userplaycount(self):
"""Returns the number of plays by a given username"""
if not self.username:
return
params = self._get_params()
params["username"] = self.username
doc = self._request(self.ws_prefix + ".getInfo", True, params)
return _number(_extract(doc, "userplaycount")) | [
"def",
"get_userplaycount",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"username",
":",
"return",
"params",
"=",
"self",
".",
"_get_params",
"(",
")",
"params",
"[",
"\"username\"",
"]",
"=",
"self",
".",
"username",
"doc",
"=",
"self",
".",
"_re... | Returns the number of plays by a given username | [
"Returns",
"the",
"number",
"of",
"plays",
"by",
"a",
"given",
"username"
] | a52f66d316797fc819b5f1d186d77f18ba97b4ff | https://github.com/pylast/pylast/blob/a52f66d316797fc819b5f1d186d77f18ba97b4ff/src/pylast/__init__.py#L1589-L1599 | train | 34,734 |
pylast/pylast | src/pylast/__init__.py | _Opus.get_listener_count | def get_listener_count(self):
"""Returns the number of listeners on the network"""
return _number(
_extract(
self._request(self.ws_prefix + ".getInfo", cacheable=True), "listeners"
)
) | python | def get_listener_count(self):
"""Returns the number of listeners on the network"""
return _number(
_extract(
self._request(self.ws_prefix + ".getInfo", cacheable=True), "listeners"
)
) | [
"def",
"get_listener_count",
"(",
"self",
")",
":",
"return",
"_number",
"(",
"_extract",
"(",
"self",
".",
"_request",
"(",
"self",
".",
"ws_prefix",
"+",
"\".getInfo\"",
",",
"cacheable",
"=",
"True",
")",
",",
"\"listeners\"",
")",
")"
] | Returns the number of listeners on the network | [
"Returns",
"the",
"number",
"of",
"listeners",
"on",
"the",
"network"
] | a52f66d316797fc819b5f1d186d77f18ba97b4ff | https://github.com/pylast/pylast/blob/a52f66d316797fc819b5f1d186d77f18ba97b4ff/src/pylast/__init__.py#L1601-L1608 | train | 34,735 |
pylast/pylast | src/pylast/__init__.py | _Opus.get_mbid | def get_mbid(self):
"""Returns the MusicBrainz ID of the album or track."""
doc = self._request(self.ws_prefix + ".getInfo", cacheable=True)
try:
lfm = doc.getElementsByTagName("lfm")[0]
opus = next(self._get_children_by_tag_name(lfm, self.ws_prefix))
mbid = next(self._get_children_by_tag_name(opus, "mbid"))
return mbid.firstChild.nodeValue
except StopIteration:
return None | python | def get_mbid(self):
"""Returns the MusicBrainz ID of the album or track."""
doc = self._request(self.ws_prefix + ".getInfo", cacheable=True)
try:
lfm = doc.getElementsByTagName("lfm")[0]
opus = next(self._get_children_by_tag_name(lfm, self.ws_prefix))
mbid = next(self._get_children_by_tag_name(opus, "mbid"))
return mbid.firstChild.nodeValue
except StopIteration:
return None | [
"def",
"get_mbid",
"(",
"self",
")",
":",
"doc",
"=",
"self",
".",
"_request",
"(",
"self",
".",
"ws_prefix",
"+",
"\".getInfo\"",
",",
"cacheable",
"=",
"True",
")",
"try",
":",
"lfm",
"=",
"doc",
".",
"getElementsByTagName",
"(",
"\"lfm\"",
")",
"[",... | Returns the MusicBrainz ID of the album or track. | [
"Returns",
"the",
"MusicBrainz",
"ID",
"of",
"the",
"album",
"or",
"track",
"."
] | a52f66d316797fc819b5f1d186d77f18ba97b4ff | https://github.com/pylast/pylast/blob/a52f66d316797fc819b5f1d186d77f18ba97b4ff/src/pylast/__init__.py#L1610-L1621 | train | 34,736 |
pylast/pylast | src/pylast/__init__.py | Album.get_tracks | def get_tracks(self):
"""Returns the list of Tracks on this album."""
return _extract_tracks(
self._request(self.ws_prefix + ".getInfo", cacheable=True), self.network
) | python | def get_tracks(self):
"""Returns the list of Tracks on this album."""
return _extract_tracks(
self._request(self.ws_prefix + ".getInfo", cacheable=True), self.network
) | [
"def",
"get_tracks",
"(",
"self",
")",
":",
"return",
"_extract_tracks",
"(",
"self",
".",
"_request",
"(",
"self",
".",
"ws_prefix",
"+",
"\".getInfo\"",
",",
"cacheable",
"=",
"True",
")",
",",
"self",
".",
"network",
")"
] | Returns the list of Tracks on this album. | [
"Returns",
"the",
"list",
"of",
"Tracks",
"on",
"this",
"album",
"."
] | a52f66d316797fc819b5f1d186d77f18ba97b4ff | https://github.com/pylast/pylast/blob/a52f66d316797fc819b5f1d186d77f18ba97b4ff/src/pylast/__init__.py#L1639-L1644 | train | 34,737 |
pylast/pylast | src/pylast/__init__.py | Artist.get_name | def get_name(self, properly_capitalized=False):
"""Returns the name of the artist.
If properly_capitalized was asserted then the name would be downloaded
overwriting the given one."""
if properly_capitalized:
self.name = _extract(
self._request(self.ws_prefix + ".getInfo", True), "name"
)
return self.name | python | def get_name(self, properly_capitalized=False):
"""Returns the name of the artist.
If properly_capitalized was asserted then the name would be downloaded
overwriting the given one."""
if properly_capitalized:
self.name = _extract(
self._request(self.ws_prefix + ".getInfo", True), "name"
)
return self.name | [
"def",
"get_name",
"(",
"self",
",",
"properly_capitalized",
"=",
"False",
")",
":",
"if",
"properly_capitalized",
":",
"self",
".",
"name",
"=",
"_extract",
"(",
"self",
".",
"_request",
"(",
"self",
".",
"ws_prefix",
"+",
"\".getInfo\"",
",",
"True",
")"... | Returns the name of the artist.
If properly_capitalized was asserted then the name would be downloaded
overwriting the given one. | [
"Returns",
"the",
"name",
"of",
"the",
"artist",
".",
"If",
"properly_capitalized",
"was",
"asserted",
"then",
"the",
"name",
"would",
"be",
"downloaded",
"overwriting",
"the",
"given",
"one",
"."
] | a52f66d316797fc819b5f1d186d77f18ba97b4ff | https://github.com/pylast/pylast/blob/a52f66d316797fc819b5f1d186d77f18ba97b4ff/src/pylast/__init__.py#L1719-L1729 | train | 34,738 |
pylast/pylast | src/pylast/__init__.py | Artist.get_mbid | def get_mbid(self):
"""Returns the MusicBrainz ID of this artist."""
doc = self._request(self.ws_prefix + ".getInfo", True)
return _extract(doc, "mbid") | python | def get_mbid(self):
"""Returns the MusicBrainz ID of this artist."""
doc = self._request(self.ws_prefix + ".getInfo", True)
return _extract(doc, "mbid") | [
"def",
"get_mbid",
"(",
"self",
")",
":",
"doc",
"=",
"self",
".",
"_request",
"(",
"self",
".",
"ws_prefix",
"+",
"\".getInfo\"",
",",
"True",
")",
"return",
"_extract",
"(",
"doc",
",",
"\"mbid\"",
")"
] | Returns the MusicBrainz ID of this artist. | [
"Returns",
"the",
"MusicBrainz",
"ID",
"of",
"this",
"artist",
"."
] | a52f66d316797fc819b5f1d186d77f18ba97b4ff | https://github.com/pylast/pylast/blob/a52f66d316797fc819b5f1d186d77f18ba97b4ff/src/pylast/__init__.py#L1772-L1777 | train | 34,739 |
pylast/pylast | src/pylast/__init__.py | Artist.get_listener_count | def get_listener_count(self):
"""Returns the number of listeners on the network."""
if hasattr(self, "listener_count"):
return self.listener_count
else:
self.listener_count = _number(
_extract(self._request(self.ws_prefix + ".getInfo", True), "listeners")
)
return self.listener_count | python | def get_listener_count(self):
"""Returns the number of listeners on the network."""
if hasattr(self, "listener_count"):
return self.listener_count
else:
self.listener_count = _number(
_extract(self._request(self.ws_prefix + ".getInfo", True), "listeners")
)
return self.listener_count | [
"def",
"get_listener_count",
"(",
"self",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"\"listener_count\"",
")",
":",
"return",
"self",
".",
"listener_count",
"else",
":",
"self",
".",
"listener_count",
"=",
"_number",
"(",
"_extract",
"(",
"self",
".",
"... | Returns the number of listeners on the network. | [
"Returns",
"the",
"number",
"of",
"listeners",
"on",
"the",
"network",
"."
] | a52f66d316797fc819b5f1d186d77f18ba97b4ff | https://github.com/pylast/pylast/blob/a52f66d316797fc819b5f1d186d77f18ba97b4ff/src/pylast/__init__.py#L1779-L1788 | train | 34,740 |
pylast/pylast | src/pylast/__init__.py | Artist.is_streamable | def is_streamable(self):
"""Returns True if the artist is streamable."""
return bool(
_number(
_extract(self._request(self.ws_prefix + ".getInfo", True), "streamable")
)
) | python | def is_streamable(self):
"""Returns True if the artist is streamable."""
return bool(
_number(
_extract(self._request(self.ws_prefix + ".getInfo", True), "streamable")
)
) | [
"def",
"is_streamable",
"(",
"self",
")",
":",
"return",
"bool",
"(",
"_number",
"(",
"_extract",
"(",
"self",
".",
"_request",
"(",
"self",
".",
"ws_prefix",
"+",
"\".getInfo\"",
",",
"True",
")",
",",
"\"streamable\"",
")",
")",
")"
] | Returns True if the artist is streamable. | [
"Returns",
"True",
"if",
"the",
"artist",
"is",
"streamable",
"."
] | a52f66d316797fc819b5f1d186d77f18ba97b4ff | https://github.com/pylast/pylast/blob/a52f66d316797fc819b5f1d186d77f18ba97b4ff/src/pylast/__init__.py#L1790-L1797 | train | 34,741 |
pylast/pylast | src/pylast/__init__.py | Artist.get_similar | def get_similar(self, limit=None):
"""Returns the similar artists on the network."""
params = self._get_params()
if limit:
params["limit"] = limit
doc = self._request(self.ws_prefix + ".getSimilar", True, params)
names = _extract_all(doc, "name")
matches = _extract_all(doc, "match")
artists = []
for i in range(0, len(names)):
artists.append(
SimilarItem(Artist(names[i], self.network), _number(matches[i]))
)
return artists | python | def get_similar(self, limit=None):
"""Returns the similar artists on the network."""
params = self._get_params()
if limit:
params["limit"] = limit
doc = self._request(self.ws_prefix + ".getSimilar", True, params)
names = _extract_all(doc, "name")
matches = _extract_all(doc, "match")
artists = []
for i in range(0, len(names)):
artists.append(
SimilarItem(Artist(names[i], self.network), _number(matches[i]))
)
return artists | [
"def",
"get_similar",
"(",
"self",
",",
"limit",
"=",
"None",
")",
":",
"params",
"=",
"self",
".",
"_get_params",
"(",
")",
"if",
"limit",
":",
"params",
"[",
"\"limit\"",
"]",
"=",
"limit",
"doc",
"=",
"self",
".",
"_request",
"(",
"self",
".",
"... | Returns the similar artists on the network. | [
"Returns",
"the",
"similar",
"artists",
"on",
"the",
"network",
"."
] | a52f66d316797fc819b5f1d186d77f18ba97b4ff | https://github.com/pylast/pylast/blob/a52f66d316797fc819b5f1d186d77f18ba97b4ff/src/pylast/__init__.py#L1827-L1845 | train | 34,742 |
pylast/pylast | src/pylast/__init__.py | Artist.get_top_albums | def get_top_albums(self, limit=None, cacheable=True):
"""Returns a list of the top albums."""
params = self._get_params()
if limit:
params["limit"] = limit
return self._get_things("getTopAlbums", "album", Album, params, cacheable) | python | def get_top_albums(self, limit=None, cacheable=True):
"""Returns a list of the top albums."""
params = self._get_params()
if limit:
params["limit"] = limit
return self._get_things("getTopAlbums", "album", Album, params, cacheable) | [
"def",
"get_top_albums",
"(",
"self",
",",
"limit",
"=",
"None",
",",
"cacheable",
"=",
"True",
")",
":",
"params",
"=",
"self",
".",
"_get_params",
"(",
")",
"if",
"limit",
":",
"params",
"[",
"\"limit\"",
"]",
"=",
"limit",
"return",
"self",
".",
"... | Returns a list of the top albums. | [
"Returns",
"a",
"list",
"of",
"the",
"top",
"albums",
"."
] | a52f66d316797fc819b5f1d186d77f18ba97b4ff | https://github.com/pylast/pylast/blob/a52f66d316797fc819b5f1d186d77f18ba97b4ff/src/pylast/__init__.py#L1847-L1853 | train | 34,743 |
pylast/pylast | src/pylast/__init__.py | Artist.get_top_tracks | def get_top_tracks(self, limit=None, cacheable=True):
"""Returns a list of the most played Tracks by this artist."""
params = self._get_params()
if limit:
params["limit"] = limit
return self._get_things("getTopTracks", "track", Track, params, cacheable) | python | def get_top_tracks(self, limit=None, cacheable=True):
"""Returns a list of the most played Tracks by this artist."""
params = self._get_params()
if limit:
params["limit"] = limit
return self._get_things("getTopTracks", "track", Track, params, cacheable) | [
"def",
"get_top_tracks",
"(",
"self",
",",
"limit",
"=",
"None",
",",
"cacheable",
"=",
"True",
")",
":",
"params",
"=",
"self",
".",
"_get_params",
"(",
")",
"if",
"limit",
":",
"params",
"[",
"\"limit\"",
"]",
"=",
"limit",
"return",
"self",
".",
"... | Returns a list of the most played Tracks by this artist. | [
"Returns",
"a",
"list",
"of",
"the",
"most",
"played",
"Tracks",
"by",
"this",
"artist",
"."
] | a52f66d316797fc819b5f1d186d77f18ba97b4ff | https://github.com/pylast/pylast/blob/a52f66d316797fc819b5f1d186d77f18ba97b4ff/src/pylast/__init__.py#L1855-L1861 | train | 34,744 |
pylast/pylast | src/pylast/__init__.py | Country.get_top_artists | def get_top_artists(self, limit=None, cacheable=True):
"""Returns a sequence of the most played artists."""
params = self._get_params()
if limit:
params["limit"] = limit
doc = self._request("geo.getTopArtists", cacheable, params)
return _extract_top_artists(doc, self) | python | def get_top_artists(self, limit=None, cacheable=True):
"""Returns a sequence of the most played artists."""
params = self._get_params()
if limit:
params["limit"] = limit
doc = self._request("geo.getTopArtists", cacheable, params)
return _extract_top_artists(doc, self) | [
"def",
"get_top_artists",
"(",
"self",
",",
"limit",
"=",
"None",
",",
"cacheable",
"=",
"True",
")",
":",
"params",
"=",
"self",
".",
"_get_params",
"(",
")",
"if",
"limit",
":",
"params",
"[",
"\"limit\"",
"]",
"=",
"limit",
"doc",
"=",
"self",
"."... | Returns a sequence of the most played artists. | [
"Returns",
"a",
"sequence",
"of",
"the",
"most",
"played",
"artists",
"."
] | a52f66d316797fc819b5f1d186d77f18ba97b4ff | https://github.com/pylast/pylast/blob/a52f66d316797fc819b5f1d186d77f18ba97b4ff/src/pylast/__init__.py#L1919-L1927 | train | 34,745 |
pylast/pylast | src/pylast/__init__.py | Track.get_duration | def get_duration(self):
"""Returns the track duration."""
doc = self._request(self.ws_prefix + ".getInfo", True)
return _number(_extract(doc, "duration")) | python | def get_duration(self):
"""Returns the track duration."""
doc = self._request(self.ws_prefix + ".getInfo", True)
return _number(_extract(doc, "duration")) | [
"def",
"get_duration",
"(",
"self",
")",
":",
"doc",
"=",
"self",
".",
"_request",
"(",
"self",
".",
"ws_prefix",
"+",
"\".getInfo\"",
",",
"True",
")",
"return",
"_number",
"(",
"_extract",
"(",
"doc",
",",
"\"duration\"",
")",
")"
] | Returns the track duration. | [
"Returns",
"the",
"track",
"duration",
"."
] | a52f66d316797fc819b5f1d186d77f18ba97b4ff | https://github.com/pylast/pylast/blob/a52f66d316797fc819b5f1d186d77f18ba97b4ff/src/pylast/__init__.py#L2113-L2118 | train | 34,746 |
pylast/pylast | src/pylast/__init__.py | Track.get_userloved | def get_userloved(self):
"""Whether the user loved this track"""
if not self.username:
return
params = self._get_params()
params["username"] = self.username
doc = self._request(self.ws_prefix + ".getInfo", True, params)
loved = _number(_extract(doc, "userloved"))
return bool(loved) | python | def get_userloved(self):
"""Whether the user loved this track"""
if not self.username:
return
params = self._get_params()
params["username"] = self.username
doc = self._request(self.ws_prefix + ".getInfo", True, params)
loved = _number(_extract(doc, "userloved"))
return bool(loved) | [
"def",
"get_userloved",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"username",
":",
"return",
"params",
"=",
"self",
".",
"_get_params",
"(",
")",
"params",
"[",
"\"username\"",
"]",
"=",
"self",
".",
"username",
"doc",
"=",
"self",
".",
"_reques... | Whether the user loved this track | [
"Whether",
"the",
"user",
"loved",
"this",
"track"
] | a52f66d316797fc819b5f1d186d77f18ba97b4ff | https://github.com/pylast/pylast/blob/a52f66d316797fc819b5f1d186d77f18ba97b4ff/src/pylast/__init__.py#L2120-L2131 | train | 34,747 |
pylast/pylast | src/pylast/__init__.py | Track.is_streamable | def is_streamable(self):
"""Returns True if the track is available at Last.fm."""
doc = self._request(self.ws_prefix + ".getInfo", True)
return _extract(doc, "streamable") == "1" | python | def is_streamable(self):
"""Returns True if the track is available at Last.fm."""
doc = self._request(self.ws_prefix + ".getInfo", True)
return _extract(doc, "streamable") == "1" | [
"def",
"is_streamable",
"(",
"self",
")",
":",
"doc",
"=",
"self",
".",
"_request",
"(",
"self",
".",
"ws_prefix",
"+",
"\".getInfo\"",
",",
"True",
")",
"return",
"_extract",
"(",
"doc",
",",
"\"streamable\"",
")",
"==",
"\"1\""
] | Returns True if the track is available at Last.fm. | [
"Returns",
"True",
"if",
"the",
"track",
"is",
"available",
"at",
"Last",
".",
"fm",
"."
] | a52f66d316797fc819b5f1d186d77f18ba97b4ff | https://github.com/pylast/pylast/blob/a52f66d316797fc819b5f1d186d77f18ba97b4ff/src/pylast/__init__.py#L2133-L2137 | train | 34,748 |
pylast/pylast | src/pylast/__init__.py | Track.is_fulltrack_available | def is_fulltrack_available(self):
"""Returns True if the full track is available for streaming."""
doc = self._request(self.ws_prefix + ".getInfo", True)
return (
doc.getElementsByTagName("streamable")[0].getAttribute("fulltrack") == "1"
) | python | def is_fulltrack_available(self):
"""Returns True if the full track is available for streaming."""
doc = self._request(self.ws_prefix + ".getInfo", True)
return (
doc.getElementsByTagName("streamable")[0].getAttribute("fulltrack") == "1"
) | [
"def",
"is_fulltrack_available",
"(",
"self",
")",
":",
"doc",
"=",
"self",
".",
"_request",
"(",
"self",
".",
"ws_prefix",
"+",
"\".getInfo\"",
",",
"True",
")",
"return",
"(",
"doc",
".",
"getElementsByTagName",
"(",
"\"streamable\"",
")",
"[",
"0",
"]",... | Returns True if the full track is available for streaming. | [
"Returns",
"True",
"if",
"the",
"full",
"track",
"is",
"available",
"for",
"streaming",
"."
] | a52f66d316797fc819b5f1d186d77f18ba97b4ff | https://github.com/pylast/pylast/blob/a52f66d316797fc819b5f1d186d77f18ba97b4ff/src/pylast/__init__.py#L2139-L2145 | train | 34,749 |
pylast/pylast | src/pylast/__init__.py | Track.get_album | def get_album(self):
"""Returns the album object of this track."""
doc = self._request(self.ws_prefix + ".getInfo", True)
albums = doc.getElementsByTagName("album")
if len(albums) == 0:
return
node = doc.getElementsByTagName("album")[0]
return Album(_extract(node, "artist"), _extract(node, "title"), self.network) | python | def get_album(self):
"""Returns the album object of this track."""
doc = self._request(self.ws_prefix + ".getInfo", True)
albums = doc.getElementsByTagName("album")
if len(albums) == 0:
return
node = doc.getElementsByTagName("album")[0]
return Album(_extract(node, "artist"), _extract(node, "title"), self.network) | [
"def",
"get_album",
"(",
"self",
")",
":",
"doc",
"=",
"self",
".",
"_request",
"(",
"self",
".",
"ws_prefix",
"+",
"\".getInfo\"",
",",
"True",
")",
"albums",
"=",
"doc",
".",
"getElementsByTagName",
"(",
"\"album\"",
")",
"if",
"len",
"(",
"albums",
... | Returns the album object of this track. | [
"Returns",
"the",
"album",
"object",
"of",
"this",
"track",
"."
] | a52f66d316797fc819b5f1d186d77f18ba97b4ff | https://github.com/pylast/pylast/blob/a52f66d316797fc819b5f1d186d77f18ba97b4ff/src/pylast/__init__.py#L2147-L2158 | train | 34,750 |
pylast/pylast | src/pylast/__init__.py | Track.get_similar | def get_similar(self, limit=None):
"""
Returns similar tracks for this track on the network,
based on listening data.
"""
params = self._get_params()
if limit:
params["limit"] = limit
doc = self._request(self.ws_prefix + ".getSimilar", True, params)
seq = []
for node in doc.getElementsByTagName(self.ws_prefix):
title = _extract(node, "name")
artist = _extract(node, "name", 1)
match = _number(_extract(node, "match"))
seq.append(SimilarItem(Track(artist, title, self.network), match))
return seq | python | def get_similar(self, limit=None):
"""
Returns similar tracks for this track on the network,
based on listening data.
"""
params = self._get_params()
if limit:
params["limit"] = limit
doc = self._request(self.ws_prefix + ".getSimilar", True, params)
seq = []
for node in doc.getElementsByTagName(self.ws_prefix):
title = _extract(node, "name")
artist = _extract(node, "name", 1)
match = _number(_extract(node, "match"))
seq.append(SimilarItem(Track(artist, title, self.network), match))
return seq | [
"def",
"get_similar",
"(",
"self",
",",
"limit",
"=",
"None",
")",
":",
"params",
"=",
"self",
".",
"_get_params",
"(",
")",
"if",
"limit",
":",
"params",
"[",
"\"limit\"",
"]",
"=",
"limit",
"doc",
"=",
"self",
".",
"_request",
"(",
"self",
".",
"... | Returns similar tracks for this track on the network,
based on listening data. | [
"Returns",
"similar",
"tracks",
"for",
"this",
"track",
"on",
"the",
"network",
"based",
"on",
"listening",
"data",
"."
] | a52f66d316797fc819b5f1d186d77f18ba97b4ff | https://github.com/pylast/pylast/blob/a52f66d316797fc819b5f1d186d77f18ba97b4ff/src/pylast/__init__.py#L2170-L2190 | train | 34,751 |
pylast/pylast | src/pylast/__init__.py | User.get_artist_tracks | def get_artist_tracks(self, artist, cacheable=False):
"""
Get a list of tracks by a given artist scrobbled by this user,
including scrobble time.
"""
# Not implemented:
# "Can be limited to specific timeranges, defaults to all time."
warnings.warn(
"User.get_artist_tracks is deprecated and will be removed in a future "
"version. User.get_track_scrobbles is a partial replacement. "
"See https://github.com/pylast/pylast/issues/298",
DeprecationWarning,
stacklevel=2,
)
params = self._get_params()
params["artist"] = artist
seq = []
for track in _collect_nodes(
None, self, self.ws_prefix + ".getArtistTracks", cacheable, params
):
title = _extract(track, "name")
artist = _extract(track, "artist")
date = _extract(track, "date")
album = _extract(track, "album")
timestamp = track.getElementsByTagName("date")[0].getAttribute("uts")
seq.append(
PlayedTrack(Track(artist, title, self.network), album, date, timestamp)
)
return seq | python | def get_artist_tracks(self, artist, cacheable=False):
"""
Get a list of tracks by a given artist scrobbled by this user,
including scrobble time.
"""
# Not implemented:
# "Can be limited to specific timeranges, defaults to all time."
warnings.warn(
"User.get_artist_tracks is deprecated and will be removed in a future "
"version. User.get_track_scrobbles is a partial replacement. "
"See https://github.com/pylast/pylast/issues/298",
DeprecationWarning,
stacklevel=2,
)
params = self._get_params()
params["artist"] = artist
seq = []
for track in _collect_nodes(
None, self, self.ws_prefix + ".getArtistTracks", cacheable, params
):
title = _extract(track, "name")
artist = _extract(track, "artist")
date = _extract(track, "date")
album = _extract(track, "album")
timestamp = track.getElementsByTagName("date")[0].getAttribute("uts")
seq.append(
PlayedTrack(Track(artist, title, self.network), album, date, timestamp)
)
return seq | [
"def",
"get_artist_tracks",
"(",
"self",
",",
"artist",
",",
"cacheable",
"=",
"False",
")",
":",
"# Not implemented:",
"# \"Can be limited to specific timeranges, defaults to all time.\"",
"warnings",
".",
"warn",
"(",
"\"User.get_artist_tracks is deprecated and will be removed ... | Get a list of tracks by a given artist scrobbled by this user,
including scrobble time. | [
"Get",
"a",
"list",
"of",
"tracks",
"by",
"a",
"given",
"artist",
"scrobbled",
"by",
"this",
"user",
"including",
"scrobble",
"time",
"."
] | a52f66d316797fc819b5f1d186d77f18ba97b4ff | https://github.com/pylast/pylast/blob/a52f66d316797fc819b5f1d186d77f18ba97b4ff/src/pylast/__init__.py#L2261-L2294 | train | 34,752 |
pylast/pylast | src/pylast/__init__.py | User.get_friends | def get_friends(self, limit=50, cacheable=False):
"""Returns a list of the user's friends. """
seq = []
for node in _collect_nodes(
limit, self, self.ws_prefix + ".getFriends", cacheable
):
seq.append(User(_extract(node, "name"), self.network))
return seq | python | def get_friends(self, limit=50, cacheable=False):
"""Returns a list of the user's friends. """
seq = []
for node in _collect_nodes(
limit, self, self.ws_prefix + ".getFriends", cacheable
):
seq.append(User(_extract(node, "name"), self.network))
return seq | [
"def",
"get_friends",
"(",
"self",
",",
"limit",
"=",
"50",
",",
"cacheable",
"=",
"False",
")",
":",
"seq",
"=",
"[",
"]",
"for",
"node",
"in",
"_collect_nodes",
"(",
"limit",
",",
"self",
",",
"self",
".",
"ws_prefix",
"+",
"\".getFriends\"",
",",
... | Returns a list of the user's friends. | [
"Returns",
"a",
"list",
"of",
"the",
"user",
"s",
"friends",
"."
] | a52f66d316797fc819b5f1d186d77f18ba97b4ff | https://github.com/pylast/pylast/blob/a52f66d316797fc819b5f1d186d77f18ba97b4ff/src/pylast/__init__.py#L2296-L2305 | train | 34,753 |
pylast/pylast | src/pylast/__init__.py | User.get_loved_tracks | def get_loved_tracks(self, limit=50, cacheable=True):
"""
Returns this user's loved track as a sequence of LovedTrack objects in
reverse order of their timestamp, all the way back to the first track.
If limit==None, it will try to pull all the available data.
This method uses caching. Enable caching only if you're pulling a
large amount of data.
"""
params = self._get_params()
if limit:
params["limit"] = limit
seq = []
for track in _collect_nodes(
limit, self, self.ws_prefix + ".getLovedTracks", cacheable, params
):
try:
artist = _extract(track, "name", 1)
except IndexError: # pragma: no cover
continue
title = _extract(track, "name")
date = _extract(track, "date")
timestamp = track.getElementsByTagName("date")[0].getAttribute("uts")
seq.append(LovedTrack(Track(artist, title, self.network), date, timestamp))
return seq | python | def get_loved_tracks(self, limit=50, cacheable=True):
"""
Returns this user's loved track as a sequence of LovedTrack objects in
reverse order of their timestamp, all the way back to the first track.
If limit==None, it will try to pull all the available data.
This method uses caching. Enable caching only if you're pulling a
large amount of data.
"""
params = self._get_params()
if limit:
params["limit"] = limit
seq = []
for track in _collect_nodes(
limit, self, self.ws_prefix + ".getLovedTracks", cacheable, params
):
try:
artist = _extract(track, "name", 1)
except IndexError: # pragma: no cover
continue
title = _extract(track, "name")
date = _extract(track, "date")
timestamp = track.getElementsByTagName("date")[0].getAttribute("uts")
seq.append(LovedTrack(Track(artist, title, self.network), date, timestamp))
return seq | [
"def",
"get_loved_tracks",
"(",
"self",
",",
"limit",
"=",
"50",
",",
"cacheable",
"=",
"True",
")",
":",
"params",
"=",
"self",
".",
"_get_params",
"(",
")",
"if",
"limit",
":",
"params",
"[",
"\"limit\"",
"]",
"=",
"limit",
"seq",
"=",
"[",
"]",
... | Returns this user's loved track as a sequence of LovedTrack objects in
reverse order of their timestamp, all the way back to the first track.
If limit==None, it will try to pull all the available data.
This method uses caching. Enable caching only if you're pulling a
large amount of data. | [
"Returns",
"this",
"user",
"s",
"loved",
"track",
"as",
"a",
"sequence",
"of",
"LovedTrack",
"objects",
"in",
"reverse",
"order",
"of",
"their",
"timestamp",
"all",
"the",
"way",
"back",
"to",
"the",
"first",
"track",
"."
] | a52f66d316797fc819b5f1d186d77f18ba97b4ff | https://github.com/pylast/pylast/blob/a52f66d316797fc819b5f1d186d77f18ba97b4ff/src/pylast/__init__.py#L2307-L2336 | train | 34,754 |
pylast/pylast | src/pylast/__init__.py | User.get_now_playing | def get_now_playing(self):
"""
Returns the currently playing track, or None if nothing is playing.
"""
params = self._get_params()
params["limit"] = "1"
doc = self._request(self.ws_prefix + ".getRecentTracks", False, params)
tracks = doc.getElementsByTagName("track")
if len(tracks) == 0:
return None
e = tracks[0]
if not e.hasAttribute("nowplaying"):
return None
artist = _extract(e, "artist")
title = _extract(e, "name")
return Track(artist, title, self.network, self.name) | python | def get_now_playing(self):
"""
Returns the currently playing track, or None if nothing is playing.
"""
params = self._get_params()
params["limit"] = "1"
doc = self._request(self.ws_prefix + ".getRecentTracks", False, params)
tracks = doc.getElementsByTagName("track")
if len(tracks) == 0:
return None
e = tracks[0]
if not e.hasAttribute("nowplaying"):
return None
artist = _extract(e, "artist")
title = _extract(e, "name")
return Track(artist, title, self.network, self.name) | [
"def",
"get_now_playing",
"(",
"self",
")",
":",
"params",
"=",
"self",
".",
"_get_params",
"(",
")",
"params",
"[",
"\"limit\"",
"]",
"=",
"\"1\"",
"doc",
"=",
"self",
".",
"_request",
"(",
"self",
".",
"ws_prefix",
"+",
"\".getRecentTracks\"",
",",
"Fa... | Returns the currently playing track, or None if nothing is playing. | [
"Returns",
"the",
"currently",
"playing",
"track",
"or",
"None",
"if",
"nothing",
"is",
"playing",
"."
] | a52f66d316797fc819b5f1d186d77f18ba97b4ff | https://github.com/pylast/pylast/blob/a52f66d316797fc819b5f1d186d77f18ba97b4ff/src/pylast/__init__.py#L2338-L2361 | train | 34,755 |
pylast/pylast | src/pylast/__init__.py | User.get_recent_tracks | def get_recent_tracks(self, limit=10, cacheable=True, time_from=None, time_to=None):
"""
Returns this user's played track as a sequence of PlayedTrack objects
in reverse order of playtime, all the way back to the first track.
Parameters:
limit : If None, it will try to pull all the available data.
from (Optional) : Beginning timestamp of a range - only display
scrobbles after this time, in UNIX timestamp format (integer
number of seconds since 00:00:00, January 1st 1970 UTC). This
must be in the UTC time zone.
to (Optional) : End timestamp of a range - only display scrobbles
before this time, in UNIX timestamp format (integer number of
seconds since 00:00:00, January 1st 1970 UTC). This must be in
the UTC time zone.
This method uses caching. Enable caching only if you're pulling a
large amount of data.
"""
params = self._get_params()
if limit:
params["limit"] = limit
if time_from:
params["from"] = time_from
if time_to:
params["to"] = time_to
seq = []
for track in _collect_nodes(
limit, self, self.ws_prefix + ".getRecentTracks", cacheable, params
):
if track.hasAttribute("nowplaying"):
continue # to prevent the now playing track from sneaking in
title = _extract(track, "name")
artist = _extract(track, "artist")
date = _extract(track, "date")
album = _extract(track, "album")
timestamp = track.getElementsByTagName("date")[0].getAttribute("uts")
seq.append(
PlayedTrack(Track(artist, title, self.network), album, date, timestamp)
)
return seq | python | def get_recent_tracks(self, limit=10, cacheable=True, time_from=None, time_to=None):
"""
Returns this user's played track as a sequence of PlayedTrack objects
in reverse order of playtime, all the way back to the first track.
Parameters:
limit : If None, it will try to pull all the available data.
from (Optional) : Beginning timestamp of a range - only display
scrobbles after this time, in UNIX timestamp format (integer
number of seconds since 00:00:00, January 1st 1970 UTC). This
must be in the UTC time zone.
to (Optional) : End timestamp of a range - only display scrobbles
before this time, in UNIX timestamp format (integer number of
seconds since 00:00:00, January 1st 1970 UTC). This must be in
the UTC time zone.
This method uses caching. Enable caching only if you're pulling a
large amount of data.
"""
params = self._get_params()
if limit:
params["limit"] = limit
if time_from:
params["from"] = time_from
if time_to:
params["to"] = time_to
seq = []
for track in _collect_nodes(
limit, self, self.ws_prefix + ".getRecentTracks", cacheable, params
):
if track.hasAttribute("nowplaying"):
continue # to prevent the now playing track from sneaking in
title = _extract(track, "name")
artist = _extract(track, "artist")
date = _extract(track, "date")
album = _extract(track, "album")
timestamp = track.getElementsByTagName("date")[0].getAttribute("uts")
seq.append(
PlayedTrack(Track(artist, title, self.network), album, date, timestamp)
)
return seq | [
"def",
"get_recent_tracks",
"(",
"self",
",",
"limit",
"=",
"10",
",",
"cacheable",
"=",
"True",
",",
"time_from",
"=",
"None",
",",
"time_to",
"=",
"None",
")",
":",
"params",
"=",
"self",
".",
"_get_params",
"(",
")",
"if",
"limit",
":",
"params",
... | Returns this user's played track as a sequence of PlayedTrack objects
in reverse order of playtime, all the way back to the first track.
Parameters:
limit : If None, it will try to pull all the available data.
from (Optional) : Beginning timestamp of a range - only display
scrobbles after this time, in UNIX timestamp format (integer
number of seconds since 00:00:00, January 1st 1970 UTC). This
must be in the UTC time zone.
to (Optional) : End timestamp of a range - only display scrobbles
before this time, in UNIX timestamp format (integer number of
seconds since 00:00:00, January 1st 1970 UTC). This must be in
the UTC time zone.
This method uses caching. Enable caching only if you're pulling a
large amount of data. | [
"Returns",
"this",
"user",
"s",
"played",
"track",
"as",
"a",
"sequence",
"of",
"PlayedTrack",
"objects",
"in",
"reverse",
"order",
"of",
"playtime",
"all",
"the",
"way",
"back",
"to",
"the",
"first",
"track",
"."
] | a52f66d316797fc819b5f1d186d77f18ba97b4ff | https://github.com/pylast/pylast/blob/a52f66d316797fc819b5f1d186d77f18ba97b4ff/src/pylast/__init__.py#L2363-L2409 | train | 34,756 |
pylast/pylast | src/pylast/__init__.py | User.get_country | def get_country(self):
"""Returns the name of the country of the user."""
doc = self._request(self.ws_prefix + ".getInfo", True)
country = _extract(doc, "country")
if country is None or country == "None":
return None
else:
return Country(country, self.network) | python | def get_country(self):
"""Returns the name of the country of the user."""
doc = self._request(self.ws_prefix + ".getInfo", True)
country = _extract(doc, "country")
if country is None or country == "None":
return None
else:
return Country(country, self.network) | [
"def",
"get_country",
"(",
"self",
")",
":",
"doc",
"=",
"self",
".",
"_request",
"(",
"self",
".",
"ws_prefix",
"+",
"\".getInfo\"",
",",
"True",
")",
"country",
"=",
"_extract",
"(",
"doc",
",",
"\"country\"",
")",
"if",
"country",
"is",
"None",
"or"... | Returns the name of the country of the user. | [
"Returns",
"the",
"name",
"of",
"the",
"country",
"of",
"the",
"user",
"."
] | a52f66d316797fc819b5f1d186d77f18ba97b4ff | https://github.com/pylast/pylast/blob/a52f66d316797fc819b5f1d186d77f18ba97b4ff/src/pylast/__init__.py#L2411-L2421 | train | 34,757 |
pylast/pylast | src/pylast/__init__.py | User.is_subscriber | def is_subscriber(self):
"""Returns whether the user is a subscriber or not. True or False."""
doc = self._request(self.ws_prefix + ".getInfo", True)
return _extract(doc, "subscriber") == "1" | python | def is_subscriber(self):
"""Returns whether the user is a subscriber or not. True or False."""
doc = self._request(self.ws_prefix + ".getInfo", True)
return _extract(doc, "subscriber") == "1" | [
"def",
"is_subscriber",
"(",
"self",
")",
":",
"doc",
"=",
"self",
".",
"_request",
"(",
"self",
".",
"ws_prefix",
"+",
"\".getInfo\"",
",",
"True",
")",
"return",
"_extract",
"(",
"doc",
",",
"\"subscriber\"",
")",
"==",
"\"1\""
] | Returns whether the user is a subscriber or not. True or False. | [
"Returns",
"whether",
"the",
"user",
"is",
"a",
"subscriber",
"or",
"not",
".",
"True",
"or",
"False",
"."
] | a52f66d316797fc819b5f1d186d77f18ba97b4ff | https://github.com/pylast/pylast/blob/a52f66d316797fc819b5f1d186d77f18ba97b4ff/src/pylast/__init__.py#L2423-L2428 | train | 34,758 |
pylast/pylast | src/pylast/__init__.py | User.get_playcount | def get_playcount(self):
"""Returns the user's playcount so far."""
doc = self._request(self.ws_prefix + ".getInfo", True)
return _number(_extract(doc, "playcount")) | python | def get_playcount(self):
"""Returns the user's playcount so far."""
doc = self._request(self.ws_prefix + ".getInfo", True)
return _number(_extract(doc, "playcount")) | [
"def",
"get_playcount",
"(",
"self",
")",
":",
"doc",
"=",
"self",
".",
"_request",
"(",
"self",
".",
"ws_prefix",
"+",
"\".getInfo\"",
",",
"True",
")",
"return",
"_number",
"(",
"_extract",
"(",
"doc",
",",
"\"playcount\"",
")",
")"
] | Returns the user's playcount so far. | [
"Returns",
"the",
"user",
"s",
"playcount",
"so",
"far",
"."
] | a52f66d316797fc819b5f1d186d77f18ba97b4ff | https://github.com/pylast/pylast/blob/a52f66d316797fc819b5f1d186d77f18ba97b4ff/src/pylast/__init__.py#L2430-L2435 | train | 34,759 |
pylast/pylast | src/pylast/__init__.py | User.get_registered | def get_registered(self):
"""Returns the user's registration date."""
doc = self._request(self.ws_prefix + ".getInfo", True)
return _extract(doc, "registered") | python | def get_registered(self):
"""Returns the user's registration date."""
doc = self._request(self.ws_prefix + ".getInfo", True)
return _extract(doc, "registered") | [
"def",
"get_registered",
"(",
"self",
")",
":",
"doc",
"=",
"self",
".",
"_request",
"(",
"self",
".",
"ws_prefix",
"+",
"\".getInfo\"",
",",
"True",
")",
"return",
"_extract",
"(",
"doc",
",",
"\"registered\"",
")"
] | Returns the user's registration date. | [
"Returns",
"the",
"user",
"s",
"registration",
"date",
"."
] | a52f66d316797fc819b5f1d186d77f18ba97b4ff | https://github.com/pylast/pylast/blob/a52f66d316797fc819b5f1d186d77f18ba97b4ff/src/pylast/__init__.py#L2437-L2442 | train | 34,760 |
pylast/pylast | src/pylast/__init__.py | User.get_unixtime_registered | def get_unixtime_registered(self):
"""Returns the user's registration date as a UNIX timestamp."""
doc = self._request(self.ws_prefix + ".getInfo", True)
return int(doc.getElementsByTagName("registered")[0].getAttribute("unixtime")) | python | def get_unixtime_registered(self):
"""Returns the user's registration date as a UNIX timestamp."""
doc = self._request(self.ws_prefix + ".getInfo", True)
return int(doc.getElementsByTagName("registered")[0].getAttribute("unixtime")) | [
"def",
"get_unixtime_registered",
"(",
"self",
")",
":",
"doc",
"=",
"self",
".",
"_request",
"(",
"self",
".",
"ws_prefix",
"+",
"\".getInfo\"",
",",
"True",
")",
"return",
"int",
"(",
"doc",
".",
"getElementsByTagName",
"(",
"\"registered\"",
")",
"[",
"... | Returns the user's registration date as a UNIX timestamp. | [
"Returns",
"the",
"user",
"s",
"registration",
"date",
"as",
"a",
"UNIX",
"timestamp",
"."
] | a52f66d316797fc819b5f1d186d77f18ba97b4ff | https://github.com/pylast/pylast/blob/a52f66d316797fc819b5f1d186d77f18ba97b4ff/src/pylast/__init__.py#L2444-L2449 | train | 34,761 |
pylast/pylast | src/pylast/__init__.py | User.get_tagged_albums | def get_tagged_albums(self, tag, limit=None, cacheable=True):
"""Returns the albums tagged by a user."""
params = self._get_params()
params["tag"] = tag
params["taggingtype"] = "album"
if limit:
params["limit"] = limit
doc = self._request(self.ws_prefix + ".getpersonaltags", cacheable, params)
return _extract_albums(doc, self.network) | python | def get_tagged_albums(self, tag, limit=None, cacheable=True):
"""Returns the albums tagged by a user."""
params = self._get_params()
params["tag"] = tag
params["taggingtype"] = "album"
if limit:
params["limit"] = limit
doc = self._request(self.ws_prefix + ".getpersonaltags", cacheable, params)
return _extract_albums(doc, self.network) | [
"def",
"get_tagged_albums",
"(",
"self",
",",
"tag",
",",
"limit",
"=",
"None",
",",
"cacheable",
"=",
"True",
")",
":",
"params",
"=",
"self",
".",
"_get_params",
"(",
")",
"params",
"[",
"\"tag\"",
"]",
"=",
"tag",
"params",
"[",
"\"taggingtype\"",
"... | Returns the albums tagged by a user. | [
"Returns",
"the",
"albums",
"tagged",
"by",
"a",
"user",
"."
] | a52f66d316797fc819b5f1d186d77f18ba97b4ff | https://github.com/pylast/pylast/blob/a52f66d316797fc819b5f1d186d77f18ba97b4ff/src/pylast/__init__.py#L2451-L2460 | train | 34,762 |
pylast/pylast | src/pylast/__init__.py | User.get_tagged_artists | def get_tagged_artists(self, tag, limit=None):
"""Returns the artists tagged by a user."""
params = self._get_params()
params["tag"] = tag
params["taggingtype"] = "artist"
if limit:
params["limit"] = limit
doc = self._request(self.ws_prefix + ".getpersonaltags", True, params)
return _extract_artists(doc, self.network) | python | def get_tagged_artists(self, tag, limit=None):
"""Returns the artists tagged by a user."""
params = self._get_params()
params["tag"] = tag
params["taggingtype"] = "artist"
if limit:
params["limit"] = limit
doc = self._request(self.ws_prefix + ".getpersonaltags", True, params)
return _extract_artists(doc, self.network) | [
"def",
"get_tagged_artists",
"(",
"self",
",",
"tag",
",",
"limit",
"=",
"None",
")",
":",
"params",
"=",
"self",
".",
"_get_params",
"(",
")",
"params",
"[",
"\"tag\"",
"]",
"=",
"tag",
"params",
"[",
"\"taggingtype\"",
"]",
"=",
"\"artist\"",
"if",
"... | Returns the artists tagged by a user. | [
"Returns",
"the",
"artists",
"tagged",
"by",
"a",
"user",
"."
] | a52f66d316797fc819b5f1d186d77f18ba97b4ff | https://github.com/pylast/pylast/blob/a52f66d316797fc819b5f1d186d77f18ba97b4ff/src/pylast/__init__.py#L2462-L2471 | train | 34,763 |
pylast/pylast | src/pylast/__init__.py | User.get_tagged_tracks | def get_tagged_tracks(self, tag, limit=None, cacheable=True):
"""Returns the tracks tagged by a user."""
params = self._get_params()
params["tag"] = tag
params["taggingtype"] = "track"
if limit:
params["limit"] = limit
doc = self._request(self.ws_prefix + ".getpersonaltags", cacheable, params)
return _extract_tracks(doc, self.network) | python | def get_tagged_tracks(self, tag, limit=None, cacheable=True):
"""Returns the tracks tagged by a user."""
params = self._get_params()
params["tag"] = tag
params["taggingtype"] = "track"
if limit:
params["limit"] = limit
doc = self._request(self.ws_prefix + ".getpersonaltags", cacheable, params)
return _extract_tracks(doc, self.network) | [
"def",
"get_tagged_tracks",
"(",
"self",
",",
"tag",
",",
"limit",
"=",
"None",
",",
"cacheable",
"=",
"True",
")",
":",
"params",
"=",
"self",
".",
"_get_params",
"(",
")",
"params",
"[",
"\"tag\"",
"]",
"=",
"tag",
"params",
"[",
"\"taggingtype\"",
"... | Returns the tracks tagged by a user. | [
"Returns",
"the",
"tracks",
"tagged",
"by",
"a",
"user",
"."
] | a52f66d316797fc819b5f1d186d77f18ba97b4ff | https://github.com/pylast/pylast/blob/a52f66d316797fc819b5f1d186d77f18ba97b4ff/src/pylast/__init__.py#L2473-L2482 | train | 34,764 |
pylast/pylast | src/pylast/__init__.py | User.get_track_scrobbles | def get_track_scrobbles(self, artist, track, cacheable=False):
"""
Get a list of this user's scrobbles of this artist's track,
including scrobble time.
"""
params = self._get_params()
params["artist"] = artist
params["track"] = track
seq = []
for track in _collect_nodes(
None, self, self.ws_prefix + ".getTrackScrobbles", cacheable, params
):
title = _extract(track, "name")
artist = _extract(track, "artist")
date = _extract(track, "date")
album = _extract(track, "album")
timestamp = track.getElementsByTagName("date")[0].getAttribute("uts")
seq.append(
PlayedTrack(Track(artist, title, self.network), album, date, timestamp)
)
return seq | python | def get_track_scrobbles(self, artist, track, cacheable=False):
"""
Get a list of this user's scrobbles of this artist's track,
including scrobble time.
"""
params = self._get_params()
params["artist"] = artist
params["track"] = track
seq = []
for track in _collect_nodes(
None, self, self.ws_prefix + ".getTrackScrobbles", cacheable, params
):
title = _extract(track, "name")
artist = _extract(track, "artist")
date = _extract(track, "date")
album = _extract(track, "album")
timestamp = track.getElementsByTagName("date")[0].getAttribute("uts")
seq.append(
PlayedTrack(Track(artist, title, self.network), album, date, timestamp)
)
return seq | [
"def",
"get_track_scrobbles",
"(",
"self",
",",
"artist",
",",
"track",
",",
"cacheable",
"=",
"False",
")",
":",
"params",
"=",
"self",
".",
"_get_params",
"(",
")",
"params",
"[",
"\"artist\"",
"]",
"=",
"artist",
"params",
"[",
"\"track\"",
"]",
"=",
... | Get a list of this user's scrobbles of this artist's track,
including scrobble time. | [
"Get",
"a",
"list",
"of",
"this",
"user",
"s",
"scrobbles",
"of",
"this",
"artist",
"s",
"track",
"including",
"scrobble",
"time",
"."
] | a52f66d316797fc819b5f1d186d77f18ba97b4ff | https://github.com/pylast/pylast/blob/a52f66d316797fc819b5f1d186d77f18ba97b4ff/src/pylast/__init__.py#L2566-L2590 | train | 34,765 |
pylast/pylast | src/pylast/__init__.py | _Search.get_total_result_count | def get_total_result_count(self):
"""Returns the total count of all the results."""
doc = self._request(self._ws_prefix + ".search", True)
return _extract(doc, "totalResults") | python | def get_total_result_count(self):
"""Returns the total count of all the results."""
doc = self._request(self._ws_prefix + ".search", True)
return _extract(doc, "totalResults") | [
"def",
"get_total_result_count",
"(",
"self",
")",
":",
"doc",
"=",
"self",
".",
"_request",
"(",
"self",
".",
"_ws_prefix",
"+",
"\".search\"",
",",
"True",
")",
"return",
"_extract",
"(",
"doc",
",",
"\"totalResults\"",
")"
] | Returns the total count of all the results. | [
"Returns",
"the",
"total",
"count",
"of",
"all",
"the",
"results",
"."
] | a52f66d316797fc819b5f1d186d77f18ba97b4ff | https://github.com/pylast/pylast/blob/a52f66d316797fc819b5f1d186d77f18ba97b4ff/src/pylast/__init__.py#L2664-L2669 | train | 34,766 |
pylast/pylast | src/pylast/__init__.py | _Search._retrieve_page | def _retrieve_page(self, page_index):
"""Returns the node of matches to be processed"""
params = self._get_params()
params["page"] = str(page_index)
doc = self._request(self._ws_prefix + ".search", True, params)
return doc.getElementsByTagName(self._ws_prefix + "matches")[0] | python | def _retrieve_page(self, page_index):
"""Returns the node of matches to be processed"""
params = self._get_params()
params["page"] = str(page_index)
doc = self._request(self._ws_prefix + ".search", True, params)
return doc.getElementsByTagName(self._ws_prefix + "matches")[0] | [
"def",
"_retrieve_page",
"(",
"self",
",",
"page_index",
")",
":",
"params",
"=",
"self",
".",
"_get_params",
"(",
")",
"params",
"[",
"\"page\"",
"]",
"=",
"str",
"(",
"page_index",
")",
"doc",
"=",
"self",
".",
"_request",
"(",
"self",
".",
"_ws_pref... | Returns the node of matches to be processed | [
"Returns",
"the",
"node",
"of",
"matches",
"to",
"be",
"processed"
] | a52f66d316797fc819b5f1d186d77f18ba97b4ff | https://github.com/pylast/pylast/blob/a52f66d316797fc819b5f1d186d77f18ba97b4ff/src/pylast/__init__.py#L2671-L2678 | train | 34,767 |
pylast/pylast | src/pylast/__init__.py | AlbumSearch.get_next_page | def get_next_page(self):
"""Returns the next page of results as a sequence of Album objects."""
master_node = self._retrieve_next_page()
seq = []
for node in master_node.getElementsByTagName("album"):
seq.append(
Album(
_extract(node, "artist"),
_extract(node, "name"),
self.network,
info={"image": _extract_all(node, "image")},
)
)
return seq | python | def get_next_page(self):
"""Returns the next page of results as a sequence of Album objects."""
master_node = self._retrieve_next_page()
seq = []
for node in master_node.getElementsByTagName("album"):
seq.append(
Album(
_extract(node, "artist"),
_extract(node, "name"),
self.network,
info={"image": _extract_all(node, "image")},
)
)
return seq | [
"def",
"get_next_page",
"(",
"self",
")",
":",
"master_node",
"=",
"self",
".",
"_retrieve_next_page",
"(",
")",
"seq",
"=",
"[",
"]",
"for",
"node",
"in",
"master_node",
".",
"getElementsByTagName",
"(",
"\"album\"",
")",
":",
"seq",
".",
"append",
"(",
... | Returns the next page of results as a sequence of Album objects. | [
"Returns",
"the",
"next",
"page",
"of",
"results",
"as",
"a",
"sequence",
"of",
"Album",
"objects",
"."
] | a52f66d316797fc819b5f1d186d77f18ba97b4ff | https://github.com/pylast/pylast/blob/a52f66d316797fc819b5f1d186d77f18ba97b4ff/src/pylast/__init__.py#L2692-L2708 | train | 34,768 |
pylast/pylast | src/pylast/__init__.py | ArtistSearch.get_next_page | def get_next_page(self):
"""Returns the next page of results as a sequence of Artist objects."""
master_node = self._retrieve_next_page()
seq = []
for node in master_node.getElementsByTagName("artist"):
artist = Artist(
_extract(node, "name"),
self.network,
info={"image": _extract_all(node, "image")},
)
artist.listener_count = _number(_extract(node, "listeners"))
seq.append(artist)
return seq | python | def get_next_page(self):
"""Returns the next page of results as a sequence of Artist objects."""
master_node = self._retrieve_next_page()
seq = []
for node in master_node.getElementsByTagName("artist"):
artist = Artist(
_extract(node, "name"),
self.network,
info={"image": _extract_all(node, "image")},
)
artist.listener_count = _number(_extract(node, "listeners"))
seq.append(artist)
return seq | [
"def",
"get_next_page",
"(",
"self",
")",
":",
"master_node",
"=",
"self",
".",
"_retrieve_next_page",
"(",
")",
"seq",
"=",
"[",
"]",
"for",
"node",
"in",
"master_node",
".",
"getElementsByTagName",
"(",
"\"artist\"",
")",
":",
"artist",
"=",
"Artist",
"(... | Returns the next page of results as a sequence of Artist objects. | [
"Returns",
"the",
"next",
"page",
"of",
"results",
"as",
"a",
"sequence",
"of",
"Artist",
"objects",
"."
] | a52f66d316797fc819b5f1d186d77f18ba97b4ff | https://github.com/pylast/pylast/blob/a52f66d316797fc819b5f1d186d77f18ba97b4ff/src/pylast/__init__.py#L2717-L2732 | train | 34,769 |
pylast/pylast | src/pylast/__init__.py | TrackSearch.get_next_page | def get_next_page(self):
"""Returns the next page of results as a sequence of Track objects."""
master_node = self._retrieve_next_page()
seq = []
for node in master_node.getElementsByTagName("track"):
track = Track(
_extract(node, "artist"),
_extract(node, "name"),
self.network,
info={"image": _extract_all(node, "image")},
)
track.listener_count = _number(_extract(node, "listeners"))
seq.append(track)
return seq | python | def get_next_page(self):
"""Returns the next page of results as a sequence of Track objects."""
master_node = self._retrieve_next_page()
seq = []
for node in master_node.getElementsByTagName("track"):
track = Track(
_extract(node, "artist"),
_extract(node, "name"),
self.network,
info={"image": _extract_all(node, "image")},
)
track.listener_count = _number(_extract(node, "listeners"))
seq.append(track)
return seq | [
"def",
"get_next_page",
"(",
"self",
")",
":",
"master_node",
"=",
"self",
".",
"_retrieve_next_page",
"(",
")",
"seq",
"=",
"[",
"]",
"for",
"node",
"in",
"master_node",
".",
"getElementsByTagName",
"(",
"\"track\"",
")",
":",
"track",
"=",
"Track",
"(",
... | Returns the next page of results as a sequence of Track objects. | [
"Returns",
"the",
"next",
"page",
"of",
"results",
"as",
"a",
"sequence",
"of",
"Track",
"objects",
"."
] | a52f66d316797fc819b5f1d186d77f18ba97b4ff | https://github.com/pylast/pylast/blob/a52f66d316797fc819b5f1d186d77f18ba97b4ff/src/pylast/__init__.py#L2747-L2763 | train | 34,770 |
lovesegfault/beautysh | beautysh/beautysh.py | Beautify.write_file | def write_file(self, fp, data):
"""Write output to a file."""
with open(fp, 'w') as f:
f.write(data) | python | def write_file(self, fp, data):
"""Write output to a file."""
with open(fp, 'w') as f:
f.write(data) | [
"def",
"write_file",
"(",
"self",
",",
"fp",
",",
"data",
")",
":",
"with",
"open",
"(",
"fp",
",",
"'w'",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"data",
")"
] | Write output to a file. | [
"Write",
"output",
"to",
"a",
"file",
"."
] | c6a622dd1acb71c041aa38bbdaa1fe4ed61d9f85 | https://github.com/lovesegfault/beautysh/blob/c6a622dd1acb71c041aa38bbdaa1fe4ed61d9f85/beautysh/beautysh.py#L47-L50 | train | 34,771 |
lovesegfault/beautysh | beautysh/beautysh.py | Beautify.detect_function_style | def detect_function_style(self, test_record):
"""Returns the index for the function declaration style detected in the given string
or None if no function declarations are detected."""
index = 0
# IMPORTANT: apply regex sequentially and stop on the first match:
for regex in FUNCTION_STYLE_REGEX:
if re.search(regex, test_record):
return index
index+=1
return None | python | def detect_function_style(self, test_record):
"""Returns the index for the function declaration style detected in the given string
or None if no function declarations are detected."""
index = 0
# IMPORTANT: apply regex sequentially and stop on the first match:
for regex in FUNCTION_STYLE_REGEX:
if re.search(regex, test_record):
return index
index+=1
return None | [
"def",
"detect_function_style",
"(",
"self",
",",
"test_record",
")",
":",
"index",
"=",
"0",
"# IMPORTANT: apply regex sequentially and stop on the first match:",
"for",
"regex",
"in",
"FUNCTION_STYLE_REGEX",
":",
"if",
"re",
".",
"search",
"(",
"regex",
",",
"test_r... | Returns the index for the function declaration style detected in the given string
or None if no function declarations are detected. | [
"Returns",
"the",
"index",
"for",
"the",
"function",
"declaration",
"style",
"detected",
"in",
"the",
"given",
"string",
"or",
"None",
"if",
"no",
"function",
"declarations",
"are",
"detected",
"."
] | c6a622dd1acb71c041aa38bbdaa1fe4ed61d9f85 | https://github.com/lovesegfault/beautysh/blob/c6a622dd1acb71c041aa38bbdaa1fe4ed61d9f85/beautysh/beautysh.py#L52-L61 | train | 34,772 |
lovesegfault/beautysh | beautysh/beautysh.py | Beautify.change_function_style | def change_function_style(self, stripped_record, func_decl_style):
"""Converts a function definition syntax from the 'func_decl_style' to the one that has been
set in self.apply_function_style and returns the string with the converted syntax."""
if func_decl_style is None:
return stripped_record
if self.apply_function_style is None:
# user does not want to enforce any specific function style
return stripped_record
regex = FUNCTION_STYLE_REGEX[func_decl_style]
replacement = FUNCTION_STYLE_REPLACEMENT[self.apply_function_style]
changed_record = re.sub(regex, replacement, stripped_record)
return changed_record.strip() | python | def change_function_style(self, stripped_record, func_decl_style):
"""Converts a function definition syntax from the 'func_decl_style' to the one that has been
set in self.apply_function_style and returns the string with the converted syntax."""
if func_decl_style is None:
return stripped_record
if self.apply_function_style is None:
# user does not want to enforce any specific function style
return stripped_record
regex = FUNCTION_STYLE_REGEX[func_decl_style]
replacement = FUNCTION_STYLE_REPLACEMENT[self.apply_function_style]
changed_record = re.sub(regex, replacement, stripped_record)
return changed_record.strip() | [
"def",
"change_function_style",
"(",
"self",
",",
"stripped_record",
",",
"func_decl_style",
")",
":",
"if",
"func_decl_style",
"is",
"None",
":",
"return",
"stripped_record",
"if",
"self",
".",
"apply_function_style",
"is",
"None",
":",
"# user does not want to enfor... | Converts a function definition syntax from the 'func_decl_style' to the one that has been
set in self.apply_function_style and returns the string with the converted syntax. | [
"Converts",
"a",
"function",
"definition",
"syntax",
"from",
"the",
"func_decl_style",
"to",
"the",
"one",
"that",
"has",
"been",
"set",
"in",
"self",
".",
"apply_function_style",
"and",
"returns",
"the",
"string",
"with",
"the",
"converted",
"syntax",
"."
] | c6a622dd1acb71c041aa38bbdaa1fe4ed61d9f85 | https://github.com/lovesegfault/beautysh/blob/c6a622dd1acb71c041aa38bbdaa1fe4ed61d9f85/beautysh/beautysh.py#L63-L74 | train | 34,773 |
lovesegfault/beautysh | beautysh/beautysh.py | Beautify.beautify_file | def beautify_file(self, path):
"""Beautify bash script file."""
error = False
if(path == '-'):
data = sys.stdin.read()
result, error = self.beautify_string(data, '(stdin)')
sys.stdout.write(result)
else: # named file
data = self.read_file(path)
result, error = self.beautify_string(data, path)
if(data != result):
if(self.check_only):
if not error:
# we want to return 0 (success) only if the given file is already
# well formatted:
error = (result != data)
else:
if(self.backup):
self.write_file(path+'.bak', data)
self.write_file(path, result)
return error | python | def beautify_file(self, path):
"""Beautify bash script file."""
error = False
if(path == '-'):
data = sys.stdin.read()
result, error = self.beautify_string(data, '(stdin)')
sys.stdout.write(result)
else: # named file
data = self.read_file(path)
result, error = self.beautify_string(data, path)
if(data != result):
if(self.check_only):
if not error:
# we want to return 0 (success) only if the given file is already
# well formatted:
error = (result != data)
else:
if(self.backup):
self.write_file(path+'.bak', data)
self.write_file(path, result)
return error | [
"def",
"beautify_file",
"(",
"self",
",",
"path",
")",
":",
"error",
"=",
"False",
"if",
"(",
"path",
"==",
"'-'",
")",
":",
"data",
"=",
"sys",
".",
"stdin",
".",
"read",
"(",
")",
"result",
",",
"error",
"=",
"self",
".",
"beautify_string",
"(",
... | Beautify bash script file. | [
"Beautify",
"bash",
"script",
"file",
"."
] | c6a622dd1acb71c041aa38bbdaa1fe4ed61d9f85 | https://github.com/lovesegfault/beautysh/blob/c6a622dd1acb71c041aa38bbdaa1fe4ed61d9f85/beautysh/beautysh.py#L264-L284 | train | 34,774 |
lovesegfault/beautysh | beautysh/beautysh.py | Beautify.main | def main(self):
"""Main beautifying function."""
error = False
parser = argparse.ArgumentParser(
description="A Bash beautifier for the masses, version {}".format(self.get_version()), add_help=False)
parser.add_argument('--indent-size', '-i', nargs=1, type=int, default=4,
help="Sets the number of spaces to be used in "
"indentation.")
parser.add_argument('--files', '-f', nargs='*',
help="Files to be beautified. This is mandatory. "
"If - is provided as filename, then beautysh reads "
"from stdin and writes on stdout.")
parser.add_argument('--backup', '-b', action='store_true',
help="Beautysh will create a backup file in the "
"same path as the original.")
parser.add_argument('--check', '-c', action='store_true',
help="Beautysh will just check the files without doing "
"any in-place beautify.")
parser.add_argument('--tab', '-t', action='store_true',
help="Sets indentation to tabs instead of spaces.")
parser.add_argument('--force-function-style', '-s', nargs=1,
help="Force a specific Bash function formatting. See below for more info.")
parser.add_argument('--version', '-v', action='store_true',
help="Prints the version and exits.")
parser.add_argument('--help', '-h', action='store_true',
help="Print this help message.")
args = parser.parse_args()
if (len(sys.argv) < 2) or args.help:
self.print_help(parser)
exit()
if args.version:
sys.stdout.write("%s\n" % self.get_version())
exit()
if(type(args.indent_size) is list):
args.indent_size = args.indent_size[0]
if not args.files:
sys.stdout.write("Please provide at least one input file\n")
exit()
self.tab_size = args.indent_size
self.backup = args.backup
self.check_only = args.check
if (args.tab):
self.tab_size = 1
self.tab_str = '\t'
if (type(args.force_function_style) is list):
provided_style = self.parse_function_style(args.force_function_style[0])
if provided_style is None:
sys.stdout.write("Invalid value for the function style. See --help for details.\n")
exit()
self.apply_function_style = provided_style
for path in args.files:
error |= self.beautify_file(path)
sys.exit((0, 1)[error]) | python | def main(self):
"""Main beautifying function."""
error = False
parser = argparse.ArgumentParser(
description="A Bash beautifier for the masses, version {}".format(self.get_version()), add_help=False)
parser.add_argument('--indent-size', '-i', nargs=1, type=int, default=4,
help="Sets the number of spaces to be used in "
"indentation.")
parser.add_argument('--files', '-f', nargs='*',
help="Files to be beautified. This is mandatory. "
"If - is provided as filename, then beautysh reads "
"from stdin and writes on stdout.")
parser.add_argument('--backup', '-b', action='store_true',
help="Beautysh will create a backup file in the "
"same path as the original.")
parser.add_argument('--check', '-c', action='store_true',
help="Beautysh will just check the files without doing "
"any in-place beautify.")
parser.add_argument('--tab', '-t', action='store_true',
help="Sets indentation to tabs instead of spaces.")
parser.add_argument('--force-function-style', '-s', nargs=1,
help="Force a specific Bash function formatting. See below for more info.")
parser.add_argument('--version', '-v', action='store_true',
help="Prints the version and exits.")
parser.add_argument('--help', '-h', action='store_true',
help="Print this help message.")
args = parser.parse_args()
if (len(sys.argv) < 2) or args.help:
self.print_help(parser)
exit()
if args.version:
sys.stdout.write("%s\n" % self.get_version())
exit()
if(type(args.indent_size) is list):
args.indent_size = args.indent_size[0]
if not args.files:
sys.stdout.write("Please provide at least one input file\n")
exit()
self.tab_size = args.indent_size
self.backup = args.backup
self.check_only = args.check
if (args.tab):
self.tab_size = 1
self.tab_str = '\t'
if (type(args.force_function_style) is list):
provided_style = self.parse_function_style(args.force_function_style[0])
if provided_style is None:
sys.stdout.write("Invalid value for the function style. See --help for details.\n")
exit()
self.apply_function_style = provided_style
for path in args.files:
error |= self.beautify_file(path)
sys.exit((0, 1)[error]) | [
"def",
"main",
"(",
"self",
")",
":",
"error",
"=",
"False",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"\"A Bash beautifier for the masses, version {}\"",
".",
"format",
"(",
"self",
".",
"get_version",
"(",
")",
")",
",",
"add... | Main beautifying function. | [
"Main",
"beautifying",
"function",
"."
] | c6a622dd1acb71c041aa38bbdaa1fe4ed61d9f85 | https://github.com/lovesegfault/beautysh/blob/c6a622dd1acb71c041aa38bbdaa1fe4ed61d9f85/beautysh/beautysh.py#L310-L362 | train | 34,775 |
genomoncology/related | src/related/_init_fields.py | init_default | def init_default(required, default, optional_default):
"""
Returns optional default if field is not required and
default was not provided.
:param bool required: whether the field is required in a given model.
:param default: default provided by creator of field.
:param optional_default: default for the data type if none provided.
:return: default or optional default based on inputs
"""
if not required and default == NOTHING:
default = optional_default
return default | python | def init_default(required, default, optional_default):
"""
Returns optional default if field is not required and
default was not provided.
:param bool required: whether the field is required in a given model.
:param default: default provided by creator of field.
:param optional_default: default for the data type if none provided.
:return: default or optional default based on inputs
"""
if not required and default == NOTHING:
default = optional_default
return default | [
"def",
"init_default",
"(",
"required",
",",
"default",
",",
"optional_default",
")",
":",
"if",
"not",
"required",
"and",
"default",
"==",
"NOTHING",
":",
"default",
"=",
"optional_default",
"return",
"default"
] | Returns optional default if field is not required and
default was not provided.
:param bool required: whether the field is required in a given model.
:param default: default provided by creator of field.
:param optional_default: default for the data type if none provided.
:return: default or optional default based on inputs | [
"Returns",
"optional",
"default",
"if",
"field",
"is",
"not",
"required",
"and",
"default",
"was",
"not",
"provided",
"."
] | be47c0081e60fc60afcde3a25f00ebcad5d18510 | https://github.com/genomoncology/related/blob/be47c0081e60fc60afcde3a25f00ebcad5d18510/src/related/_init_fields.py#L5-L18 | train | 34,776 |
genomoncology/related | src/related/converters.py | to_child_field | def to_child_field(cls):
"""
Returns an callable instance that will convert a value to a Child object.
:param cls: Valid class type of the Child.
:return: instance of ChildConverter.
"""
class ChildConverter(object):
def __init__(self, cls):
self._cls = cls
@property
def cls(self):
return resolve_class(self._cls)
def __call__(self, value):
try:
# Issue #33: if value is the class and callable, then invoke
if value == self._cls and callable(value):
value = value()
return to_model(self.cls, value)
except ValueError as e:
error_msg = CHILD_ERROR_MSG.format(value, self.cls, str(e))
raise ValueError(error_msg)
return ChildConverter(cls) | python | def to_child_field(cls):
"""
Returns an callable instance that will convert a value to a Child object.
:param cls: Valid class type of the Child.
:return: instance of ChildConverter.
"""
class ChildConverter(object):
def __init__(self, cls):
self._cls = cls
@property
def cls(self):
return resolve_class(self._cls)
def __call__(self, value):
try:
# Issue #33: if value is the class and callable, then invoke
if value == self._cls and callable(value):
value = value()
return to_model(self.cls, value)
except ValueError as e:
error_msg = CHILD_ERROR_MSG.format(value, self.cls, str(e))
raise ValueError(error_msg)
return ChildConverter(cls) | [
"def",
"to_child_field",
"(",
"cls",
")",
":",
"class",
"ChildConverter",
"(",
"object",
")",
":",
"def",
"__init__",
"(",
"self",
",",
"cls",
")",
":",
"self",
".",
"_cls",
"=",
"cls",
"@",
"property",
"def",
"cls",
"(",
"self",
")",
":",
"return",
... | Returns an callable instance that will convert a value to a Child object.
:param cls: Valid class type of the Child.
:return: instance of ChildConverter. | [
"Returns",
"an",
"callable",
"instance",
"that",
"will",
"convert",
"a",
"value",
"to",
"a",
"Child",
"object",
"."
] | be47c0081e60fc60afcde3a25f00ebcad5d18510 | https://github.com/genomoncology/related/blob/be47c0081e60fc60afcde3a25f00ebcad5d18510/src/related/converters.py#L17-L45 | train | 34,777 |
genomoncology/related | src/related/converters.py | to_mapping_field | def to_mapping_field(cls, key): # pragma: no mccabe
"""
Returns a callable instance that will convert a value to a Mapping.
:param cls: Valid class type of the items in the Sequence.
:param key: Attribute name of the key value in each item of cls instance.
:return: instance of the MappingConverter.
"""
class MappingConverter(object):
def __init__(self, cls, key):
self._cls = cls
self.key = key
@property
def cls(self):
return resolve_class(self._cls)
def __call__(self, values):
kwargs = OrderedDict()
if isinstance(values, TypedMapping):
return values
if not isinstance(values, (type({}), type(None))):
raise TypeError("Invalid type : {}".format(type(values)))
if values:
for key_value, item in values.items():
if isinstance(item, dict):
item[self.key] = key_value
item = to_model(self.cls, item)
kwargs[key_value] = item
return TypedMapping(cls=self.cls, kwargs=kwargs, key=self.key)
return MappingConverter(cls, key) | python | def to_mapping_field(cls, key): # pragma: no mccabe
"""
Returns a callable instance that will convert a value to a Mapping.
:param cls: Valid class type of the items in the Sequence.
:param key: Attribute name of the key value in each item of cls instance.
:return: instance of the MappingConverter.
"""
class MappingConverter(object):
def __init__(self, cls, key):
self._cls = cls
self.key = key
@property
def cls(self):
return resolve_class(self._cls)
def __call__(self, values):
kwargs = OrderedDict()
if isinstance(values, TypedMapping):
return values
if not isinstance(values, (type({}), type(None))):
raise TypeError("Invalid type : {}".format(type(values)))
if values:
for key_value, item in values.items():
if isinstance(item, dict):
item[self.key] = key_value
item = to_model(self.cls, item)
kwargs[key_value] = item
return TypedMapping(cls=self.cls, kwargs=kwargs, key=self.key)
return MappingConverter(cls, key) | [
"def",
"to_mapping_field",
"(",
"cls",
",",
"key",
")",
":",
"# pragma: no mccabe",
"class",
"MappingConverter",
"(",
"object",
")",
":",
"def",
"__init__",
"(",
"self",
",",
"cls",
",",
"key",
")",
":",
"self",
".",
"_cls",
"=",
"cls",
"self",
".",
"k... | Returns a callable instance that will convert a value to a Mapping.
:param cls: Valid class type of the items in the Sequence.
:param key: Attribute name of the key value in each item of cls instance.
:return: instance of the MappingConverter. | [
"Returns",
"a",
"callable",
"instance",
"that",
"will",
"convert",
"a",
"value",
"to",
"a",
"Mapping",
"."
] | be47c0081e60fc60afcde3a25f00ebcad5d18510 | https://github.com/genomoncology/related/blob/be47c0081e60fc60afcde3a25f00ebcad5d18510/src/related/converters.py#L96-L132 | train | 34,778 |
genomoncology/related | src/related/converters.py | to_date_field | def to_date_field(formatter):
"""
Returns a callable instance that will convert a string to a Date.
:param formatter: String that represents data format for parsing.
:return: instance of the DateConverter.
"""
class DateConverter(object):
def __init__(self, formatter):
self.formatter = formatter
def __call__(self, value):
if isinstance(value, string_types):
value = datetime.strptime(value, self.formatter).date()
if isinstance(value, datetime):
value = value.date()
return value
return DateConverter(formatter) | python | def to_date_field(formatter):
"""
Returns a callable instance that will convert a string to a Date.
:param formatter: String that represents data format for parsing.
:return: instance of the DateConverter.
"""
class DateConverter(object):
def __init__(self, formatter):
self.formatter = formatter
def __call__(self, value):
if isinstance(value, string_types):
value = datetime.strptime(value, self.formatter).date()
if isinstance(value, datetime):
value = value.date()
return value
return DateConverter(formatter) | [
"def",
"to_date_field",
"(",
"formatter",
")",
":",
"class",
"DateConverter",
"(",
"object",
")",
":",
"def",
"__init__",
"(",
"self",
",",
"formatter",
")",
":",
"self",
".",
"formatter",
"=",
"formatter",
"def",
"__call__",
"(",
"self",
",",
"value",
"... | Returns a callable instance that will convert a string to a Date.
:param formatter: String that represents data format for parsing.
:return: instance of the DateConverter. | [
"Returns",
"a",
"callable",
"instance",
"that",
"will",
"convert",
"a",
"string",
"to",
"a",
"Date",
"."
] | be47c0081e60fc60afcde3a25f00ebcad5d18510 | https://github.com/genomoncology/related/blob/be47c0081e60fc60afcde3a25f00ebcad5d18510/src/related/converters.py#L191-L212 | train | 34,779 |
genomoncology/related | src/related/converters.py | to_datetime_field | def to_datetime_field(formatter):
"""
Returns a callable instance that will convert a string to a DateTime.
:param formatter: String that represents data format for parsing.
:return: instance of the DateTimeConverter.
"""
class DateTimeConverter(object):
def __init__(self, formatter):
self.formatter = formatter
def __call__(self, value):
if isinstance(value, string_types):
value = parser.parse(value)
return value
return DateTimeConverter(formatter) | python | def to_datetime_field(formatter):
"""
Returns a callable instance that will convert a string to a DateTime.
:param formatter: String that represents data format for parsing.
:return: instance of the DateTimeConverter.
"""
class DateTimeConverter(object):
def __init__(self, formatter):
self.formatter = formatter
def __call__(self, value):
if isinstance(value, string_types):
value = parser.parse(value)
return value
return DateTimeConverter(formatter) | [
"def",
"to_datetime_field",
"(",
"formatter",
")",
":",
"class",
"DateTimeConverter",
"(",
"object",
")",
":",
"def",
"__init__",
"(",
"self",
",",
"formatter",
")",
":",
"self",
".",
"formatter",
"=",
"formatter",
"def",
"__call__",
"(",
"self",
",",
"val... | Returns a callable instance that will convert a string to a DateTime.
:param formatter: String that represents data format for parsing.
:return: instance of the DateTimeConverter. | [
"Returns",
"a",
"callable",
"instance",
"that",
"will",
"convert",
"a",
"string",
"to",
"a",
"DateTime",
"."
] | be47c0081e60fc60afcde3a25f00ebcad5d18510 | https://github.com/genomoncology/related/blob/be47c0081e60fc60afcde3a25f00ebcad5d18510/src/related/converters.py#L215-L233 | train | 34,780 |
genomoncology/related | src/related/converters.py | to_time_field | def to_time_field(formatter):
"""
Returns a callable instance that will convert a string to a Time.
:param formatter: String that represents data format for parsing.
:return: instance of the TimeConverter.
"""
class TimeConverter(object):
def __init__(self, formatter):
self.formatter = formatter
def __call__(self, value):
if isinstance(value, string_types):
value = datetime.strptime(value, self.formatter).time()
return value
return TimeConverter(formatter) | python | def to_time_field(formatter):
"""
Returns a callable instance that will convert a string to a Time.
:param formatter: String that represents data format for parsing.
:return: instance of the TimeConverter.
"""
class TimeConverter(object):
def __init__(self, formatter):
self.formatter = formatter
def __call__(self, value):
if isinstance(value, string_types):
value = datetime.strptime(value, self.formatter).time()
return value
return TimeConverter(formatter) | [
"def",
"to_time_field",
"(",
"formatter",
")",
":",
"class",
"TimeConverter",
"(",
"object",
")",
":",
"def",
"__init__",
"(",
"self",
",",
"formatter",
")",
":",
"self",
".",
"formatter",
"=",
"formatter",
"def",
"__call__",
"(",
"self",
",",
"value",
"... | Returns a callable instance that will convert a string to a Time.
:param formatter: String that represents data format for parsing.
:return: instance of the TimeConverter. | [
"Returns",
"a",
"callable",
"instance",
"that",
"will",
"convert",
"a",
"string",
"to",
"a",
"Time",
"."
] | be47c0081e60fc60afcde3a25f00ebcad5d18510 | https://github.com/genomoncology/related/blob/be47c0081e60fc60afcde3a25f00ebcad5d18510/src/related/converters.py#L236-L254 | train | 34,781 |
genomoncology/related | src/related/functions.py | to_dict | def to_dict(obj, **kwargs):
"""
Convert an object into dictionary. Uses singledispatch to allow for
clean extensions for custom class types.
Reference: https://pypi.python.org/pypi/singledispatch
:param obj: object instance
:param kwargs: keyword arguments such as suppress_private_attr,
suppress_empty_values, dict_factory
:return: converted dictionary.
"""
# if is_related, then iterate attrs.
if is_model(obj.__class__):
return related_obj_to_dict(obj, **kwargs)
# else, return obj directly. register a custom to_dict if you need to!
# reference: https://pypi.python.org/pypi/singledispatch
else:
return obj | python | def to_dict(obj, **kwargs):
"""
Convert an object into dictionary. Uses singledispatch to allow for
clean extensions for custom class types.
Reference: https://pypi.python.org/pypi/singledispatch
:param obj: object instance
:param kwargs: keyword arguments such as suppress_private_attr,
suppress_empty_values, dict_factory
:return: converted dictionary.
"""
# if is_related, then iterate attrs.
if is_model(obj.__class__):
return related_obj_to_dict(obj, **kwargs)
# else, return obj directly. register a custom to_dict if you need to!
# reference: https://pypi.python.org/pypi/singledispatch
else:
return obj | [
"def",
"to_dict",
"(",
"obj",
",",
"*",
"*",
"kwargs",
")",
":",
"# if is_related, then iterate attrs.",
"if",
"is_model",
"(",
"obj",
".",
"__class__",
")",
":",
"return",
"related_obj_to_dict",
"(",
"obj",
",",
"*",
"*",
"kwargs",
")",
"# else, return obj di... | Convert an object into dictionary. Uses singledispatch to allow for
clean extensions for custom class types.
Reference: https://pypi.python.org/pypi/singledispatch
:param obj: object instance
:param kwargs: keyword arguments such as suppress_private_attr,
suppress_empty_values, dict_factory
:return: converted dictionary. | [
"Convert",
"an",
"object",
"into",
"dictionary",
".",
"Uses",
"singledispatch",
"to",
"allow",
"for",
"clean",
"extensions",
"for",
"custom",
"class",
"types",
"."
] | be47c0081e60fc60afcde3a25f00ebcad5d18510 | https://github.com/genomoncology/related/blob/be47c0081e60fc60afcde3a25f00ebcad5d18510/src/related/functions.py#L18-L38 | train | 34,782 |
genomoncology/related | src/related/functions.py | related_obj_to_dict | def related_obj_to_dict(obj, **kwargs):
""" Covert a known related object to a dictionary. """
# Explicitly discard formatter kwarg, should not be cascaded down.
kwargs.pop('formatter', None)
# If True, remove fields that start with an underscore (e.g. _secret)
suppress_private_attr = kwargs.get("suppress_private_attr", False)
# if True, don't store fields with None values into dictionary.
suppress_empty_values = kwargs.get("suppress_empty_values", False)
# get list of attrs fields
attrs = fields(obj.__class__)
# instantiate return dict, use OrderedDict type by default
return_dict = kwargs.get("dict_factory", OrderedDict)()
for a in attrs:
# skip if private attr and flag tells you to skip
if suppress_private_attr and a.name.startswith("_"):
continue
metadata = a.metadata or {}
# formatter is a related-specific `attrs` meta field
# see fields.DateField
formatter = metadata.get('formatter')
# get value and call to_dict on it, passing the kwargs/formatter
value = getattr(obj, a.name)
value = to_dict(value, formatter=formatter, **kwargs)
# check flag, skip None values
if suppress_empty_values and value is None:
continue
# field name can be overridden by the metadata field
key_name = a.metadata.get('key') or a.name
# store converted / formatted value into return dictionary
return_dict[key_name] = value
return return_dict | python | def related_obj_to_dict(obj, **kwargs):
""" Covert a known related object to a dictionary. """
# Explicitly discard formatter kwarg, should not be cascaded down.
kwargs.pop('formatter', None)
# If True, remove fields that start with an underscore (e.g. _secret)
suppress_private_attr = kwargs.get("suppress_private_attr", False)
# if True, don't store fields with None values into dictionary.
suppress_empty_values = kwargs.get("suppress_empty_values", False)
# get list of attrs fields
attrs = fields(obj.__class__)
# instantiate return dict, use OrderedDict type by default
return_dict = kwargs.get("dict_factory", OrderedDict)()
for a in attrs:
# skip if private attr and flag tells you to skip
if suppress_private_attr and a.name.startswith("_"):
continue
metadata = a.metadata or {}
# formatter is a related-specific `attrs` meta field
# see fields.DateField
formatter = metadata.get('formatter')
# get value and call to_dict on it, passing the kwargs/formatter
value = getattr(obj, a.name)
value = to_dict(value, formatter=formatter, **kwargs)
# check flag, skip None values
if suppress_empty_values and value is None:
continue
# field name can be overridden by the metadata field
key_name = a.metadata.get('key') or a.name
# store converted / formatted value into return dictionary
return_dict[key_name] = value
return return_dict | [
"def",
"related_obj_to_dict",
"(",
"obj",
",",
"*",
"*",
"kwargs",
")",
":",
"# Explicitly discard formatter kwarg, should not be cascaded down.",
"kwargs",
".",
"pop",
"(",
"'formatter'",
",",
"None",
")",
"# If True, remove fields that start with an underscore (e.g. _secret)"... | Covert a known related object to a dictionary. | [
"Covert",
"a",
"known",
"related",
"object",
"to",
"a",
"dictionary",
"."
] | be47c0081e60fc60afcde3a25f00ebcad5d18510 | https://github.com/genomoncology/related/blob/be47c0081e60fc60afcde3a25f00ebcad5d18510/src/related/functions.py#L41-L85 | train | 34,783 |
genomoncology/related | src/related/functions.py | convert_key_to_attr_names | def convert_key_to_attr_names(cls, original):
""" convert key names to their corresponding attribute names """
attrs = fields(cls)
updated = {}
keys_pulled = set()
for a in attrs:
key_name = a.metadata.get('key') or a.name
if key_name in original:
updated[a.name] = original.get(key_name)
keys_pulled.add(key_name)
if getattr(cls, '__related_strict__', False):
extra = set(original.keys()) - keys_pulled
if len(extra):
raise ValueError("Extra keys (strict mode): {}".format(extra))
return updated | python | def convert_key_to_attr_names(cls, original):
""" convert key names to their corresponding attribute names """
attrs = fields(cls)
updated = {}
keys_pulled = set()
for a in attrs:
key_name = a.metadata.get('key') or a.name
if key_name in original:
updated[a.name] = original.get(key_name)
keys_pulled.add(key_name)
if getattr(cls, '__related_strict__', False):
extra = set(original.keys()) - keys_pulled
if len(extra):
raise ValueError("Extra keys (strict mode): {}".format(extra))
return updated | [
"def",
"convert_key_to_attr_names",
"(",
"cls",
",",
"original",
")",
":",
"attrs",
"=",
"fields",
"(",
"cls",
")",
"updated",
"=",
"{",
"}",
"keys_pulled",
"=",
"set",
"(",
")",
"for",
"a",
"in",
"attrs",
":",
"key_name",
"=",
"a",
".",
"metadata",
... | convert key names to their corresponding attribute names | [
"convert",
"key",
"names",
"to",
"their",
"corresponding",
"attribute",
"names"
] | be47c0081e60fc60afcde3a25f00ebcad5d18510 | https://github.com/genomoncology/related/blob/be47c0081e60fc60afcde3a25f00ebcad5d18510/src/related/functions.py#L112-L129 | train | 34,784 |
genomoncology/related | src/related/functions.py | to_yaml | def to_yaml(obj, stream=None, dumper_cls=yaml.Dumper, default_flow_style=False,
**kwargs):
"""
Serialize a Python object into a YAML stream with OrderedDict and
default_flow_style defaulted to False.
If stream is None, return the produced string instead.
OrderedDict reference: http://stackoverflow.com/a/21912744
default_flow_style reference: http://stackoverflow.com/a/18210750
:param data: python object to be serialized
:param stream: to be serialized to
:param Dumper: base Dumper class to extend.
:param kwargs: arguments to pass to to_dict
:return: stream if provided, string if stream is None
"""
class OrderedDumper(dumper_cls):
pass
def dict_representer(dumper, data):
return dumper.represent_mapping(
yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG,
data.items())
OrderedDumper.add_representer(OrderedDict, dict_representer)
obj_dict = to_dict(obj, **kwargs)
return yaml.dump(obj_dict, stream, OrderedDumper,
default_flow_style=default_flow_style) | python | def to_yaml(obj, stream=None, dumper_cls=yaml.Dumper, default_flow_style=False,
**kwargs):
"""
Serialize a Python object into a YAML stream with OrderedDict and
default_flow_style defaulted to False.
If stream is None, return the produced string instead.
OrderedDict reference: http://stackoverflow.com/a/21912744
default_flow_style reference: http://stackoverflow.com/a/18210750
:param data: python object to be serialized
:param stream: to be serialized to
:param Dumper: base Dumper class to extend.
:param kwargs: arguments to pass to to_dict
:return: stream if provided, string if stream is None
"""
class OrderedDumper(dumper_cls):
pass
def dict_representer(dumper, data):
return dumper.represent_mapping(
yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG,
data.items())
OrderedDumper.add_representer(OrderedDict, dict_representer)
obj_dict = to_dict(obj, **kwargs)
return yaml.dump(obj_dict, stream, OrderedDumper,
default_flow_style=default_flow_style) | [
"def",
"to_yaml",
"(",
"obj",
",",
"stream",
"=",
"None",
",",
"dumper_cls",
"=",
"yaml",
".",
"Dumper",
",",
"default_flow_style",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"class",
"OrderedDumper",
"(",
"dumper_cls",
")",
":",
"pass",
"def",
"... | Serialize a Python object into a YAML stream with OrderedDict and
default_flow_style defaulted to False.
If stream is None, return the produced string instead.
OrderedDict reference: http://stackoverflow.com/a/21912744
default_flow_style reference: http://stackoverflow.com/a/18210750
:param data: python object to be serialized
:param stream: to be serialized to
:param Dumper: base Dumper class to extend.
:param kwargs: arguments to pass to to_dict
:return: stream if provided, string if stream is None | [
"Serialize",
"a",
"Python",
"object",
"into",
"a",
"YAML",
"stream",
"with",
"OrderedDict",
"and",
"default_flow_style",
"defaulted",
"to",
"False",
"."
] | be47c0081e60fc60afcde3a25f00ebcad5d18510 | https://github.com/genomoncology/related/blob/be47c0081e60fc60afcde3a25f00ebcad5d18510/src/related/functions.py#L144-L175 | train | 34,785 |
genomoncology/related | src/related/functions.py | from_yaml | def from_yaml(stream, cls=None, loader_cls=yaml.Loader,
object_pairs_hook=OrderedDict, **extras):
"""
Convert a YAML stream into a class via the OrderedLoader class.
"""
class OrderedLoader(loader_cls):
pass
def construct_mapping(loader, node):
loader.flatten_mapping(node)
return object_pairs_hook(loader.construct_pairs(node))
OrderedLoader.add_constructor(
yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG,
construct_mapping)
yaml_dict = yaml.load(stream, OrderedLoader) or {}
yaml_dict.update(extras)
return cls(**yaml_dict) if cls else yaml_dict | python | def from_yaml(stream, cls=None, loader_cls=yaml.Loader,
object_pairs_hook=OrderedDict, **extras):
"""
Convert a YAML stream into a class via the OrderedLoader class.
"""
class OrderedLoader(loader_cls):
pass
def construct_mapping(loader, node):
loader.flatten_mapping(node)
return object_pairs_hook(loader.construct_pairs(node))
OrderedLoader.add_constructor(
yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG,
construct_mapping)
yaml_dict = yaml.load(stream, OrderedLoader) or {}
yaml_dict.update(extras)
return cls(**yaml_dict) if cls else yaml_dict | [
"def",
"from_yaml",
"(",
"stream",
",",
"cls",
"=",
"None",
",",
"loader_cls",
"=",
"yaml",
".",
"Loader",
",",
"object_pairs_hook",
"=",
"OrderedDict",
",",
"*",
"*",
"extras",
")",
":",
"class",
"OrderedLoader",
"(",
"loader_cls",
")",
":",
"pass",
"de... | Convert a YAML stream into a class via the OrderedLoader class. | [
"Convert",
"a",
"YAML",
"stream",
"into",
"a",
"class",
"via",
"the",
"OrderedLoader",
"class",
"."
] | be47c0081e60fc60afcde3a25f00ebcad5d18510 | https://github.com/genomoncology/related/blob/be47c0081e60fc60afcde3a25f00ebcad5d18510/src/related/functions.py#L178-L197 | train | 34,786 |
genomoncology/related | src/related/functions.py | from_json | def from_json(stream, cls=None, object_pairs_hook=OrderedDict, **extras):
"""
Convert a JSON string or stream into specified class.
"""
stream = stream.read() if hasattr(stream, 'read') else stream
json_dict = json.loads(stream, object_pairs_hook=object_pairs_hook)
if extras:
json_dict.update(extras) # pragma: no cover
return to_model(cls, json_dict) if cls else json_dict | python | def from_json(stream, cls=None, object_pairs_hook=OrderedDict, **extras):
"""
Convert a JSON string or stream into specified class.
"""
stream = stream.read() if hasattr(stream, 'read') else stream
json_dict = json.loads(stream, object_pairs_hook=object_pairs_hook)
if extras:
json_dict.update(extras) # pragma: no cover
return to_model(cls, json_dict) if cls else json_dict | [
"def",
"from_json",
"(",
"stream",
",",
"cls",
"=",
"None",
",",
"object_pairs_hook",
"=",
"OrderedDict",
",",
"*",
"*",
"extras",
")",
":",
"stream",
"=",
"stream",
".",
"read",
"(",
")",
"if",
"hasattr",
"(",
"stream",
",",
"'read'",
")",
"else",
"... | Convert a JSON string or stream into specified class. | [
"Convert",
"a",
"JSON",
"string",
"or",
"stream",
"into",
"specified",
"class",
"."
] | be47c0081e60fc60afcde3a25f00ebcad5d18510 | https://github.com/genomoncology/related/blob/be47c0081e60fc60afcde3a25f00ebcad5d18510/src/related/functions.py#L212-L220 | train | 34,787 |
genomoncology/related | src/related/fields.py | BooleanField | def BooleanField(default=NOTHING, required=True, repr=True, cmp=True,
key=None):
"""
Create new bool field on a model.
:param default: any boolean value
:param bool required: whether or not the object is invalid if not provided.
:param bool repr: include this field should appear in object's repr.
:param bool cmp: include this field in generated comparison.
:param string key: override name of the value when converted to dict.
"""
default = _init_fields.init_default(required, default, None)
validator = _init_fields.init_validator(required, bool)
return attrib(default=default, validator=validator, repr=repr, cmp=cmp,
metadata=dict(key=key)) | python | def BooleanField(default=NOTHING, required=True, repr=True, cmp=True,
key=None):
"""
Create new bool field on a model.
:param default: any boolean value
:param bool required: whether or not the object is invalid if not provided.
:param bool repr: include this field should appear in object's repr.
:param bool cmp: include this field in generated comparison.
:param string key: override name of the value when converted to dict.
"""
default = _init_fields.init_default(required, default, None)
validator = _init_fields.init_validator(required, bool)
return attrib(default=default, validator=validator, repr=repr, cmp=cmp,
metadata=dict(key=key)) | [
"def",
"BooleanField",
"(",
"default",
"=",
"NOTHING",
",",
"required",
"=",
"True",
",",
"repr",
"=",
"True",
",",
"cmp",
"=",
"True",
",",
"key",
"=",
"None",
")",
":",
"default",
"=",
"_init_fields",
".",
"init_default",
"(",
"required",
",",
"defau... | Create new bool field on a model.
:param default: any boolean value
:param bool required: whether or not the object is invalid if not provided.
:param bool repr: include this field should appear in object's repr.
:param bool cmp: include this field in generated comparison.
:param string key: override name of the value when converted to dict. | [
"Create",
"new",
"bool",
"field",
"on",
"a",
"model",
"."
] | be47c0081e60fc60afcde3a25f00ebcad5d18510 | https://github.com/genomoncology/related/blob/be47c0081e60fc60afcde3a25f00ebcad5d18510/src/related/fields.py#L13-L27 | train | 34,788 |
genomoncology/related | src/related/fields.py | ChildField | def ChildField(cls, default=NOTHING, required=True, repr=True, cmp=True,
key=None):
"""
Create new child field on a model.
:param cls: class (or name) of the model to be related.
:param default: any object value of type cls
:param bool required: whether or not the object is invalid if not provided.
:param bool repr: include this field should appear in object's repr.
:param bool cmp: include this field in generated comparison.
:param string key: override name of the value when converted to dict.
"""
default = _init_fields.init_default(required, default, None)
converter = converters.to_child_field(cls)
validator = _init_fields.init_validator(
required, object if isinstance(cls, str) else cls
)
return attrib(default=default, converter=converter, validator=validator,
repr=repr, cmp=cmp, metadata=dict(key=key)) | python | def ChildField(cls, default=NOTHING, required=True, repr=True, cmp=True,
key=None):
"""
Create new child field on a model.
:param cls: class (or name) of the model to be related.
:param default: any object value of type cls
:param bool required: whether or not the object is invalid if not provided.
:param bool repr: include this field should appear in object's repr.
:param bool cmp: include this field in generated comparison.
:param string key: override name of the value when converted to dict.
"""
default = _init_fields.init_default(required, default, None)
converter = converters.to_child_field(cls)
validator = _init_fields.init_validator(
required, object if isinstance(cls, str) else cls
)
return attrib(default=default, converter=converter, validator=validator,
repr=repr, cmp=cmp, metadata=dict(key=key)) | [
"def",
"ChildField",
"(",
"cls",
",",
"default",
"=",
"NOTHING",
",",
"required",
"=",
"True",
",",
"repr",
"=",
"True",
",",
"cmp",
"=",
"True",
",",
"key",
"=",
"None",
")",
":",
"default",
"=",
"_init_fields",
".",
"init_default",
"(",
"required",
... | Create new child field on a model.
:param cls: class (or name) of the model to be related.
:param default: any object value of type cls
:param bool required: whether or not the object is invalid if not provided.
:param bool repr: include this field should appear in object's repr.
:param bool cmp: include this field in generated comparison.
:param string key: override name of the value when converted to dict. | [
"Create",
"new",
"child",
"field",
"on",
"a",
"model",
"."
] | be47c0081e60fc60afcde3a25f00ebcad5d18510 | https://github.com/genomoncology/related/blob/be47c0081e60fc60afcde3a25f00ebcad5d18510/src/related/fields.py#L30-L48 | train | 34,789 |
genomoncology/related | src/related/fields.py | DateField | def DateField(formatter=types.DEFAULT_DATE_FORMAT, default=NOTHING,
required=True, repr=True, cmp=True, key=None):
"""
Create new date field on a model.
:param formatter: date formatter string (default: "%Y-%m-%d")
:param default: any date or string that can be converted to a date value
:param bool required: whether or not the object is invalid if not provided.
:param bool repr: include this field should appear in object's repr.
:param bool cmp: include this field in generated comparison.
:param string key: override name of the value when converted to dict.
"""
default = _init_fields.init_default(required, default, None)
validator = _init_fields.init_validator(required, date)
converter = converters.to_date_field(formatter)
return attrib(default=default, converter=converter, validator=validator,
repr=repr, cmp=cmp,
metadata=dict(formatter=formatter, key=key)) | python | def DateField(formatter=types.DEFAULT_DATE_FORMAT, default=NOTHING,
required=True, repr=True, cmp=True, key=None):
"""
Create new date field on a model.
:param formatter: date formatter string (default: "%Y-%m-%d")
:param default: any date or string that can be converted to a date value
:param bool required: whether or not the object is invalid if not provided.
:param bool repr: include this field should appear in object's repr.
:param bool cmp: include this field in generated comparison.
:param string key: override name of the value when converted to dict.
"""
default = _init_fields.init_default(required, default, None)
validator = _init_fields.init_validator(required, date)
converter = converters.to_date_field(formatter)
return attrib(default=default, converter=converter, validator=validator,
repr=repr, cmp=cmp,
metadata=dict(formatter=formatter, key=key)) | [
"def",
"DateField",
"(",
"formatter",
"=",
"types",
".",
"DEFAULT_DATE_FORMAT",
",",
"default",
"=",
"NOTHING",
",",
"required",
"=",
"True",
",",
"repr",
"=",
"True",
",",
"cmp",
"=",
"True",
",",
"key",
"=",
"None",
")",
":",
"default",
"=",
"_init_f... | Create new date field on a model.
:param formatter: date formatter string (default: "%Y-%m-%d")
:param default: any date or string that can be converted to a date value
:param bool required: whether or not the object is invalid if not provided.
:param bool repr: include this field should appear in object's repr.
:param bool cmp: include this field in generated comparison.
:param string key: override name of the value when converted to dict. | [
"Create",
"new",
"date",
"field",
"on",
"a",
"model",
"."
] | be47c0081e60fc60afcde3a25f00ebcad5d18510 | https://github.com/genomoncology/related/blob/be47c0081e60fc60afcde3a25f00ebcad5d18510/src/related/fields.py#L51-L68 | train | 34,790 |
genomoncology/related | src/related/fields.py | DateTimeField | def DateTimeField(formatter=types.DEFAULT_DATETIME_FORMAT, default=NOTHING,
required=True, repr=True, cmp=True, key=None):
"""
Create new datetime field on a model.
:param formatter: datetime formatter string (default: "ISO_FORMAT")
:param default: any datetime or string that can be converted to a datetime
:param bool required: whether or not the object is invalid if not provided.
:param bool repr: include this field should appear in object's repr.
:param bool cmp: include this field in generated comparison.
:param string key: override name of the value when converted to dict.
"""
default = _init_fields.init_default(required, default, None)
validator = _init_fields.init_validator(required, datetime)
converter = converters.to_datetime_field(formatter)
return attrib(default=default, converter=converter, validator=validator,
repr=repr, cmp=cmp,
metadata=dict(formatter=formatter, key=key)) | python | def DateTimeField(formatter=types.DEFAULT_DATETIME_FORMAT, default=NOTHING,
required=True, repr=True, cmp=True, key=None):
"""
Create new datetime field on a model.
:param formatter: datetime formatter string (default: "ISO_FORMAT")
:param default: any datetime or string that can be converted to a datetime
:param bool required: whether or not the object is invalid if not provided.
:param bool repr: include this field should appear in object's repr.
:param bool cmp: include this field in generated comparison.
:param string key: override name of the value when converted to dict.
"""
default = _init_fields.init_default(required, default, None)
validator = _init_fields.init_validator(required, datetime)
converter = converters.to_datetime_field(formatter)
return attrib(default=default, converter=converter, validator=validator,
repr=repr, cmp=cmp,
metadata=dict(formatter=formatter, key=key)) | [
"def",
"DateTimeField",
"(",
"formatter",
"=",
"types",
".",
"DEFAULT_DATETIME_FORMAT",
",",
"default",
"=",
"NOTHING",
",",
"required",
"=",
"True",
",",
"repr",
"=",
"True",
",",
"cmp",
"=",
"True",
",",
"key",
"=",
"None",
")",
":",
"default",
"=",
... | Create new datetime field on a model.
:param formatter: datetime formatter string (default: "ISO_FORMAT")
:param default: any datetime or string that can be converted to a datetime
:param bool required: whether or not the object is invalid if not provided.
:param bool repr: include this field should appear in object's repr.
:param bool cmp: include this field in generated comparison.
:param string key: override name of the value when converted to dict. | [
"Create",
"new",
"datetime",
"field",
"on",
"a",
"model",
"."
] | be47c0081e60fc60afcde3a25f00ebcad5d18510 | https://github.com/genomoncology/related/blob/be47c0081e60fc60afcde3a25f00ebcad5d18510/src/related/fields.py#L71-L88 | train | 34,791 |
genomoncology/related | src/related/fields.py | TimeField | def TimeField(formatter=types.DEFAULT_TIME_FORMAT, default=NOTHING,
required=True, repr=True, cmp=True, key=None):
"""
Create new time field on a model.
:param formatter: time formatter string (default: "%H:%M:%S")
:param default: any time or string that can be converted to a time value
:param bool required: whether or not the object is invalid if not provided.
:param bool repr: include this field should appear in object's repr.
:param bool cmp: include this field in generated comparison.
:param string key: override name of the value when converted to dict.
"""
default = _init_fields.init_default(required, default, None)
validator = _init_fields.init_validator(required, time)
converter = converters.to_time_field(formatter)
return attrib(default=default, converter=converter, validator=validator,
repr=repr, cmp=cmp,
metadata=dict(formatter=formatter, key=key)) | python | def TimeField(formatter=types.DEFAULT_TIME_FORMAT, default=NOTHING,
required=True, repr=True, cmp=True, key=None):
"""
Create new time field on a model.
:param formatter: time formatter string (default: "%H:%M:%S")
:param default: any time or string that can be converted to a time value
:param bool required: whether or not the object is invalid if not provided.
:param bool repr: include this field should appear in object's repr.
:param bool cmp: include this field in generated comparison.
:param string key: override name of the value when converted to dict.
"""
default = _init_fields.init_default(required, default, None)
validator = _init_fields.init_validator(required, time)
converter = converters.to_time_field(formatter)
return attrib(default=default, converter=converter, validator=validator,
repr=repr, cmp=cmp,
metadata=dict(formatter=formatter, key=key)) | [
"def",
"TimeField",
"(",
"formatter",
"=",
"types",
".",
"DEFAULT_TIME_FORMAT",
",",
"default",
"=",
"NOTHING",
",",
"required",
"=",
"True",
",",
"repr",
"=",
"True",
",",
"cmp",
"=",
"True",
",",
"key",
"=",
"None",
")",
":",
"default",
"=",
"_init_f... | Create new time field on a model.
:param formatter: time formatter string (default: "%H:%M:%S")
:param default: any time or string that can be converted to a time value
:param bool required: whether or not the object is invalid if not provided.
:param bool repr: include this field should appear in object's repr.
:param bool cmp: include this field in generated comparison.
:param string key: override name of the value when converted to dict. | [
"Create",
"new",
"time",
"field",
"on",
"a",
"model",
"."
] | be47c0081e60fc60afcde3a25f00ebcad5d18510 | https://github.com/genomoncology/related/blob/be47c0081e60fc60afcde3a25f00ebcad5d18510/src/related/fields.py#L91-L108 | train | 34,792 |
genomoncology/related | src/related/fields.py | FloatField | def FloatField(default=NOTHING, required=True, repr=True, cmp=True,
key=None):
"""
Create new float field on a model.
:param default: any float value
:param bool required: whether or not the object is invalid if not provided.
:param bool repr: include this field should appear in object's repr.
:param bool cmp: include this field in generated comparison.
:param string key: override name of the value when converted to dict.
"""
default = _init_fields.init_default(required, default, None)
validator = _init_fields.init_validator(required, float)
return attrib(default=default, converter=converters.float_if_not_none,
validator=validator, repr=repr, cmp=cmp,
metadata=dict(key=key)) | python | def FloatField(default=NOTHING, required=True, repr=True, cmp=True,
key=None):
"""
Create new float field on a model.
:param default: any float value
:param bool required: whether or not the object is invalid if not provided.
:param bool repr: include this field should appear in object's repr.
:param bool cmp: include this field in generated comparison.
:param string key: override name of the value when converted to dict.
"""
default = _init_fields.init_default(required, default, None)
validator = _init_fields.init_validator(required, float)
return attrib(default=default, converter=converters.float_if_not_none,
validator=validator, repr=repr, cmp=cmp,
metadata=dict(key=key)) | [
"def",
"FloatField",
"(",
"default",
"=",
"NOTHING",
",",
"required",
"=",
"True",
",",
"repr",
"=",
"True",
",",
"cmp",
"=",
"True",
",",
"key",
"=",
"None",
")",
":",
"default",
"=",
"_init_fields",
".",
"init_default",
"(",
"required",
",",
"default... | Create new float field on a model.
:param default: any float value
:param bool required: whether or not the object is invalid if not provided.
:param bool repr: include this field should appear in object's repr.
:param bool cmp: include this field in generated comparison.
:param string key: override name of the value when converted to dict. | [
"Create",
"new",
"float",
"field",
"on",
"a",
"model",
"."
] | be47c0081e60fc60afcde3a25f00ebcad5d18510 | https://github.com/genomoncology/related/blob/be47c0081e60fc60afcde3a25f00ebcad5d18510/src/related/fields.py#L111-L126 | train | 34,793 |
genomoncology/related | src/related/fields.py | IntegerField | def IntegerField(default=NOTHING, required=True, repr=True, cmp=True,
key=None):
"""
Create new int field on a model.
:param default: any integer value
:param bool required: whether or not the object is invalid if not provided.
:param bool repr: include this field should appear in object's repr.
:param bool cmp: include this field in generated comparison.
:param string key: override name of the value when converted to dict.
"""
default = _init_fields.init_default(required, default, None)
validator = _init_fields.init_validator(required, int)
return attrib(default=default, converter=converters.int_if_not_none,
validator=validator, repr=repr, cmp=cmp,
metadata=dict(key=key)) | python | def IntegerField(default=NOTHING, required=True, repr=True, cmp=True,
key=None):
"""
Create new int field on a model.
:param default: any integer value
:param bool required: whether or not the object is invalid if not provided.
:param bool repr: include this field should appear in object's repr.
:param bool cmp: include this field in generated comparison.
:param string key: override name of the value when converted to dict.
"""
default = _init_fields.init_default(required, default, None)
validator = _init_fields.init_validator(required, int)
return attrib(default=default, converter=converters.int_if_not_none,
validator=validator, repr=repr, cmp=cmp,
metadata=dict(key=key)) | [
"def",
"IntegerField",
"(",
"default",
"=",
"NOTHING",
",",
"required",
"=",
"True",
",",
"repr",
"=",
"True",
",",
"cmp",
"=",
"True",
",",
"key",
"=",
"None",
")",
":",
"default",
"=",
"_init_fields",
".",
"init_default",
"(",
"required",
",",
"defau... | Create new int field on a model.
:param default: any integer value
:param bool required: whether or not the object is invalid if not provided.
:param bool repr: include this field should appear in object's repr.
:param bool cmp: include this field in generated comparison.
:param string key: override name of the value when converted to dict. | [
"Create",
"new",
"int",
"field",
"on",
"a",
"model",
"."
] | be47c0081e60fc60afcde3a25f00ebcad5d18510 | https://github.com/genomoncology/related/blob/be47c0081e60fc60afcde3a25f00ebcad5d18510/src/related/fields.py#L129-L144 | train | 34,794 |
genomoncology/related | src/related/fields.py | MappingField | def MappingField(cls, child_key, default=NOTHING, required=True, repr=False,
key=None):
"""
Create new mapping field on a model.
:param cls: class (or name) of the model to be related in Sequence.
:param child_key: key field on the child object to be used as the map key.
:param default: any mapping type
:param bool required: whether or not the object is invalid if not provided.
:param bool repr: include this field should appear in object's repr.
:param bool cmp: include this field in generated comparison.
:param string key: override name of the value when converted to dict.
"""
default = _init_fields.init_default(required, default, OrderedDict())
converter = converters.to_mapping_field(cls, child_key)
validator = _init_fields.init_validator(required, types.TypedMapping)
return attrib(default=default, converter=converter, validator=validator,
repr=repr, metadata=dict(key=key)) | python | def MappingField(cls, child_key, default=NOTHING, required=True, repr=False,
key=None):
"""
Create new mapping field on a model.
:param cls: class (or name) of the model to be related in Sequence.
:param child_key: key field on the child object to be used as the map key.
:param default: any mapping type
:param bool required: whether or not the object is invalid if not provided.
:param bool repr: include this field should appear in object's repr.
:param bool cmp: include this field in generated comparison.
:param string key: override name of the value when converted to dict.
"""
default = _init_fields.init_default(required, default, OrderedDict())
converter = converters.to_mapping_field(cls, child_key)
validator = _init_fields.init_validator(required, types.TypedMapping)
return attrib(default=default, converter=converter, validator=validator,
repr=repr, metadata=dict(key=key)) | [
"def",
"MappingField",
"(",
"cls",
",",
"child_key",
",",
"default",
"=",
"NOTHING",
",",
"required",
"=",
"True",
",",
"repr",
"=",
"False",
",",
"key",
"=",
"None",
")",
":",
"default",
"=",
"_init_fields",
".",
"init_default",
"(",
"required",
",",
... | Create new mapping field on a model.
:param cls: class (or name) of the model to be related in Sequence.
:param child_key: key field on the child object to be used as the map key.
:param default: any mapping type
:param bool required: whether or not the object is invalid if not provided.
:param bool repr: include this field should appear in object's repr.
:param bool cmp: include this field in generated comparison.
:param string key: override name of the value when converted to dict. | [
"Create",
"new",
"mapping",
"field",
"on",
"a",
"model",
"."
] | be47c0081e60fc60afcde3a25f00ebcad5d18510 | https://github.com/genomoncology/related/blob/be47c0081e60fc60afcde3a25f00ebcad5d18510/src/related/fields.py#L147-L164 | train | 34,795 |
genomoncology/related | src/related/fields.py | RegexField | def RegexField(regex, default=NOTHING, required=True, repr=True, cmp=True,
key=None):
"""
Create new str field on a model.
:param regex: regex validation string (e.g. "[^@]+@[^@]+" for email)
:param default: any string value
:param bool required: whether or not the object is invalid if not provided.
:param bool repr: include this field should appear in object's repr.
:param bool cmp: include this field in generated comparison.
:param string key: override name of the value when converted to dict.
"""
default = _init_fields.init_default(required, default, None)
validator = _init_fields.init_validator(required, string_types,
validators.regex(regex))
return attrib(default=default, converter=converters.str_if_not_none,
validator=validator, repr=repr, cmp=cmp,
metadata=dict(key=key)) | python | def RegexField(regex, default=NOTHING, required=True, repr=True, cmp=True,
key=None):
"""
Create new str field on a model.
:param regex: regex validation string (e.g. "[^@]+@[^@]+" for email)
:param default: any string value
:param bool required: whether or not the object is invalid if not provided.
:param bool repr: include this field should appear in object's repr.
:param bool cmp: include this field in generated comparison.
:param string key: override name of the value when converted to dict.
"""
default = _init_fields.init_default(required, default, None)
validator = _init_fields.init_validator(required, string_types,
validators.regex(regex))
return attrib(default=default, converter=converters.str_if_not_none,
validator=validator, repr=repr, cmp=cmp,
metadata=dict(key=key)) | [
"def",
"RegexField",
"(",
"regex",
",",
"default",
"=",
"NOTHING",
",",
"required",
"=",
"True",
",",
"repr",
"=",
"True",
",",
"cmp",
"=",
"True",
",",
"key",
"=",
"None",
")",
":",
"default",
"=",
"_init_fields",
".",
"init_default",
"(",
"required",... | Create new str field on a model.
:param regex: regex validation string (e.g. "[^@]+@[^@]+" for email)
:param default: any string value
:param bool required: whether or not the object is invalid if not provided.
:param bool repr: include this field should appear in object's repr.
:param bool cmp: include this field in generated comparison.
:param string key: override name of the value when converted to dict. | [
"Create",
"new",
"str",
"field",
"on",
"a",
"model",
"."
] | be47c0081e60fc60afcde3a25f00ebcad5d18510 | https://github.com/genomoncology/related/blob/be47c0081e60fc60afcde3a25f00ebcad5d18510/src/related/fields.py#L167-L184 | train | 34,796 |
genomoncology/related | src/related/fields.py | SequenceField | def SequenceField(cls, default=NOTHING, required=True, repr=False, key=None):
"""
Create new sequence field on a model.
:param cls: class (or name) of the model to be related in Sequence.
:param default: any TypedSequence or list
:param bool required: whether or not the object is invalid if not provided.
:param bool repr: include this field should appear in object's repr.
:param bool cmp: include this field in generated comparison.
:param string key: override name of the value when converted to dict.
"""
default = _init_fields.init_default(required, default, [])
converter = converters.to_sequence_field(cls)
validator = _init_fields.init_validator(required, types.TypedSequence)
return attrib(default=default, converter=converter, validator=validator,
repr=repr, metadata=dict(key=key)) | python | def SequenceField(cls, default=NOTHING, required=True, repr=False, key=None):
"""
Create new sequence field on a model.
:param cls: class (or name) of the model to be related in Sequence.
:param default: any TypedSequence or list
:param bool required: whether or not the object is invalid if not provided.
:param bool repr: include this field should appear in object's repr.
:param bool cmp: include this field in generated comparison.
:param string key: override name of the value when converted to dict.
"""
default = _init_fields.init_default(required, default, [])
converter = converters.to_sequence_field(cls)
validator = _init_fields.init_validator(required, types.TypedSequence)
return attrib(default=default, converter=converter, validator=validator,
repr=repr, metadata=dict(key=key)) | [
"def",
"SequenceField",
"(",
"cls",
",",
"default",
"=",
"NOTHING",
",",
"required",
"=",
"True",
",",
"repr",
"=",
"False",
",",
"key",
"=",
"None",
")",
":",
"default",
"=",
"_init_fields",
".",
"init_default",
"(",
"required",
",",
"default",
",",
"... | Create new sequence field on a model.
:param cls: class (or name) of the model to be related in Sequence.
:param default: any TypedSequence or list
:param bool required: whether or not the object is invalid if not provided.
:param bool repr: include this field should appear in object's repr.
:param bool cmp: include this field in generated comparison.
:param string key: override name of the value when converted to dict. | [
"Create",
"new",
"sequence",
"field",
"on",
"a",
"model",
"."
] | be47c0081e60fc60afcde3a25f00ebcad5d18510 | https://github.com/genomoncology/related/blob/be47c0081e60fc60afcde3a25f00ebcad5d18510/src/related/fields.py#L187-L202 | train | 34,797 |
genomoncology/related | src/related/fields.py | SetField | def SetField(cls, default=NOTHING, required=True, repr=False, key=None):
"""
Create new set field on a model.
:param cls: class (or name) of the model to be related in Set.
:param default: any TypedSet or set
:param bool required: whether or not the object is invalid if not provided.
:param bool repr: include this field should appear in object's repr.
:param bool cmp: include this field in generated comparison.
:param string key: override name of the value when converted to dict.
"""
default = _init_fields.init_default(required, default, set())
converter = converters.to_set_field(cls)
validator = _init_fields.init_validator(required, types.TypedSet)
return attrib(default=default, converter=converter, validator=validator,
repr=repr, metadata=dict(key=key)) | python | def SetField(cls, default=NOTHING, required=True, repr=False, key=None):
"""
Create new set field on a model.
:param cls: class (or name) of the model to be related in Set.
:param default: any TypedSet or set
:param bool required: whether or not the object is invalid if not provided.
:param bool repr: include this field should appear in object's repr.
:param bool cmp: include this field in generated comparison.
:param string key: override name of the value when converted to dict.
"""
default = _init_fields.init_default(required, default, set())
converter = converters.to_set_field(cls)
validator = _init_fields.init_validator(required, types.TypedSet)
return attrib(default=default, converter=converter, validator=validator,
repr=repr, metadata=dict(key=key)) | [
"def",
"SetField",
"(",
"cls",
",",
"default",
"=",
"NOTHING",
",",
"required",
"=",
"True",
",",
"repr",
"=",
"False",
",",
"key",
"=",
"None",
")",
":",
"default",
"=",
"_init_fields",
".",
"init_default",
"(",
"required",
",",
"default",
",",
"set",... | Create new set field on a model.
:param cls: class (or name) of the model to be related in Set.
:param default: any TypedSet or set
:param bool required: whether or not the object is invalid if not provided.
:param bool repr: include this field should appear in object's repr.
:param bool cmp: include this field in generated comparison.
:param string key: override name of the value when converted to dict. | [
"Create",
"new",
"set",
"field",
"on",
"a",
"model",
"."
] | be47c0081e60fc60afcde3a25f00ebcad5d18510 | https://github.com/genomoncology/related/blob/be47c0081e60fc60afcde3a25f00ebcad5d18510/src/related/fields.py#L205-L220 | train | 34,798 |
genomoncology/related | src/related/fields.py | DecimalField | def DecimalField(default=NOTHING, required=True, repr=True, cmp=True,
key=None):
"""
Create new decimal field on a model.
:param default: any decimal value
:param bool required: whether or not the object is invalid if not provided.
:param bool repr: include this field should appear in object's repr.
:param bool cmp: include this field in generated comparison.
:param string key: override name of the value when converted to dict.
"""
default = _init_fields.init_default(required, default, None)
validator = _init_fields.init_validator(required, Decimal)
return attrib(default=default, converter=lambda x: Decimal(x),
validator=validator, repr=repr, cmp=cmp,
metadata=dict(key=key)) | python | def DecimalField(default=NOTHING, required=True, repr=True, cmp=True,
key=None):
"""
Create new decimal field on a model.
:param default: any decimal value
:param bool required: whether or not the object is invalid if not provided.
:param bool repr: include this field should appear in object's repr.
:param bool cmp: include this field in generated comparison.
:param string key: override name of the value when converted to dict.
"""
default = _init_fields.init_default(required, default, None)
validator = _init_fields.init_validator(required, Decimal)
return attrib(default=default, converter=lambda x: Decimal(x),
validator=validator, repr=repr, cmp=cmp,
metadata=dict(key=key)) | [
"def",
"DecimalField",
"(",
"default",
"=",
"NOTHING",
",",
"required",
"=",
"True",
",",
"repr",
"=",
"True",
",",
"cmp",
"=",
"True",
",",
"key",
"=",
"None",
")",
":",
"default",
"=",
"_init_fields",
".",
"init_default",
"(",
"required",
",",
"defau... | Create new decimal field on a model.
:param default: any decimal value
:param bool required: whether or not the object is invalid if not provided.
:param bool repr: include this field should appear in object's repr.
:param bool cmp: include this field in generated comparison.
:param string key: override name of the value when converted to dict. | [
"Create",
"new",
"decimal",
"field",
"on",
"a",
"model",
"."
] | be47c0081e60fc60afcde3a25f00ebcad5d18510 | https://github.com/genomoncology/related/blob/be47c0081e60fc60afcde3a25f00ebcad5d18510/src/related/fields.py#L277-L292 | train | 34,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.