partition stringclasses 3 values | func_name stringlengths 1 134 | docstring stringlengths 1 46.9k | path stringlengths 4 223 | original_string stringlengths 75 104k | code stringlengths 75 104k | docstring_tokens listlengths 1 1.97k | repo stringlengths 7 55 | language stringclasses 1 value | url stringlengths 87 315 | code_tokens listlengths 19 28.4k | sha stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|
test | draw_image | Draw an image.
The image's top-left corner is drawn at ``(x1, y1)``, and its lower-left at ``(x2, y2)``. If ``x2`` and ``y2`` are omitted, they
are calculated to render the image at its native resoultion.
Note that images can be flipped and scaled by providing alternative values for ``x2`` and ``y2``.
:param image: an :class:`Image` to draw | bacon/graphics.py | def draw_image(image, x1, y1, x2 = None, y2 = None):
'''Draw an image.
The image's top-left corner is drawn at ``(x1, y1)``, and its lower-left at ``(x2, y2)``. If ``x2`` and ``y2`` are omitted, they
are calculated to render the image at its native resoultion.
Note that images can be flipped and scaled by providing alternative values for ``x2`` and ``y2``.
:param image: an :class:`Image` to draw
'''
if x2 is None:
x2 = x1 + image.width
if y2 is None:
y2 = y1 + image.height
lib.DrawImage(image._handle, x1, y1, x2, y2) | def draw_image(image, x1, y1, x2 = None, y2 = None):
'''Draw an image.
The image's top-left corner is drawn at ``(x1, y1)``, and its lower-left at ``(x2, y2)``. If ``x2`` and ``y2`` are omitted, they
are calculated to render the image at its native resoultion.
Note that images can be flipped and scaled by providing alternative values for ``x2`` and ``y2``.
:param image: an :class:`Image` to draw
'''
if x2 is None:
x2 = x1 + image.width
if y2 is None:
y2 = y1 + image.height
lib.DrawImage(image._handle, x1, y1, x2, y2) | [
"Draw",
"an",
"image",
"."
] | aholkner/bacon | python | https://github.com/aholkner/bacon/blob/edf3810dcb211942d392a8637945871399b0650d/bacon/graphics.py#L181-L195 | [
"def",
"draw_image",
"(",
"image",
",",
"x1",
",",
"y1",
",",
"x2",
"=",
"None",
",",
"y2",
"=",
"None",
")",
":",
"if",
"x2",
"is",
"None",
":",
"x2",
"=",
"x1",
"+",
"image",
".",
"width",
"if",
"y2",
"is",
"None",
":",
"y2",
"=",
"y1",
"+",
"image",
".",
"height",
"lib",
".",
"DrawImage",
"(",
"image",
".",
"_handle",
",",
"x1",
",",
"y1",
",",
"x2",
",",
"y2",
")"
] | edf3810dcb211942d392a8637945871399b0650d |
test | draw_image_region | Draw a rectangular region of an image.
The part of the image contained by the rectangle in texel-space by the coordinates ``(ix1, iy1)`` to ``(ix2, iy2)`` is
drawn at coordinates ``(x1, y1)`` to ``(x2, y2)``. All coordinates have the origin ``(0, 0)`` at the upper-left corner.
For example, to draw the left half of a ``100x100`` image at coordinates ``(x, y)``::
bacon.draw_image_region(image, x, y, x + 50, y + 100,
0, 0, 50, 100)
:param image: an :class:`Image` to draw | bacon/graphics.py | def draw_image_region(image, x1, y1, x2, y2,
ix1, iy1, ix2, iy2):
'''Draw a rectangular region of an image.
The part of the image contained by the rectangle in texel-space by the coordinates ``(ix1, iy1)`` to ``(ix2, iy2)`` is
drawn at coordinates ``(x1, y1)`` to ``(x2, y2)``. All coordinates have the origin ``(0, 0)`` at the upper-left corner.
For example, to draw the left half of a ``100x100`` image at coordinates ``(x, y)``::
bacon.draw_image_region(image, x, y, x + 50, y + 100,
0, 0, 50, 100)
:param image: an :class:`Image` to draw
'''
lib.DrawImageRegion(image._handle, x1, y1, x2, y2, ix1, iy1, ix2, iy2) | def draw_image_region(image, x1, y1, x2, y2,
ix1, iy1, ix2, iy2):
'''Draw a rectangular region of an image.
The part of the image contained by the rectangle in texel-space by the coordinates ``(ix1, iy1)`` to ``(ix2, iy2)`` is
drawn at coordinates ``(x1, y1)`` to ``(x2, y2)``. All coordinates have the origin ``(0, 0)`` at the upper-left corner.
For example, to draw the left half of a ``100x100`` image at coordinates ``(x, y)``::
bacon.draw_image_region(image, x, y, x + 50, y + 100,
0, 0, 50, 100)
:param image: an :class:`Image` to draw
'''
lib.DrawImageRegion(image._handle, x1, y1, x2, y2, ix1, iy1, ix2, iy2) | [
"Draw",
"a",
"rectangular",
"region",
"of",
"an",
"image",
"."
] | aholkner/bacon | python | https://github.com/aholkner/bacon/blob/edf3810dcb211942d392a8637945871399b0650d/bacon/graphics.py#L197-L211 | [
"def",
"draw_image_region",
"(",
"image",
",",
"x1",
",",
"y1",
",",
"x2",
",",
"y2",
",",
"ix1",
",",
"iy1",
",",
"ix2",
",",
"iy2",
")",
":",
"lib",
".",
"DrawImageRegion",
"(",
"image",
".",
"_handle",
",",
"x1",
",",
"y1",
",",
"x2",
",",
"y2",
",",
"ix1",
",",
"iy1",
",",
"ix2",
",",
"iy2",
")"
] | edf3810dcb211942d392a8637945871399b0650d |
test | OggPage.size | Total frame size. | mutagen/ogg.py | def size(self):
"""Total frame size."""
header_size = 27 # Initial header size
for datum in self.packets:
quot, rem = divmod(len(datum), 255)
header_size += quot + 1
if not self.complete and rem == 0:
# Packet contains a multiple of 255 bytes and is not
# terminated, so we don't have a \x00 at the end.
header_size -= 1
header_size += sum(map(len, self.packets))
return header_size | def size(self):
"""Total frame size."""
header_size = 27 # Initial header size
for datum in self.packets:
quot, rem = divmod(len(datum), 255)
header_size += quot + 1
if not self.complete and rem == 0:
# Packet contains a multiple of 255 bytes and is not
# terminated, so we don't have a \x00 at the end.
header_size -= 1
header_size += sum(map(len, self.packets))
return header_size | [
"Total",
"frame",
"size",
"."
] | LordSputnik/mutagen | python | https://github.com/LordSputnik/mutagen/blob/38e62c8dc35c72b16554f5dbe7c0fde91acc3411/mutagen/ogg.py#L165-L177 | [
"def",
"size",
"(",
"self",
")",
":",
"header_size",
"=",
"27",
"# Initial header size",
"for",
"datum",
"in",
"self",
".",
"packets",
":",
"quot",
",",
"rem",
"=",
"divmod",
"(",
"len",
"(",
"datum",
")",
",",
"255",
")",
"header_size",
"+=",
"quot",
"+",
"1",
"if",
"not",
"self",
".",
"complete",
"and",
"rem",
"==",
"0",
":",
"# Packet contains a multiple of 255 bytes and is not",
"# terminated, so we don't have a \\x00 at the end.",
"header_size",
"-=",
"1",
"header_size",
"+=",
"sum",
"(",
"map",
"(",
"len",
",",
"self",
".",
"packets",
")",
")",
"return",
"header_size"
] | 38e62c8dc35c72b16554f5dbe7c0fde91acc3411 |
test | OggPage.replace | Replace old_pages with new_pages within fileobj.
old_pages must have come from reading fileobj originally.
new_pages are assumed to have the 'same' data as old_pages,
and so the serial and sequence numbers will be copied, as will
the flags for the first and last pages.
fileobj will be resized and pages renumbered as necessary. As
such, it must be opened r+b or w+b. | mutagen/ogg.py | def replace(cls, fileobj, old_pages, new_pages):
"""Replace old_pages with new_pages within fileobj.
old_pages must have come from reading fileobj originally.
new_pages are assumed to have the 'same' data as old_pages,
and so the serial and sequence numbers will be copied, as will
the flags for the first and last pages.
fileobj will be resized and pages renumbered as necessary. As
such, it must be opened r+b or w+b.
"""
# Number the new pages starting from the first old page.
first = old_pages[0].sequence
for page, seq in zip(new_pages, range(first, first + len(new_pages))):
page.sequence = seq
page.serial = old_pages[0].serial
new_pages[0].first = old_pages[0].first
new_pages[0].last = old_pages[0].last
new_pages[0].continued = old_pages[0].continued
new_pages[-1].first = old_pages[-1].first
new_pages[-1].last = old_pages[-1].last
new_pages[-1].complete = old_pages[-1].complete
if not new_pages[-1].complete and len(new_pages[-1].packets) == 1:
new_pages[-1].position = -1
new_data = b''.join(cls.write(p) for p in new_pages)
# Make room in the file for the new data.
delta = len(new_data)
fileobj.seek(old_pages[0].offset, 0)
insert_bytes(fileobj, delta, old_pages[0].offset)
fileobj.seek(old_pages[0].offset, 0)
fileobj.write(new_data)
new_data_end = old_pages[0].offset + delta
# Go through the old pages and delete them. Since we shifted
# the data down the file, we need to adjust their offsets. We
# also need to go backwards, so we don't adjust the deltas of
# the other pages.
old_pages.reverse()
for old_page in old_pages:
adj_offset = old_page.offset + delta
delete_bytes(fileobj, old_page.size, adj_offset)
# Finally, if there's any discrepency in length, we need to
# renumber the pages for the logical stream.
if len(old_pages) != len(new_pages):
fileobj.seek(new_data_end, 0)
serial = new_pages[-1].serial
sequence = new_pages[-1].sequence + 1
cls.renumber(fileobj, serial, sequence) | def replace(cls, fileobj, old_pages, new_pages):
"""Replace old_pages with new_pages within fileobj.
old_pages must have come from reading fileobj originally.
new_pages are assumed to have the 'same' data as old_pages,
and so the serial and sequence numbers will be copied, as will
the flags for the first and last pages.
fileobj will be resized and pages renumbered as necessary. As
such, it must be opened r+b or w+b.
"""
# Number the new pages starting from the first old page.
first = old_pages[0].sequence
for page, seq in zip(new_pages, range(first, first + len(new_pages))):
page.sequence = seq
page.serial = old_pages[0].serial
new_pages[0].first = old_pages[0].first
new_pages[0].last = old_pages[0].last
new_pages[0].continued = old_pages[0].continued
new_pages[-1].first = old_pages[-1].first
new_pages[-1].last = old_pages[-1].last
new_pages[-1].complete = old_pages[-1].complete
if not new_pages[-1].complete and len(new_pages[-1].packets) == 1:
new_pages[-1].position = -1
new_data = b''.join(cls.write(p) for p in new_pages)
# Make room in the file for the new data.
delta = len(new_data)
fileobj.seek(old_pages[0].offset, 0)
insert_bytes(fileobj, delta, old_pages[0].offset)
fileobj.seek(old_pages[0].offset, 0)
fileobj.write(new_data)
new_data_end = old_pages[0].offset + delta
# Go through the old pages and delete them. Since we shifted
# the data down the file, we need to adjust their offsets. We
# also need to go backwards, so we don't adjust the deltas of
# the other pages.
old_pages.reverse()
for old_page in old_pages:
adj_offset = old_page.offset + delta
delete_bytes(fileobj, old_page.size, adj_offset)
# Finally, if there's any discrepency in length, we need to
# renumber the pages for the logical stream.
if len(old_pages) != len(new_pages):
fileobj.seek(new_data_end, 0)
serial = new_pages[-1].serial
sequence = new_pages[-1].sequence + 1
cls.renumber(fileobj, serial, sequence) | [
"Replace",
"old_pages",
"with",
"new_pages",
"within",
"fileobj",
"."
] | LordSputnik/mutagen | python | https://github.com/LordSputnik/mutagen/blob/38e62c8dc35c72b16554f5dbe7c0fde91acc3411/mutagen/ogg.py#L338-L391 | [
"def",
"replace",
"(",
"cls",
",",
"fileobj",
",",
"old_pages",
",",
"new_pages",
")",
":",
"# Number the new pages starting from the first old page.",
"first",
"=",
"old_pages",
"[",
"0",
"]",
".",
"sequence",
"for",
"page",
",",
"seq",
"in",
"zip",
"(",
"new_pages",
",",
"range",
"(",
"first",
",",
"first",
"+",
"len",
"(",
"new_pages",
")",
")",
")",
":",
"page",
".",
"sequence",
"=",
"seq",
"page",
".",
"serial",
"=",
"old_pages",
"[",
"0",
"]",
".",
"serial",
"new_pages",
"[",
"0",
"]",
".",
"first",
"=",
"old_pages",
"[",
"0",
"]",
".",
"first",
"new_pages",
"[",
"0",
"]",
".",
"last",
"=",
"old_pages",
"[",
"0",
"]",
".",
"last",
"new_pages",
"[",
"0",
"]",
".",
"continued",
"=",
"old_pages",
"[",
"0",
"]",
".",
"continued",
"new_pages",
"[",
"-",
"1",
"]",
".",
"first",
"=",
"old_pages",
"[",
"-",
"1",
"]",
".",
"first",
"new_pages",
"[",
"-",
"1",
"]",
".",
"last",
"=",
"old_pages",
"[",
"-",
"1",
"]",
".",
"last",
"new_pages",
"[",
"-",
"1",
"]",
".",
"complete",
"=",
"old_pages",
"[",
"-",
"1",
"]",
".",
"complete",
"if",
"not",
"new_pages",
"[",
"-",
"1",
"]",
".",
"complete",
"and",
"len",
"(",
"new_pages",
"[",
"-",
"1",
"]",
".",
"packets",
")",
"==",
"1",
":",
"new_pages",
"[",
"-",
"1",
"]",
".",
"position",
"=",
"-",
"1",
"new_data",
"=",
"b''",
".",
"join",
"(",
"cls",
".",
"write",
"(",
"p",
")",
"for",
"p",
"in",
"new_pages",
")",
"# Make room in the file for the new data.",
"delta",
"=",
"len",
"(",
"new_data",
")",
"fileobj",
".",
"seek",
"(",
"old_pages",
"[",
"0",
"]",
".",
"offset",
",",
"0",
")",
"insert_bytes",
"(",
"fileobj",
",",
"delta",
",",
"old_pages",
"[",
"0",
"]",
".",
"offset",
")",
"fileobj",
".",
"seek",
"(",
"old_pages",
"[",
"0",
"]",
".",
"offset",
",",
"0",
")",
"fileobj",
".",
"write",
"(",
"new_data",
")",
"new_data_end",
"=",
"old_pages",
"[",
"0",
"]",
".",
"offset",
"+",
"delta",
"# Go through the old pages and delete them. Since we shifted",
"# the data down the file, we need to adjust their offsets. We",
"# also need to go backwards, so we don't adjust the deltas of",
"# the other pages.",
"old_pages",
".",
"reverse",
"(",
")",
"for",
"old_page",
"in",
"old_pages",
":",
"adj_offset",
"=",
"old_page",
".",
"offset",
"+",
"delta",
"delete_bytes",
"(",
"fileobj",
",",
"old_page",
".",
"size",
",",
"adj_offset",
")",
"# Finally, if there's any discrepency in length, we need to",
"# renumber the pages for the logical stream.",
"if",
"len",
"(",
"old_pages",
")",
"!=",
"len",
"(",
"new_pages",
")",
":",
"fileobj",
".",
"seek",
"(",
"new_data_end",
",",
"0",
")",
"serial",
"=",
"new_pages",
"[",
"-",
"1",
"]",
".",
"serial",
"sequence",
"=",
"new_pages",
"[",
"-",
"1",
"]",
".",
"sequence",
"+",
"1",
"cls",
".",
"renumber",
"(",
"fileobj",
",",
"serial",
",",
"sequence",
")"
] | 38e62c8dc35c72b16554f5dbe7c0fde91acc3411 |
test | OggPage.find_last | Find the last page of the stream 'serial'.
If the file is not multiplexed this function is fast. If it is,
it must read the whole the stream.
This finds the last page in the actual file object, or the last
page in the stream (with eos set), whichever comes first. | mutagen/ogg.py | def find_last(fileobj, serial):
"""Find the last page of the stream 'serial'.
If the file is not multiplexed this function is fast. If it is,
it must read the whole the stream.
This finds the last page in the actual file object, or the last
page in the stream (with eos set), whichever comes first.
"""
# For non-muxed streams, look at the last page.
try:
fileobj.seek(-256*256, 2)
except IOError:
# The file is less than 64k in length.
fileobj.seek(0)
data = fileobj.read()
try:
index = data.rindex(b"OggS")
except ValueError:
raise error("unable to find final Ogg header")
bytesobj = cBytesIO(data[index:])
best_page = None
try:
page = OggPage(bytesobj)
except error:
pass
else:
if page.serial == serial:
if page.last:
return page
else:
best_page = page
else:
best_page = None
# The stream is muxed, so use the slow way.
fileobj.seek(0)
try:
page = OggPage(fileobj)
while not page.last:
page = OggPage(fileobj)
while page.serial != serial:
page = OggPage(fileobj)
best_page = page
return page
except error:
return best_page
except EOFError:
return best_page | def find_last(fileobj, serial):
"""Find the last page of the stream 'serial'.
If the file is not multiplexed this function is fast. If it is,
it must read the whole the stream.
This finds the last page in the actual file object, or the last
page in the stream (with eos set), whichever comes first.
"""
# For non-muxed streams, look at the last page.
try:
fileobj.seek(-256*256, 2)
except IOError:
# The file is less than 64k in length.
fileobj.seek(0)
data = fileobj.read()
try:
index = data.rindex(b"OggS")
except ValueError:
raise error("unable to find final Ogg header")
bytesobj = cBytesIO(data[index:])
best_page = None
try:
page = OggPage(bytesobj)
except error:
pass
else:
if page.serial == serial:
if page.last:
return page
else:
best_page = page
else:
best_page = None
# The stream is muxed, so use the slow way.
fileobj.seek(0)
try:
page = OggPage(fileobj)
while not page.last:
page = OggPage(fileobj)
while page.serial != serial:
page = OggPage(fileobj)
best_page = page
return page
except error:
return best_page
except EOFError:
return best_page | [
"Find",
"the",
"last",
"page",
"of",
"the",
"stream",
"serial",
"."
] | LordSputnik/mutagen | python | https://github.com/LordSputnik/mutagen/blob/38e62c8dc35c72b16554f5dbe7c0fde91acc3411/mutagen/ogg.py#L394-L443 | [
"def",
"find_last",
"(",
"fileobj",
",",
"serial",
")",
":",
"# For non-muxed streams, look at the last page.",
"try",
":",
"fileobj",
".",
"seek",
"(",
"-",
"256",
"*",
"256",
",",
"2",
")",
"except",
"IOError",
":",
"# The file is less than 64k in length.",
"fileobj",
".",
"seek",
"(",
"0",
")",
"data",
"=",
"fileobj",
".",
"read",
"(",
")",
"try",
":",
"index",
"=",
"data",
".",
"rindex",
"(",
"b\"OggS\"",
")",
"except",
"ValueError",
":",
"raise",
"error",
"(",
"\"unable to find final Ogg header\"",
")",
"bytesobj",
"=",
"cBytesIO",
"(",
"data",
"[",
"index",
":",
"]",
")",
"best_page",
"=",
"None",
"try",
":",
"page",
"=",
"OggPage",
"(",
"bytesobj",
")",
"except",
"error",
":",
"pass",
"else",
":",
"if",
"page",
".",
"serial",
"==",
"serial",
":",
"if",
"page",
".",
"last",
":",
"return",
"page",
"else",
":",
"best_page",
"=",
"page",
"else",
":",
"best_page",
"=",
"None",
"# The stream is muxed, so use the slow way.",
"fileobj",
".",
"seek",
"(",
"0",
")",
"try",
":",
"page",
"=",
"OggPage",
"(",
"fileobj",
")",
"while",
"not",
"page",
".",
"last",
":",
"page",
"=",
"OggPage",
"(",
"fileobj",
")",
"while",
"page",
".",
"serial",
"!=",
"serial",
":",
"page",
"=",
"OggPage",
"(",
"fileobj",
")",
"best_page",
"=",
"page",
"return",
"page",
"except",
"error",
":",
"return",
"best_page",
"except",
"EOFError",
":",
"return",
"best_page"
] | 38e62c8dc35c72b16554f5dbe7c0fde91acc3411 |
test | OggFileType.load | Load file information from a filename. | mutagen/ogg.py | def load(self, filename):
"""Load file information from a filename."""
self.filename = filename
fileobj = open(filename, "rb")
try:
try:
self.info = self._Info(fileobj)
self.tags = self._Tags(fileobj, self.info)
self.info._post_tags(fileobj)
except error as e:
reraise(self._Error, e, sys.exc_info()[2])
except EOFError:
raise self._Error("no appropriate stream found")
finally:
fileobj.close() | def load(self, filename):
"""Load file information from a filename."""
self.filename = filename
fileobj = open(filename, "rb")
try:
try:
self.info = self._Info(fileobj)
self.tags = self._Tags(fileobj, self.info)
self.info._post_tags(fileobj)
except error as e:
reraise(self._Error, e, sys.exc_info()[2])
except EOFError:
raise self._Error("no appropriate stream found")
finally:
fileobj.close() | [
"Load",
"file",
"information",
"from",
"a",
"filename",
"."
] | LordSputnik/mutagen | python | https://github.com/LordSputnik/mutagen/blob/38e62c8dc35c72b16554f5dbe7c0fde91acc3411/mutagen/ogg.py#L454-L469 | [
"def",
"load",
"(",
"self",
",",
"filename",
")",
":",
"self",
".",
"filename",
"=",
"filename",
"fileobj",
"=",
"open",
"(",
"filename",
",",
"\"rb\"",
")",
"try",
":",
"try",
":",
"self",
".",
"info",
"=",
"self",
".",
"_Info",
"(",
"fileobj",
")",
"self",
".",
"tags",
"=",
"self",
".",
"_Tags",
"(",
"fileobj",
",",
"self",
".",
"info",
")",
"self",
".",
"info",
".",
"_post_tags",
"(",
"fileobj",
")",
"except",
"error",
"as",
"e",
":",
"reraise",
"(",
"self",
".",
"_Error",
",",
"e",
",",
"sys",
".",
"exc_info",
"(",
")",
"[",
"2",
"]",
")",
"except",
"EOFError",
":",
"raise",
"self",
".",
"_Error",
"(",
"\"no appropriate stream found\"",
")",
"finally",
":",
"fileobj",
".",
"close",
"(",
")"
] | 38e62c8dc35c72b16554f5dbe7c0fde91acc3411 |
test | OggFileType.delete | Remove tags from a file.
If no filename is given, the one most recently loaded is used. | mutagen/ogg.py | def delete(self, filename=None):
"""Remove tags from a file.
If no filename is given, the one most recently loaded is used.
"""
if filename is None:
filename = self.filename
self.tags.clear()
fileobj = open(filename, "rb+")
try:
try:
self.tags._inject(fileobj)
except error as e:
reraise(self._Error, e, sys.exc_info()[2])
except EOFError:
raise self._Error("no appropriate stream found")
finally:
fileobj.close() | def delete(self, filename=None):
"""Remove tags from a file.
If no filename is given, the one most recently loaded is used.
"""
if filename is None:
filename = self.filename
self.tags.clear()
fileobj = open(filename, "rb+")
try:
try:
self.tags._inject(fileobj)
except error as e:
reraise(self._Error, e, sys.exc_info()[2])
except EOFError:
raise self._Error("no appropriate stream found")
finally:
fileobj.close() | [
"Remove",
"tags",
"from",
"a",
"file",
"."
] | LordSputnik/mutagen | python | https://github.com/LordSputnik/mutagen/blob/38e62c8dc35c72b16554f5dbe7c0fde91acc3411/mutagen/ogg.py#L471-L490 | [
"def",
"delete",
"(",
"self",
",",
"filename",
"=",
"None",
")",
":",
"if",
"filename",
"is",
"None",
":",
"filename",
"=",
"self",
".",
"filename",
"self",
".",
"tags",
".",
"clear",
"(",
")",
"fileobj",
"=",
"open",
"(",
"filename",
",",
"\"rb+\"",
")",
"try",
":",
"try",
":",
"self",
".",
"tags",
".",
"_inject",
"(",
"fileobj",
")",
"except",
"error",
"as",
"e",
":",
"reraise",
"(",
"self",
".",
"_Error",
",",
"e",
",",
"sys",
".",
"exc_info",
"(",
")",
"[",
"2",
"]",
")",
"except",
"EOFError",
":",
"raise",
"self",
".",
"_Error",
"(",
"\"no appropriate stream found\"",
")",
"finally",
":",
"fileobj",
".",
"close",
"(",
")"
] | 38e62c8dc35c72b16554f5dbe7c0fde91acc3411 |
test | OggTheoraCommentDict._inject | Write tag data into the Theora comment packet/page. | mutagen/oggtheora.py | def _inject(self, fileobj):
"""Write tag data into the Theora comment packet/page."""
fileobj.seek(0)
page = OggPage(fileobj)
while not page.packets[0].startswith(b"\x81theora"):
page = OggPage(fileobj)
old_pages = [page]
while not (old_pages[-1].complete or len(old_pages[-1].packets) > 1):
page = OggPage(fileobj)
if page.serial == old_pages[0].serial:
old_pages.append(page)
packets = OggPage.to_packets(old_pages, strict=False)
packets[0] = b"\x81theora" + self.write(framing=False)
new_pages = OggPage.from_packets(packets, old_pages[0].sequence)
OggPage.replace(fileobj, old_pages, new_pages) | def _inject(self, fileobj):
"""Write tag data into the Theora comment packet/page."""
fileobj.seek(0)
page = OggPage(fileobj)
while not page.packets[0].startswith(b"\x81theora"):
page = OggPage(fileobj)
old_pages = [page]
while not (old_pages[-1].complete or len(old_pages[-1].packets) > 1):
page = OggPage(fileobj)
if page.serial == old_pages[0].serial:
old_pages.append(page)
packets = OggPage.to_packets(old_pages, strict=False)
packets[0] = b"\x81theora" + self.write(framing=False)
new_pages = OggPage.from_packets(packets, old_pages[0].sequence)
OggPage.replace(fileobj, old_pages, new_pages) | [
"Write",
"tag",
"data",
"into",
"the",
"Theora",
"comment",
"packet",
"/",
"page",
"."
] | LordSputnik/mutagen | python | https://github.com/LordSputnik/mutagen/blob/38e62c8dc35c72b16554f5dbe7c0fde91acc3411/mutagen/oggtheora.py#L89-L108 | [
"def",
"_inject",
"(",
"self",
",",
"fileobj",
")",
":",
"fileobj",
".",
"seek",
"(",
"0",
")",
"page",
"=",
"OggPage",
"(",
"fileobj",
")",
"while",
"not",
"page",
".",
"packets",
"[",
"0",
"]",
".",
"startswith",
"(",
"b\"\\x81theora\"",
")",
":",
"page",
"=",
"OggPage",
"(",
"fileobj",
")",
"old_pages",
"=",
"[",
"page",
"]",
"while",
"not",
"(",
"old_pages",
"[",
"-",
"1",
"]",
".",
"complete",
"or",
"len",
"(",
"old_pages",
"[",
"-",
"1",
"]",
".",
"packets",
")",
">",
"1",
")",
":",
"page",
"=",
"OggPage",
"(",
"fileobj",
")",
"if",
"page",
".",
"serial",
"==",
"old_pages",
"[",
"0",
"]",
".",
"serial",
":",
"old_pages",
".",
"append",
"(",
"page",
")",
"packets",
"=",
"OggPage",
".",
"to_packets",
"(",
"old_pages",
",",
"strict",
"=",
"False",
")",
"packets",
"[",
"0",
"]",
"=",
"b\"\\x81theora\"",
"+",
"self",
".",
"write",
"(",
"framing",
"=",
"False",
")",
"new_pages",
"=",
"OggPage",
".",
"from_packets",
"(",
"packets",
",",
"old_pages",
"[",
"0",
"]",
".",
"sequence",
")",
"OggPage",
".",
"replace",
"(",
"fileobj",
",",
"old_pages",
",",
"new_pages",
")"
] | 38e62c8dc35c72b16554f5dbe7c0fde91acc3411 |
test | created_hosted_zone_parser | Parses the API responses for the
:py:meth:`route53.connection.Route53Connection.create_hosted_zone` method.
:param lxml.etree._Element root: The root node of the etree parsed
response from the API.
:param Route53Connection connection: The connection instance used to
query the API.
:rtype: HostedZone
:returns: The newly created HostedZone. | route53/xml_parsers/created_hosted_zone.py | def created_hosted_zone_parser(root, connection):
"""
Parses the API responses for the
:py:meth:`route53.connection.Route53Connection.create_hosted_zone` method.
:param lxml.etree._Element root: The root node of the etree parsed
response from the API.
:param Route53Connection connection: The connection instance used to
query the API.
:rtype: HostedZone
:returns: The newly created HostedZone.
"""
zone = root.find('./{*}HostedZone')
# This pops out a HostedZone instance.
hosted_zone = parse_hosted_zone(zone, connection)
# Now we'll fill in the nameservers.
e_delegation_set = root.find('./{*}DelegationSet')
# Modifies the HostedZone in place.
parse_delegation_set(hosted_zone, e_delegation_set)
# With each CreateHostedZone request, there's some details about the
# request's ID, status, and submission time. We'll return this in a tuple
# just for the sake of completeness.
e_change_info = root.find('./{*}ChangeInfo')
# Translate the ChangeInfo values to a dict.
change_info = parse_change_info(e_change_info)
return hosted_zone, change_info | def created_hosted_zone_parser(root, connection):
"""
Parses the API responses for the
:py:meth:`route53.connection.Route53Connection.create_hosted_zone` method.
:param lxml.etree._Element root: The root node of the etree parsed
response from the API.
:param Route53Connection connection: The connection instance used to
query the API.
:rtype: HostedZone
:returns: The newly created HostedZone.
"""
zone = root.find('./{*}HostedZone')
# This pops out a HostedZone instance.
hosted_zone = parse_hosted_zone(zone, connection)
# Now we'll fill in the nameservers.
e_delegation_set = root.find('./{*}DelegationSet')
# Modifies the HostedZone in place.
parse_delegation_set(hosted_zone, e_delegation_set)
# With each CreateHostedZone request, there's some details about the
# request's ID, status, and submission time. We'll return this in a tuple
# just for the sake of completeness.
e_change_info = root.find('./{*}ChangeInfo')
# Translate the ChangeInfo values to a dict.
change_info = parse_change_info(e_change_info)
return hosted_zone, change_info | [
"Parses",
"the",
"API",
"responses",
"for",
"the",
":",
"py",
":",
"meth",
":",
"route53",
".",
"connection",
".",
"Route53Connection",
".",
"create_hosted_zone",
"method",
"."
] | gtaylor/python-route53 | python | https://github.com/gtaylor/python-route53/blob/b9fc7e258a79551c9ed61e4a71668b7f06f9e774/route53/xml_parsers/created_hosted_zone.py#L4-L33 | [
"def",
"created_hosted_zone_parser",
"(",
"root",
",",
"connection",
")",
":",
"zone",
"=",
"root",
".",
"find",
"(",
"'./{*}HostedZone'",
")",
"# This pops out a HostedZone instance.",
"hosted_zone",
"=",
"parse_hosted_zone",
"(",
"zone",
",",
"connection",
")",
"# Now we'll fill in the nameservers.",
"e_delegation_set",
"=",
"root",
".",
"find",
"(",
"'./{*}DelegationSet'",
")",
"# Modifies the HostedZone in place.",
"parse_delegation_set",
"(",
"hosted_zone",
",",
"e_delegation_set",
")",
"# With each CreateHostedZone request, there's some details about the",
"# request's ID, status, and submission time. We'll return this in a tuple",
"# just for the sake of completeness.",
"e_change_info",
"=",
"root",
".",
"find",
"(",
"'./{*}ChangeInfo'",
")",
"# Translate the ChangeInfo values to a dict.",
"change_info",
"=",
"parse_change_info",
"(",
"e_change_info",
")",
"return",
"hosted_zone",
",",
"change_info"
] | b9fc7e258a79551c9ed61e4a71668b7f06f9e774 |
test | ContentProcessor.set_section | set current section during parsing | native/Vendor/FreeType/src/tools/docmaker/content.py | def set_section( self, section_name ):
"""set current section during parsing"""
if not self.sections.has_key( section_name ):
section = DocSection( section_name )
self.sections[section_name] = section
self.section = section
else:
self.section = self.sections[section_name] | def set_section( self, section_name ):
"""set current section during parsing"""
if not self.sections.has_key( section_name ):
section = DocSection( section_name )
self.sections[section_name] = section
self.section = section
else:
self.section = self.sections[section_name] | [
"set",
"current",
"section",
"during",
"parsing"
] | aholkner/bacon | python | https://github.com/aholkner/bacon/blob/edf3810dcb211942d392a8637945871399b0650d/native/Vendor/FreeType/src/tools/docmaker/content.py#L353-L360 | [
"def",
"set_section",
"(",
"self",
",",
"section_name",
")",
":",
"if",
"not",
"self",
".",
"sections",
".",
"has_key",
"(",
"section_name",
")",
":",
"section",
"=",
"DocSection",
"(",
"section_name",
")",
"self",
".",
"sections",
"[",
"section_name",
"]",
"=",
"section",
"self",
".",
"section",
"=",
"section",
"else",
":",
"self",
".",
"section",
"=",
"self",
".",
"sections",
"[",
"section_name",
"]"
] | edf3810dcb211942d392a8637945871399b0650d |
test | ContentProcessor.add_markup | add a new markup section | native/Vendor/FreeType/src/tools/docmaker/content.py | def add_markup( self ):
"""add a new markup section"""
if self.markup and self.markup_lines:
# get rid of last line of markup if it's empty
marks = self.markup_lines
if len( marks ) > 0 and not string.strip( marks[-1] ):
self.markup_lines = marks[:-1]
m = DocMarkup( self.markup, self.markup_lines )
self.markups.append( m )
self.markup = None
self.markup_lines = [] | def add_markup( self ):
"""add a new markup section"""
if self.markup and self.markup_lines:
# get rid of last line of markup if it's empty
marks = self.markup_lines
if len( marks ) > 0 and not string.strip( marks[-1] ):
self.markup_lines = marks[:-1]
m = DocMarkup( self.markup, self.markup_lines )
self.markups.append( m )
self.markup = None
self.markup_lines = [] | [
"add",
"a",
"new",
"markup",
"section"
] | aholkner/bacon | python | https://github.com/aholkner/bacon/blob/edf3810dcb211942d392a8637945871399b0650d/native/Vendor/FreeType/src/tools/docmaker/content.py#L373-L387 | [
"def",
"add_markup",
"(",
"self",
")",
":",
"if",
"self",
".",
"markup",
"and",
"self",
".",
"markup_lines",
":",
"# get rid of last line of markup if it's empty",
"marks",
"=",
"self",
".",
"markup_lines",
"if",
"len",
"(",
"marks",
")",
">",
"0",
"and",
"not",
"string",
".",
"strip",
"(",
"marks",
"[",
"-",
"1",
"]",
")",
":",
"self",
".",
"markup_lines",
"=",
"marks",
"[",
":",
"-",
"1",
"]",
"m",
"=",
"DocMarkup",
"(",
"self",
".",
"markup",
",",
"self",
".",
"markup_lines",
")",
"self",
".",
"markups",
".",
"append",
"(",
"m",
")",
"self",
".",
"markup",
"=",
"None",
"self",
".",
"markup_lines",
"=",
"[",
"]"
] | edf3810dcb211942d392a8637945871399b0650d |
test | ContentProcessor.process_content | process a block content and return a list of DocMarkup objects
corresponding to it | native/Vendor/FreeType/src/tools/docmaker/content.py | def process_content( self, content ):
"""process a block content and return a list of DocMarkup objects
corresponding to it"""
markup = None
markup_lines = []
first = 1
for line in content:
found = None
for t in re_markup_tags:
m = t.match( line )
if m:
found = string.lower( m.group( 1 ) )
prefix = len( m.group( 0 ) )
line = " " * prefix + line[prefix:] # remove markup from line
break
# is it the start of a new markup section ?
if found:
first = 0
self.add_markup() # add current markup content
self.markup = found
if len( string.strip( line ) ) > 0:
self.markup_lines.append( line )
elif first == 0:
self.markup_lines.append( line )
self.add_markup()
return self.markups | def process_content( self, content ):
"""process a block content and return a list of DocMarkup objects
corresponding to it"""
markup = None
markup_lines = []
first = 1
for line in content:
found = None
for t in re_markup_tags:
m = t.match( line )
if m:
found = string.lower( m.group( 1 ) )
prefix = len( m.group( 0 ) )
line = " " * prefix + line[prefix:] # remove markup from line
break
# is it the start of a new markup section ?
if found:
first = 0
self.add_markup() # add current markup content
self.markup = found
if len( string.strip( line ) ) > 0:
self.markup_lines.append( line )
elif first == 0:
self.markup_lines.append( line )
self.add_markup()
return self.markups | [
"process",
"a",
"block",
"content",
"and",
"return",
"a",
"list",
"of",
"DocMarkup",
"objects",
"corresponding",
"to",
"it"
] | aholkner/bacon | python | https://github.com/aholkner/bacon/blob/edf3810dcb211942d392a8637945871399b0650d/native/Vendor/FreeType/src/tools/docmaker/content.py#L389-L418 | [
"def",
"process_content",
"(",
"self",
",",
"content",
")",
":",
"markup",
"=",
"None",
"markup_lines",
"=",
"[",
"]",
"first",
"=",
"1",
"for",
"line",
"in",
"content",
":",
"found",
"=",
"None",
"for",
"t",
"in",
"re_markup_tags",
":",
"m",
"=",
"t",
".",
"match",
"(",
"line",
")",
"if",
"m",
":",
"found",
"=",
"string",
".",
"lower",
"(",
"m",
".",
"group",
"(",
"1",
")",
")",
"prefix",
"=",
"len",
"(",
"m",
".",
"group",
"(",
"0",
")",
")",
"line",
"=",
"\" \"",
"*",
"prefix",
"+",
"line",
"[",
"prefix",
":",
"]",
"# remove markup from line",
"break",
"# is it the start of a new markup section ?",
"if",
"found",
":",
"first",
"=",
"0",
"self",
".",
"add_markup",
"(",
")",
"# add current markup content",
"self",
".",
"markup",
"=",
"found",
"if",
"len",
"(",
"string",
".",
"strip",
"(",
"line",
")",
")",
">",
"0",
":",
"self",
".",
"markup_lines",
".",
"append",
"(",
"line",
")",
"elif",
"first",
"==",
"0",
":",
"self",
".",
"markup_lines",
".",
"append",
"(",
"line",
")",
"self",
".",
"add_markup",
"(",
")",
"return",
"self",
".",
"markups"
] | edf3810dcb211942d392a8637945871399b0650d |
test | DocBlock.get_markup | return the DocMarkup corresponding to a given tag in a block | native/Vendor/FreeType/src/tools/docmaker/content.py | def get_markup( self, tag_name ):
"""return the DocMarkup corresponding to a given tag in a block"""
for m in self.markups:
if m.tag == string.lower( tag_name ):
return m
return None | def get_markup( self, tag_name ):
"""return the DocMarkup corresponding to a given tag in a block"""
for m in self.markups:
if m.tag == string.lower( tag_name ):
return m
return None | [
"return",
"the",
"DocMarkup",
"corresponding",
"to",
"a",
"given",
"tag",
"in",
"a",
"block"
] | aholkner/bacon | python | https://github.com/aholkner/bacon/blob/edf3810dcb211942d392a8637945871399b0650d/native/Vendor/FreeType/src/tools/docmaker/content.py#L551-L556 | [
"def",
"get_markup",
"(",
"self",
",",
"tag_name",
")",
":",
"for",
"m",
"in",
"self",
".",
"markups",
":",
"if",
"m",
".",
"tag",
"==",
"string",
".",
"lower",
"(",
"tag_name",
")",
":",
"return",
"m",
"return",
"None"
] | edf3810dcb211942d392a8637945871399b0650d |
test | create_hosted_zone_writer | Forms an XML string that we'll send to Route53 in order to create
a new hosted zone.
:param Route53Connection connection: The connection instance used to
query the API.
:param str name: The name of the hosted zone to create. | route53/xml_generators/created_hosted_zone.py | def create_hosted_zone_writer(connection, name, caller_reference, comment):
"""
Forms an XML string that we'll send to Route53 in order to create
a new hosted zone.
:param Route53Connection connection: The connection instance used to
query the API.
:param str name: The name of the hosted zone to create.
"""
if not caller_reference:
caller_reference = str(uuid.uuid4())
e_root = etree.Element(
"CreateHostedZoneRequest",
xmlns=connection._xml_namespace
)
e_name = etree.SubElement(e_root, "Name")
e_name.text = name
e_caller_reference = etree.SubElement(e_root, "CallerReference")
e_caller_reference.text = caller_reference
if comment:
e_config = etree.SubElement(e_root, "HostedZoneConfig")
e_comment = etree.SubElement(e_config, "Comment")
e_comment.text = comment
e_tree = etree.ElementTree(element=e_root)
fobj = BytesIO()
# This writes bytes.
e_tree.write(fobj, xml_declaration=True, encoding='utf-8', method="xml")
return fobj.getvalue().decode('utf-8') | def create_hosted_zone_writer(connection, name, caller_reference, comment):
"""
Forms an XML string that we'll send to Route53 in order to create
a new hosted zone.
:param Route53Connection connection: The connection instance used to
query the API.
:param str name: The name of the hosted zone to create.
"""
if not caller_reference:
caller_reference = str(uuid.uuid4())
e_root = etree.Element(
"CreateHostedZoneRequest",
xmlns=connection._xml_namespace
)
e_name = etree.SubElement(e_root, "Name")
e_name.text = name
e_caller_reference = etree.SubElement(e_root, "CallerReference")
e_caller_reference.text = caller_reference
if comment:
e_config = etree.SubElement(e_root, "HostedZoneConfig")
e_comment = etree.SubElement(e_config, "Comment")
e_comment.text = comment
e_tree = etree.ElementTree(element=e_root)
fobj = BytesIO()
# This writes bytes.
e_tree.write(fobj, xml_declaration=True, encoding='utf-8', method="xml")
return fobj.getvalue().decode('utf-8') | [
"Forms",
"an",
"XML",
"string",
"that",
"we",
"ll",
"send",
"to",
"Route53",
"in",
"order",
"to",
"create",
"a",
"new",
"hosted",
"zone",
"."
] | gtaylor/python-route53 | python | https://github.com/gtaylor/python-route53/blob/b9fc7e258a79551c9ed61e4a71668b7f06f9e774/route53/xml_generators/created_hosted_zone.py#L5-L39 | [
"def",
"create_hosted_zone_writer",
"(",
"connection",
",",
"name",
",",
"caller_reference",
",",
"comment",
")",
":",
"if",
"not",
"caller_reference",
":",
"caller_reference",
"=",
"str",
"(",
"uuid",
".",
"uuid4",
"(",
")",
")",
"e_root",
"=",
"etree",
".",
"Element",
"(",
"\"CreateHostedZoneRequest\"",
",",
"xmlns",
"=",
"connection",
".",
"_xml_namespace",
")",
"e_name",
"=",
"etree",
".",
"SubElement",
"(",
"e_root",
",",
"\"Name\"",
")",
"e_name",
".",
"text",
"=",
"name",
"e_caller_reference",
"=",
"etree",
".",
"SubElement",
"(",
"e_root",
",",
"\"CallerReference\"",
")",
"e_caller_reference",
".",
"text",
"=",
"caller_reference",
"if",
"comment",
":",
"e_config",
"=",
"etree",
".",
"SubElement",
"(",
"e_root",
",",
"\"HostedZoneConfig\"",
")",
"e_comment",
"=",
"etree",
".",
"SubElement",
"(",
"e_config",
",",
"\"Comment\"",
")",
"e_comment",
".",
"text",
"=",
"comment",
"e_tree",
"=",
"etree",
".",
"ElementTree",
"(",
"element",
"=",
"e_root",
")",
"fobj",
"=",
"BytesIO",
"(",
")",
"# This writes bytes.",
"e_tree",
".",
"write",
"(",
"fobj",
",",
"xml_declaration",
"=",
"True",
",",
"encoding",
"=",
"'utf-8'",
",",
"method",
"=",
"\"xml\"",
")",
"return",
"fobj",
".",
"getvalue",
"(",
")",
".",
"decode",
"(",
"'utf-8'",
")"
] | b9fc7e258a79551c9ed61e4a71668b7f06f9e774 |
test | lock | Lock a file object 'safely'.
That means a failure to lock because the platform doesn't
support fcntl or filesystem locks is not considered a
failure. This call does block.
Returns whether or not the lock was successful, or
raises an exception in more extreme circumstances (full
lock table, invalid file). | mutagen/_util.py | def lock(fileobj):
"""Lock a file object 'safely'.
That means a failure to lock because the platform doesn't
support fcntl or filesystem locks is not considered a
failure. This call does block.
Returns whether or not the lock was successful, or
raises an exception in more extreme circumstances (full
lock table, invalid file).
"""
try:
import fcntl
except ImportError:
return False
else:
try:
fcntl.lockf(fileobj, fcntl.LOCK_EX)
except IOError:
# FIXME: There's possibly a lot of complicated
# logic that needs to go here in case the IOError
# is EACCES or EAGAIN.
return False
else:
return True | def lock(fileobj):
"""Lock a file object 'safely'.
That means a failure to lock because the platform doesn't
support fcntl or filesystem locks is not considered a
failure. This call does block.
Returns whether or not the lock was successful, or
raises an exception in more extreme circumstances (full
lock table, invalid file).
"""
try:
import fcntl
except ImportError:
return False
else:
try:
fcntl.lockf(fileobj, fcntl.LOCK_EX)
except IOError:
# FIXME: There's possibly a lot of complicated
# logic that needs to go here in case the IOError
# is EACCES or EAGAIN.
return False
else:
return True | [
"Lock",
"a",
"file",
"object",
"safely",
"."
] | LordSputnik/mutagen | python | https://github.com/LordSputnik/mutagen/blob/38e62c8dc35c72b16554f5dbe7c0fde91acc3411/mutagen/_util.py#L107-L132 | [
"def",
"lock",
"(",
"fileobj",
")",
":",
"try",
":",
"import",
"fcntl",
"except",
"ImportError",
":",
"return",
"False",
"else",
":",
"try",
":",
"fcntl",
".",
"lockf",
"(",
"fileobj",
",",
"fcntl",
".",
"LOCK_EX",
")",
"except",
"IOError",
":",
"# FIXME: There's possibly a lot of complicated",
"# logic that needs to go here in case the IOError",
"# is EACCES or EAGAIN.",
"return",
"False",
"else",
":",
"return",
"True"
] | 38e62c8dc35c72b16554f5dbe7c0fde91acc3411 |
test | insert_bytes | Insert size bytes of empty space starting at offset.
fobj must be an open file object, open rb+ or
equivalent. Mutagen tries to use mmap to resize the file, but
falls back to a significantly slower method if mmap fails. | mutagen/_util.py | def insert_bytes(fobj, size, offset, BUFFER_SIZE=2**16):
"""Insert size bytes of empty space starting at offset.
fobj must be an open file object, open rb+ or
equivalent. Mutagen tries to use mmap to resize the file, but
falls back to a significantly slower method if mmap fails.
"""
assert 0 < size
assert 0 <= offset
locked = False
fobj.seek(0, 2)
filesize = fobj.tell()
movesize = filesize - offset
fobj.write(b'\x00' * size)
fobj.flush()
try:
try:
import mmap
file_map = mmap.mmap(fobj.fileno(), filesize + size)
try:
file_map.move(offset + size, offset, movesize)
finally:
file_map.close()
except (ValueError, EnvironmentError, ImportError):
# handle broken mmap scenarios
locked = lock(fobj)
fobj.truncate(filesize)
fobj.seek(0, 2)
padsize = size
# Don't generate an enormous string if we need to pad
# the file out several megs.
while padsize:
addsize = min(BUFFER_SIZE, padsize)
fobj.write(b"\x00" * addsize)
padsize -= addsize
fobj.seek(filesize, 0)
while movesize:
# At the start of this loop, fobj is pointing at the end
# of the data we need to move, which is of movesize length.
thismove = min(BUFFER_SIZE, movesize)
# Seek back however much we're going to read this frame.
fobj.seek(-thismove, 1)
nextpos = fobj.tell()
# Read it, so we're back at the end.
data = fobj.read(thismove)
# Seek back to where we need to write it.
fobj.seek(-thismove + size, 1)
# Write it.
fobj.write(data)
# And seek back to the end of the unmoved data.
fobj.seek(nextpos)
movesize -= thismove
fobj.flush()
finally:
if locked:
unlock(fobj) | def insert_bytes(fobj, size, offset, BUFFER_SIZE=2**16):
"""Insert size bytes of empty space starting at offset.
fobj must be an open file object, open rb+ or
equivalent. Mutagen tries to use mmap to resize the file, but
falls back to a significantly slower method if mmap fails.
"""
assert 0 < size
assert 0 <= offset
locked = False
fobj.seek(0, 2)
filesize = fobj.tell()
movesize = filesize - offset
fobj.write(b'\x00' * size)
fobj.flush()
try:
try:
import mmap
file_map = mmap.mmap(fobj.fileno(), filesize + size)
try:
file_map.move(offset + size, offset, movesize)
finally:
file_map.close()
except (ValueError, EnvironmentError, ImportError):
# handle broken mmap scenarios
locked = lock(fobj)
fobj.truncate(filesize)
fobj.seek(0, 2)
padsize = size
# Don't generate an enormous string if we need to pad
# the file out several megs.
while padsize:
addsize = min(BUFFER_SIZE, padsize)
fobj.write(b"\x00" * addsize)
padsize -= addsize
fobj.seek(filesize, 0)
while movesize:
# At the start of this loop, fobj is pointing at the end
# of the data we need to move, which is of movesize length.
thismove = min(BUFFER_SIZE, movesize)
# Seek back however much we're going to read this frame.
fobj.seek(-thismove, 1)
nextpos = fobj.tell()
# Read it, so we're back at the end.
data = fobj.read(thismove)
# Seek back to where we need to write it.
fobj.seek(-thismove + size, 1)
# Write it.
fobj.write(data)
# And seek back to the end of the unmoved data.
fobj.seek(nextpos)
movesize -= thismove
fobj.flush()
finally:
if locked:
unlock(fobj) | [
"Insert",
"size",
"bytes",
"of",
"empty",
"space",
"starting",
"at",
"offset",
"."
] | LordSputnik/mutagen | python | https://github.com/LordSputnik/mutagen/blob/38e62c8dc35c72b16554f5dbe7c0fde91acc3411/mutagen/_util.py#L148-L207 | [
"def",
"insert_bytes",
"(",
"fobj",
",",
"size",
",",
"offset",
",",
"BUFFER_SIZE",
"=",
"2",
"**",
"16",
")",
":",
"assert",
"0",
"<",
"size",
"assert",
"0",
"<=",
"offset",
"locked",
"=",
"False",
"fobj",
".",
"seek",
"(",
"0",
",",
"2",
")",
"filesize",
"=",
"fobj",
".",
"tell",
"(",
")",
"movesize",
"=",
"filesize",
"-",
"offset",
"fobj",
".",
"write",
"(",
"b'\\x00'",
"*",
"size",
")",
"fobj",
".",
"flush",
"(",
")",
"try",
":",
"try",
":",
"import",
"mmap",
"file_map",
"=",
"mmap",
".",
"mmap",
"(",
"fobj",
".",
"fileno",
"(",
")",
",",
"filesize",
"+",
"size",
")",
"try",
":",
"file_map",
".",
"move",
"(",
"offset",
"+",
"size",
",",
"offset",
",",
"movesize",
")",
"finally",
":",
"file_map",
".",
"close",
"(",
")",
"except",
"(",
"ValueError",
",",
"EnvironmentError",
",",
"ImportError",
")",
":",
"# handle broken mmap scenarios",
"locked",
"=",
"lock",
"(",
"fobj",
")",
"fobj",
".",
"truncate",
"(",
"filesize",
")",
"fobj",
".",
"seek",
"(",
"0",
",",
"2",
")",
"padsize",
"=",
"size",
"# Don't generate an enormous string if we need to pad",
"# the file out several megs.",
"while",
"padsize",
":",
"addsize",
"=",
"min",
"(",
"BUFFER_SIZE",
",",
"padsize",
")",
"fobj",
".",
"write",
"(",
"b\"\\x00\"",
"*",
"addsize",
")",
"padsize",
"-=",
"addsize",
"fobj",
".",
"seek",
"(",
"filesize",
",",
"0",
")",
"while",
"movesize",
":",
"# At the start of this loop, fobj is pointing at the end",
"# of the data we need to move, which is of movesize length.",
"thismove",
"=",
"min",
"(",
"BUFFER_SIZE",
",",
"movesize",
")",
"# Seek back however much we're going to read this frame.",
"fobj",
".",
"seek",
"(",
"-",
"thismove",
",",
"1",
")",
"nextpos",
"=",
"fobj",
".",
"tell",
"(",
")",
"# Read it, so we're back at the end.",
"data",
"=",
"fobj",
".",
"read",
"(",
"thismove",
")",
"# Seek back to where we need to write it.",
"fobj",
".",
"seek",
"(",
"-",
"thismove",
"+",
"size",
",",
"1",
")",
"# Write it.",
"fobj",
".",
"write",
"(",
"data",
")",
"# And seek back to the end of the unmoved data.",
"fobj",
".",
"seek",
"(",
"nextpos",
")",
"movesize",
"-=",
"thismove",
"fobj",
".",
"flush",
"(",
")",
"finally",
":",
"if",
"locked",
":",
"unlock",
"(",
"fobj",
")"
] | 38e62c8dc35c72b16554f5dbe7c0fde91acc3411 |
test | delete_bytes | Delete size bytes of empty space starting at offset.
fobj must be an open file object, open rb+ or
equivalent. Mutagen tries to use mmap to resize the file, but
falls back to a significantly slower method if mmap fails. | mutagen/_util.py | def delete_bytes(fobj, size, offset, BUFFER_SIZE=2**16):
"""Delete size bytes of empty space starting at offset.
fobj must be an open file object, open rb+ or
equivalent. Mutagen tries to use mmap to resize the file, but
falls back to a significantly slower method if mmap fails.
"""
locked = False
assert 0 < size
assert 0 <= offset
fobj.seek(0, 2)
filesize = fobj.tell()
movesize = filesize - offset - size
assert 0 <= movesize
try:
if movesize > 0:
fobj.flush()
try:
import mmap
file_map = mmap.mmap(fobj.fileno(), filesize)
try:
file_map.move(offset, offset + size, movesize)
finally:
file_map.close()
except (ValueError, EnvironmentError, ImportError):
# handle broken mmap scenarios
locked = lock(fobj)
fobj.seek(offset + size)
buf = fobj.read(BUFFER_SIZE)
while buf:
fobj.seek(offset)
fobj.write(buf)
offset += len(buf)
fobj.seek(offset + size)
buf = fobj.read(BUFFER_SIZE)
fobj.truncate(filesize - size)
fobj.flush()
finally:
if locked:
unlock(fobj) | def delete_bytes(fobj, size, offset, BUFFER_SIZE=2**16):
"""Delete size bytes of empty space starting at offset.
fobj must be an open file object, open rb+ or
equivalent. Mutagen tries to use mmap to resize the file, but
falls back to a significantly slower method if mmap fails.
"""
locked = False
assert 0 < size
assert 0 <= offset
fobj.seek(0, 2)
filesize = fobj.tell()
movesize = filesize - offset - size
assert 0 <= movesize
try:
if movesize > 0:
fobj.flush()
try:
import mmap
file_map = mmap.mmap(fobj.fileno(), filesize)
try:
file_map.move(offset, offset + size, movesize)
finally:
file_map.close()
except (ValueError, EnvironmentError, ImportError):
# handle broken mmap scenarios
locked = lock(fobj)
fobj.seek(offset + size)
buf = fobj.read(BUFFER_SIZE)
while buf:
fobj.seek(offset)
fobj.write(buf)
offset += len(buf)
fobj.seek(offset + size)
buf = fobj.read(BUFFER_SIZE)
fobj.truncate(filesize - size)
fobj.flush()
finally:
if locked:
unlock(fobj) | [
"Delete",
"size",
"bytes",
"of",
"empty",
"space",
"starting",
"at",
"offset",
"."
] | LordSputnik/mutagen | python | https://github.com/LordSputnik/mutagen/blob/38e62c8dc35c72b16554f5dbe7c0fde91acc3411/mutagen/_util.py#L210-L250 | [
"def",
"delete_bytes",
"(",
"fobj",
",",
"size",
",",
"offset",
",",
"BUFFER_SIZE",
"=",
"2",
"**",
"16",
")",
":",
"locked",
"=",
"False",
"assert",
"0",
"<",
"size",
"assert",
"0",
"<=",
"offset",
"fobj",
".",
"seek",
"(",
"0",
",",
"2",
")",
"filesize",
"=",
"fobj",
".",
"tell",
"(",
")",
"movesize",
"=",
"filesize",
"-",
"offset",
"-",
"size",
"assert",
"0",
"<=",
"movesize",
"try",
":",
"if",
"movesize",
">",
"0",
":",
"fobj",
".",
"flush",
"(",
")",
"try",
":",
"import",
"mmap",
"file_map",
"=",
"mmap",
".",
"mmap",
"(",
"fobj",
".",
"fileno",
"(",
")",
",",
"filesize",
")",
"try",
":",
"file_map",
".",
"move",
"(",
"offset",
",",
"offset",
"+",
"size",
",",
"movesize",
")",
"finally",
":",
"file_map",
".",
"close",
"(",
")",
"except",
"(",
"ValueError",
",",
"EnvironmentError",
",",
"ImportError",
")",
":",
"# handle broken mmap scenarios",
"locked",
"=",
"lock",
"(",
"fobj",
")",
"fobj",
".",
"seek",
"(",
"offset",
"+",
"size",
")",
"buf",
"=",
"fobj",
".",
"read",
"(",
"BUFFER_SIZE",
")",
"while",
"buf",
":",
"fobj",
".",
"seek",
"(",
"offset",
")",
"fobj",
".",
"write",
"(",
"buf",
")",
"offset",
"+=",
"len",
"(",
"buf",
")",
"fobj",
".",
"seek",
"(",
"offset",
"+",
"size",
")",
"buf",
"=",
"fobj",
".",
"read",
"(",
"BUFFER_SIZE",
")",
"fobj",
".",
"truncate",
"(",
"filesize",
"-",
"size",
")",
"fobj",
".",
"flush",
"(",
")",
"finally",
":",
"if",
"locked",
":",
"unlock",
"(",
"fobj",
")"
] | 38e62c8dc35c72b16554f5dbe7c0fde91acc3411 |
test | utf8 | Convert a basestring to a valid UTF-8 str. | mutagen/_util.py | def utf8(data):
"""Convert a basestring to a valid UTF-8 str."""
if isinstance(data, bytes):
return data.decode("utf-8", "replace").encode("utf-8")
elif isinstance(data, text_type):
return data.encode("utf-8")
else:
raise TypeError("only unicode/bytes types can be converted to UTF-8") | def utf8(data):
"""Convert a basestring to a valid UTF-8 str."""
if isinstance(data, bytes):
return data.decode("utf-8", "replace").encode("utf-8")
elif isinstance(data, text_type):
return data.encode("utf-8")
else:
raise TypeError("only unicode/bytes types can be converted to UTF-8") | [
"Convert",
"a",
"basestring",
"to",
"a",
"valid",
"UTF",
"-",
"8",
"str",
"."
] | LordSputnik/mutagen | python | https://github.com/LordSputnik/mutagen/blob/38e62c8dc35c72b16554f5dbe7c0fde91acc3411/mutagen/_util.py#L253-L261 | [
"def",
"utf8",
"(",
"data",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"bytes",
")",
":",
"return",
"data",
".",
"decode",
"(",
"\"utf-8\"",
",",
"\"replace\"",
")",
".",
"encode",
"(",
"\"utf-8\"",
")",
"elif",
"isinstance",
"(",
"data",
",",
"text_type",
")",
":",
"return",
"data",
".",
"encode",
"(",
"\"utf-8\"",
")",
"else",
":",
"raise",
"TypeError",
"(",
"\"only unicode/bytes types can be converted to UTF-8\"",
")"
] | 38e62c8dc35c72b16554f5dbe7c0fde91acc3411 |
test | ChangeSet.add_change | Adds a change to this change set.
:param str action: Must be one of either 'CREATE' or 'DELETE'.
:param resource_record_set.ResourceRecordSet record_set: The
ResourceRecordSet object that was created or deleted. | route53/change_set.py | def add_change(self, action, record_set):
"""
Adds a change to this change set.
:param str action: Must be one of either 'CREATE' or 'DELETE'.
:param resource_record_set.ResourceRecordSet record_set: The
ResourceRecordSet object that was created or deleted.
"""
action = action.upper()
if action not in ['CREATE', 'DELETE']:
raise Route53Error("action must be one of 'CREATE' or 'DELETE'")
change_tuple = (action, record_set)
if action == 'CREATE':
self.creations.append(change_tuple)
else:
self.deletions.append(change_tuple) | def add_change(self, action, record_set):
"""
Adds a change to this change set.
:param str action: Must be one of either 'CREATE' or 'DELETE'.
:param resource_record_set.ResourceRecordSet record_set: The
ResourceRecordSet object that was created or deleted.
"""
action = action.upper()
if action not in ['CREATE', 'DELETE']:
raise Route53Error("action must be one of 'CREATE' or 'DELETE'")
change_tuple = (action, record_set)
if action == 'CREATE':
self.creations.append(change_tuple)
else:
self.deletions.append(change_tuple) | [
"Adds",
"a",
"change",
"to",
"this",
"change",
"set",
"."
] | gtaylor/python-route53 | python | https://github.com/gtaylor/python-route53/blob/b9fc7e258a79551c9ed61e4a71668b7f06f9e774/route53/change_set.py#L22-L41 | [
"def",
"add_change",
"(",
"self",
",",
"action",
",",
"record_set",
")",
":",
"action",
"=",
"action",
".",
"upper",
"(",
")",
"if",
"action",
"not",
"in",
"[",
"'CREATE'",
",",
"'DELETE'",
"]",
":",
"raise",
"Route53Error",
"(",
"\"action must be one of 'CREATE' or 'DELETE'\"",
")",
"change_tuple",
"=",
"(",
"action",
",",
"record_set",
")",
"if",
"action",
"==",
"'CREATE'",
":",
"self",
".",
"creations",
".",
"append",
"(",
"change_tuple",
")",
"else",
":",
"self",
".",
"deletions",
".",
"append",
"(",
"change_tuple",
")"
] | b9fc7e258a79551c9ed61e4a71668b7f06f9e774 |
test | parse_change_info | Parses a ChangeInfo tag. Seen in CreateHostedZone, DeleteHostedZone,
and ChangeResourceRecordSetsRequest.
:param lxml.etree._Element e_change_info: A ChangeInfo element.
:rtype: dict
:returns: A dict representation of the change info. | route53/xml_parsers/common_change_info.py | def parse_change_info(e_change_info):
"""
Parses a ChangeInfo tag. Seen in CreateHostedZone, DeleteHostedZone,
and ChangeResourceRecordSetsRequest.
:param lxml.etree._Element e_change_info: A ChangeInfo element.
:rtype: dict
:returns: A dict representation of the change info.
"""
if e_change_info is None:
return e_change_info
status = e_change_info.find('./{*}Status').text
submitted_at = e_change_info.find('./{*}SubmittedAt').text
submitted_at = parse_iso_8601_time_str(submitted_at)
return {
'request_id': id,
'request_status': status,
'request_submitted_at': submitted_at
} | def parse_change_info(e_change_info):
"""
Parses a ChangeInfo tag. Seen in CreateHostedZone, DeleteHostedZone,
and ChangeResourceRecordSetsRequest.
:param lxml.etree._Element e_change_info: A ChangeInfo element.
:rtype: dict
:returns: A dict representation of the change info.
"""
if e_change_info is None:
return e_change_info
status = e_change_info.find('./{*}Status').text
submitted_at = e_change_info.find('./{*}SubmittedAt').text
submitted_at = parse_iso_8601_time_str(submitted_at)
return {
'request_id': id,
'request_status': status,
'request_submitted_at': submitted_at
} | [
"Parses",
"a",
"ChangeInfo",
"tag",
".",
"Seen",
"in",
"CreateHostedZone",
"DeleteHostedZone",
"and",
"ChangeResourceRecordSetsRequest",
"."
] | gtaylor/python-route53 | python | https://github.com/gtaylor/python-route53/blob/b9fc7e258a79551c9ed61e4a71668b7f06f9e774/route53/xml_parsers/common_change_info.py#L8-L29 | [
"def",
"parse_change_info",
"(",
"e_change_info",
")",
":",
"if",
"e_change_info",
"is",
"None",
":",
"return",
"e_change_info",
"status",
"=",
"e_change_info",
".",
"find",
"(",
"'./{*}Status'",
")",
".",
"text",
"submitted_at",
"=",
"e_change_info",
".",
"find",
"(",
"'./{*}SubmittedAt'",
")",
".",
"text",
"submitted_at",
"=",
"parse_iso_8601_time_str",
"(",
"submitted_at",
")",
"return",
"{",
"'request_id'",
":",
"id",
",",
"'request_status'",
":",
"status",
",",
"'request_submitted_at'",
":",
"submitted_at",
"}"
] | b9fc7e258a79551c9ed61e4a71668b7f06f9e774 |
test | get_resource_path | Get a path to the given filename to load as a resource. All non-absolute filenames passed to
:class:`Image`, :class:`Font`, :class:`Sound`, etc are transformed through this function.
:param str filename: a relative path to a resource file
:return str: an absolute path to the file | bacon/resource.py | def get_resource_path(filename):
'''Get a path to the given filename to load as a resource. All non-absolute filenames passed to
:class:`Image`, :class:`Font`, :class:`Sound`, etc are transformed through this function.
:param str filename: a relative path to a resource file
:return str: an absolute path to the file
'''
path = os.path.join(resource_dir, filename)
if _dll_dir and not os.path.exists(path):
path = os.path.join(_dll_dir, filename)
return path | def get_resource_path(filename):
'''Get a path to the given filename to load as a resource. All non-absolute filenames passed to
:class:`Image`, :class:`Font`, :class:`Sound`, etc are transformed through this function.
:param str filename: a relative path to a resource file
:return str: an absolute path to the file
'''
path = os.path.join(resource_dir, filename)
if _dll_dir and not os.path.exists(path):
path = os.path.join(_dll_dir, filename)
return path | [
"Get",
"a",
"path",
"to",
"the",
"given",
"filename",
"to",
"load",
"as",
"a",
"resource",
".",
"All",
"non",
"-",
"absolute",
"filenames",
"passed",
"to",
":",
"class",
":",
"Image",
":",
"class",
":",
"Font",
":",
"class",
":",
"Sound",
"etc",
"are",
"transformed",
"through",
"this",
"function",
"."
] | aholkner/bacon | python | https://github.com/aholkner/bacon/blob/edf3810dcb211942d392a8637945871399b0650d/bacon/resource.py#L25-L35 | [
"def",
"get_resource_path",
"(",
"filename",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"resource_dir",
",",
"filename",
")",
"if",
"_dll_dir",
"and",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"_dll_dir",
",",
"filename",
")",
"return",
"path"
] | edf3810dcb211942d392a8637945871399b0650d |
test | Font.get_glyph | Retrieves a :class:`Glyph` that renders the given character.
:param char: the character (a string) | bacon/font.py | def get_glyph(self, char):
'''Retrieves a :class:`Glyph` that renders the given character.
:param char: the character (a string)
'''
try:
return self._glyphs[char]
except KeyError:
glyph = self._font_file.get_glyph(self._size, self._content_scale, char, self._flags)
self._glyphs[char] = glyph
return glyph | def get_glyph(self, char):
'''Retrieves a :class:`Glyph` that renders the given character.
:param char: the character (a string)
'''
try:
return self._glyphs[char]
except KeyError:
glyph = self._font_file.get_glyph(self._size, self._content_scale, char, self._flags)
self._glyphs[char] = glyph
return glyph | [
"Retrieves",
"a",
":",
"class",
":",
"Glyph",
"that",
"renders",
"the",
"given",
"character",
"."
] | aholkner/bacon | python | https://github.com/aholkner/bacon/blob/edf3810dcb211942d392a8637945871399b0650d/bacon/font.py#L200-L210 | [
"def",
"get_glyph",
"(",
"self",
",",
"char",
")",
":",
"try",
":",
"return",
"self",
".",
"_glyphs",
"[",
"char",
"]",
"except",
"KeyError",
":",
"glyph",
"=",
"self",
".",
"_font_file",
".",
"get_glyph",
"(",
"self",
".",
"_size",
",",
"self",
".",
"_content_scale",
",",
"char",
",",
"self",
".",
"_flags",
")",
"self",
".",
"_glyphs",
"[",
"char",
"]",
"=",
"glyph",
"return",
"glyph"
] | edf3810dcb211942d392a8637945871399b0650d |
test | Font.measure_string | Calculates the width of the given string in this font.
:param str: the string to measure
:return float: width of the string, in pixels | bacon/font.py | def measure_string(self, str):
'''Calculates the width of the given string in this font.
:param str: the string to measure
:return float: width of the string, in pixels
'''
style = bacon.text.Style(self)
run = bacon.text.GlyphRun(style, str)
glyph_layout = bacon.text.GlyphLayout([run], 0, 0)
return glyph_layout.content_width | def measure_string(self, str):
'''Calculates the width of the given string in this font.
:param str: the string to measure
:return float: width of the string, in pixels
'''
style = bacon.text.Style(self)
run = bacon.text.GlyphRun(style, str)
glyph_layout = bacon.text.GlyphLayout([run], 0, 0)
return glyph_layout.content_width | [
"Calculates",
"the",
"width",
"of",
"the",
"given",
"string",
"in",
"this",
"font",
"."
] | aholkner/bacon | python | https://github.com/aholkner/bacon/blob/edf3810dcb211942d392a8637945871399b0650d/bacon/font.py#L219-L228 | [
"def",
"measure_string",
"(",
"self",
",",
"str",
")",
":",
"style",
"=",
"bacon",
".",
"text",
".",
"Style",
"(",
"self",
")",
"run",
"=",
"bacon",
".",
"text",
".",
"GlyphRun",
"(",
"style",
",",
"str",
")",
"glyph_layout",
"=",
"bacon",
".",
"text",
".",
"GlyphLayout",
"(",
"[",
"run",
"]",
",",
"0",
",",
"0",
")",
"return",
"glyph_layout",
".",
"content_width"
] | edf3810dcb211942d392a8637945871399b0650d |
test | ResourceRecordSet.is_modified | Determines whether this record set has been modified since the
last retrieval or save.
:rtype: bool
:returns: ``True` if the record set has been modified,
and ``False`` if not. | route53/resource_record_set.py | def is_modified(self):
"""
Determines whether this record set has been modified since the
last retrieval or save.
:rtype: bool
:returns: ``True` if the record set has been modified,
and ``False`` if not.
"""
for key, val in self._initial_vals.items():
if getattr(self, key) != val:
# One of the initial values doesn't match, we know
# this object has been touched.
return True
return False | def is_modified(self):
"""
Determines whether this record set has been modified since the
last retrieval or save.
:rtype: bool
:returns: ``True` if the record set has been modified,
and ``False`` if not.
"""
for key, val in self._initial_vals.items():
if getattr(self, key) != val:
# One of the initial values doesn't match, we know
# this object has been touched.
return True
return False | [
"Determines",
"whether",
"this",
"record",
"set",
"has",
"been",
"modified",
"since",
"the",
"last",
"retrieval",
"or",
"save",
"."
] | gtaylor/python-route53 | python | https://github.com/gtaylor/python-route53/blob/b9fc7e258a79551c9ed61e4a71668b7f06f9e774/route53/resource_record_set.py#L82-L98 | [
"def",
"is_modified",
"(",
"self",
")",
":",
"for",
"key",
",",
"val",
"in",
"self",
".",
"_initial_vals",
".",
"items",
"(",
")",
":",
"if",
"getattr",
"(",
"self",
",",
"key",
")",
"!=",
"val",
":",
"# One of the initial values doesn't match, we know",
"# this object has been touched.",
"return",
"True",
"return",
"False"
] | b9fc7e258a79551c9ed61e4a71668b7f06f9e774 |
test | ResourceRecordSet.delete | Deletes this record set. | route53/resource_record_set.py | def delete(self):
"""
Deletes this record set.
"""
cset = ChangeSet(connection=self.connection, hosted_zone_id=self.zone_id)
cset.add_change('DELETE', self)
return self.connection._change_resource_record_sets(cset) | def delete(self):
"""
Deletes this record set.
"""
cset = ChangeSet(connection=self.connection, hosted_zone_id=self.zone_id)
cset.add_change('DELETE', self)
return self.connection._change_resource_record_sets(cset) | [
"Deletes",
"this",
"record",
"set",
"."
] | gtaylor/python-route53 | python | https://github.com/gtaylor/python-route53/blob/b9fc7e258a79551c9ed61e4a71668b7f06f9e774/route53/resource_record_set.py#L100-L108 | [
"def",
"delete",
"(",
"self",
")",
":",
"cset",
"=",
"ChangeSet",
"(",
"connection",
"=",
"self",
".",
"connection",
",",
"hosted_zone_id",
"=",
"self",
".",
"zone_id",
")",
"cset",
".",
"add_change",
"(",
"'DELETE'",
",",
"self",
")",
"return",
"self",
".",
"connection",
".",
"_change_resource_record_sets",
"(",
"cset",
")"
] | b9fc7e258a79551c9ed61e4a71668b7f06f9e774 |
test | ResourceRecordSet.save | Saves any changes to this record set. | route53/resource_record_set.py | def save(self):
"""
Saves any changes to this record set.
"""
cset = ChangeSet(connection=self.connection, hosted_zone_id=self.zone_id)
# Record sets can't actually be modified. You have to delete the
# existing one and create a new one. Since this happens within a single
# change set, it appears that the values were modified, when instead
# the whole thing is replaced.
cset.add_change('DELETE', self)
cset.add_change('CREATE', self)
retval = self.connection._change_resource_record_sets(cset)
# Now copy the current attribute values on this instance to
# the initial_vals dict. This will re-set the modification tracking.
for key, val in self._initial_vals.items():
self._initial_vals[key] = getattr(self, key)
return retval | def save(self):
"""
Saves any changes to this record set.
"""
cset = ChangeSet(connection=self.connection, hosted_zone_id=self.zone_id)
# Record sets can't actually be modified. You have to delete the
# existing one and create a new one. Since this happens within a single
# change set, it appears that the values were modified, when instead
# the whole thing is replaced.
cset.add_change('DELETE', self)
cset.add_change('CREATE', self)
retval = self.connection._change_resource_record_sets(cset)
# Now copy the current attribute values on this instance to
# the initial_vals dict. This will re-set the modification tracking.
for key, val in self._initial_vals.items():
self._initial_vals[key] = getattr(self, key)
return retval | [
"Saves",
"any",
"changes",
"to",
"this",
"record",
"set",
"."
] | gtaylor/python-route53 | python | https://github.com/gtaylor/python-route53/blob/b9fc7e258a79551c9ed61e4a71668b7f06f9e774/route53/resource_record_set.py#L110-L129 | [
"def",
"save",
"(",
"self",
")",
":",
"cset",
"=",
"ChangeSet",
"(",
"connection",
"=",
"self",
".",
"connection",
",",
"hosted_zone_id",
"=",
"self",
".",
"zone_id",
")",
"# Record sets can't actually be modified. You have to delete the",
"# existing one and create a new one. Since this happens within a single",
"# change set, it appears that the values were modified, when instead",
"# the whole thing is replaced.",
"cset",
".",
"add_change",
"(",
"'DELETE'",
",",
"self",
")",
"cset",
".",
"add_change",
"(",
"'CREATE'",
",",
"self",
")",
"retval",
"=",
"self",
".",
"connection",
".",
"_change_resource_record_sets",
"(",
"cset",
")",
"# Now copy the current attribute values on this instance to",
"# the initial_vals dict. This will re-set the modification tracking.",
"for",
"key",
",",
"val",
"in",
"self",
".",
"_initial_vals",
".",
"items",
"(",
")",
":",
"self",
".",
"_initial_vals",
"[",
"key",
"]",
"=",
"getattr",
"(",
"self",
",",
"key",
")",
"return",
"retval"
] | b9fc7e258a79551c9ed61e4a71668b7f06f9e774 |
test | delete | Remove tags from a file.
Keyword arguments:
* delete_v1 -- delete any ID3v1 tag
* delete_v2 -- delete any ID3v2 tag | mutagen/id3.py | def delete(filename, delete_v1=True, delete_v2=True):
"""Remove tags from a file.
Keyword arguments:
* delete_v1 -- delete any ID3v1 tag
* delete_v2 -- delete any ID3v2 tag
"""
f = open(filename, 'rb+')
if delete_v1:
try:
f.seek(-128, 2)
except IOError:
pass
else:
if f.read(3) == b'TAG':
f.seek(-128, 2)
f.truncate()
# technically an insize=0 tag is invalid, but we delete it anyway
# (primarily because we used to write it)
if delete_v2:
f.seek(0, 0)
idata = f.read(10)
try:
id3, vmaj, vrev, flags, insize = unpack('>3sBBB4s', idata)
except struct.error:
id3, insize = b'', -1
insize = BitPaddedInt(insize)
if id3 == b'ID3' and insize >= 0:
delete_bytes(f, insize + 10, 0) | def delete(filename, delete_v1=True, delete_v2=True):
"""Remove tags from a file.
Keyword arguments:
* delete_v1 -- delete any ID3v1 tag
* delete_v2 -- delete any ID3v2 tag
"""
f = open(filename, 'rb+')
if delete_v1:
try:
f.seek(-128, 2)
except IOError:
pass
else:
if f.read(3) == b'TAG':
f.seek(-128, 2)
f.truncate()
# technically an insize=0 tag is invalid, but we delete it anyway
# (primarily because we used to write it)
if delete_v2:
f.seek(0, 0)
idata = f.read(10)
try:
id3, vmaj, vrev, flags, insize = unpack('>3sBBB4s', idata)
except struct.error:
id3, insize = b'', -1
insize = BitPaddedInt(insize)
if id3 == b'ID3' and insize >= 0:
delete_bytes(f, insize + 10, 0) | [
"Remove",
"tags",
"from",
"a",
"file",
"."
] | LordSputnik/mutagen | python | https://github.com/LordSputnik/mutagen/blob/38e62c8dc35c72b16554f5dbe7c0fde91acc3411/mutagen/id3.py#L739-L771 | [
"def",
"delete",
"(",
"filename",
",",
"delete_v1",
"=",
"True",
",",
"delete_v2",
"=",
"True",
")",
":",
"f",
"=",
"open",
"(",
"filename",
",",
"'rb+'",
")",
"if",
"delete_v1",
":",
"try",
":",
"f",
".",
"seek",
"(",
"-",
"128",
",",
"2",
")",
"except",
"IOError",
":",
"pass",
"else",
":",
"if",
"f",
".",
"read",
"(",
"3",
")",
"==",
"b'TAG'",
":",
"f",
".",
"seek",
"(",
"-",
"128",
",",
"2",
")",
"f",
".",
"truncate",
"(",
")",
"# technically an insize=0 tag is invalid, but we delete it anyway",
"# (primarily because we used to write it)",
"if",
"delete_v2",
":",
"f",
".",
"seek",
"(",
"0",
",",
"0",
")",
"idata",
"=",
"f",
".",
"read",
"(",
"10",
")",
"try",
":",
"id3",
",",
"vmaj",
",",
"vrev",
",",
"flags",
",",
"insize",
"=",
"unpack",
"(",
"'>3sBBB4s'",
",",
"idata",
")",
"except",
"struct",
".",
"error",
":",
"id3",
",",
"insize",
"=",
"b''",
",",
"-",
"1",
"insize",
"=",
"BitPaddedInt",
"(",
"insize",
")",
"if",
"id3",
"==",
"b'ID3'",
"and",
"insize",
">=",
"0",
":",
"delete_bytes",
"(",
"f",
",",
"insize",
"+",
"10",
",",
"0",
")"
] | 38e62c8dc35c72b16554f5dbe7c0fde91acc3411 |
test | ParseID3v1 | Parse an ID3v1 tag, returning a list of ID3v2.4 frames. | mutagen/id3.py | def ParseID3v1(data):
"""Parse an ID3v1 tag, returning a list of ID3v2.4 frames."""
try:
data = data[data.index(b'TAG'):]
except ValueError:
return None
if 128 < len(data) or len(data) < 124:
return None
# Issue #69 - Previous versions of Mutagen, when encountering
# out-of-spec TDRC and TYER frames of less than four characters,
# wrote only the characters available - e.g. "1" or "" - into the
# year field. To parse those, reduce the size of the year field.
# Amazingly, "0s" works as a struct format string.
unpack_fmt = "3s30s30s30s%ds29sBB" % (len(data) - 124)
try:
tag, title, artist, album, year, comment, track, genre = unpack(
unpack_fmt, data)
except StructError:
return None
if tag != b"TAG":
return None
def fix(data):
return data.split(b'\x00')[0].strip().decode('latin1')
title, artist, album, year, comment = map(
fix, [title, artist, album, year, comment])
frames = {}
if title:
frames['TIT2'] = TIT2(encoding=0, text=title)
if artist:
frames['TPE1'] = TPE1(encoding=0, text=[artist])
if album:
frames['TALB'] = TALB(encoding=0, text=album)
if year:
frames['TDRC'] = TDRC(encoding=0, text=year)
if comment:
frames['COMM'] = COMM(encoding=0, lang='eng', desc="ID3v1 Comment",
text=comment)
# Don't read a track number if it looks like the comment was
# padded with spaces instead of nulls (thanks, WinAmp).
if track and ((track != 32) or (data[-3] == b'\x00'[0])):
frames['TRCK'] = TRCK(encoding=0, text=str(track))
if genre != 255:
frames['TCON'] = TCON(encoding=0, text=str(genre))
return frames | def ParseID3v1(data):
"""Parse an ID3v1 tag, returning a list of ID3v2.4 frames."""
try:
data = data[data.index(b'TAG'):]
except ValueError:
return None
if 128 < len(data) or len(data) < 124:
return None
# Issue #69 - Previous versions of Mutagen, when encountering
# out-of-spec TDRC and TYER frames of less than four characters,
# wrote only the characters available - e.g. "1" or "" - into the
# year field. To parse those, reduce the size of the year field.
# Amazingly, "0s" works as a struct format string.
unpack_fmt = "3s30s30s30s%ds29sBB" % (len(data) - 124)
try:
tag, title, artist, album, year, comment, track, genre = unpack(
unpack_fmt, data)
except StructError:
return None
if tag != b"TAG":
return None
def fix(data):
return data.split(b'\x00')[0].strip().decode('latin1')
title, artist, album, year, comment = map(
fix, [title, artist, album, year, comment])
frames = {}
if title:
frames['TIT2'] = TIT2(encoding=0, text=title)
if artist:
frames['TPE1'] = TPE1(encoding=0, text=[artist])
if album:
frames['TALB'] = TALB(encoding=0, text=album)
if year:
frames['TDRC'] = TDRC(encoding=0, text=year)
if comment:
frames['COMM'] = COMM(encoding=0, lang='eng', desc="ID3v1 Comment",
text=comment)
# Don't read a track number if it looks like the comment was
# padded with spaces instead of nulls (thanks, WinAmp).
if track and ((track != 32) or (data[-3] == b'\x00'[0])):
frames['TRCK'] = TRCK(encoding=0, text=str(track))
if genre != 255:
frames['TCON'] = TCON(encoding=0, text=str(genre))
return frames | [
"Parse",
"an",
"ID3v1",
"tag",
"returning",
"a",
"list",
"of",
"ID3v2",
".",
"4",
"frames",
"."
] | LordSputnik/mutagen | python | https://github.com/LordSputnik/mutagen/blob/38e62c8dc35c72b16554f5dbe7c0fde91acc3411/mutagen/id3.py#L779-L830 | [
"def",
"ParseID3v1",
"(",
"data",
")",
":",
"try",
":",
"data",
"=",
"data",
"[",
"data",
".",
"index",
"(",
"b'TAG'",
")",
":",
"]",
"except",
"ValueError",
":",
"return",
"None",
"if",
"128",
"<",
"len",
"(",
"data",
")",
"or",
"len",
"(",
"data",
")",
"<",
"124",
":",
"return",
"None",
"# Issue #69 - Previous versions of Mutagen, when encountering",
"# out-of-spec TDRC and TYER frames of less than four characters,",
"# wrote only the characters available - e.g. \"1\" or \"\" - into the",
"# year field. To parse those, reduce the size of the year field.",
"# Amazingly, \"0s\" works as a struct format string.",
"unpack_fmt",
"=",
"\"3s30s30s30s%ds29sBB\"",
"%",
"(",
"len",
"(",
"data",
")",
"-",
"124",
")",
"try",
":",
"tag",
",",
"title",
",",
"artist",
",",
"album",
",",
"year",
",",
"comment",
",",
"track",
",",
"genre",
"=",
"unpack",
"(",
"unpack_fmt",
",",
"data",
")",
"except",
"StructError",
":",
"return",
"None",
"if",
"tag",
"!=",
"b\"TAG\"",
":",
"return",
"None",
"def",
"fix",
"(",
"data",
")",
":",
"return",
"data",
".",
"split",
"(",
"b'\\x00'",
")",
"[",
"0",
"]",
".",
"strip",
"(",
")",
".",
"decode",
"(",
"'latin1'",
")",
"title",
",",
"artist",
",",
"album",
",",
"year",
",",
"comment",
"=",
"map",
"(",
"fix",
",",
"[",
"title",
",",
"artist",
",",
"album",
",",
"year",
",",
"comment",
"]",
")",
"frames",
"=",
"{",
"}",
"if",
"title",
":",
"frames",
"[",
"'TIT2'",
"]",
"=",
"TIT2",
"(",
"encoding",
"=",
"0",
",",
"text",
"=",
"title",
")",
"if",
"artist",
":",
"frames",
"[",
"'TPE1'",
"]",
"=",
"TPE1",
"(",
"encoding",
"=",
"0",
",",
"text",
"=",
"[",
"artist",
"]",
")",
"if",
"album",
":",
"frames",
"[",
"'TALB'",
"]",
"=",
"TALB",
"(",
"encoding",
"=",
"0",
",",
"text",
"=",
"album",
")",
"if",
"year",
":",
"frames",
"[",
"'TDRC'",
"]",
"=",
"TDRC",
"(",
"encoding",
"=",
"0",
",",
"text",
"=",
"year",
")",
"if",
"comment",
":",
"frames",
"[",
"'COMM'",
"]",
"=",
"COMM",
"(",
"encoding",
"=",
"0",
",",
"lang",
"=",
"'eng'",
",",
"desc",
"=",
"\"ID3v1 Comment\"",
",",
"text",
"=",
"comment",
")",
"# Don't read a track number if it looks like the comment was",
"# padded with spaces instead of nulls (thanks, WinAmp).",
"if",
"track",
"and",
"(",
"(",
"track",
"!=",
"32",
")",
"or",
"(",
"data",
"[",
"-",
"3",
"]",
"==",
"b'\\x00'",
"[",
"0",
"]",
")",
")",
":",
"frames",
"[",
"'TRCK'",
"]",
"=",
"TRCK",
"(",
"encoding",
"=",
"0",
",",
"text",
"=",
"str",
"(",
"track",
")",
")",
"if",
"genre",
"!=",
"255",
":",
"frames",
"[",
"'TCON'",
"]",
"=",
"TCON",
"(",
"encoding",
"=",
"0",
",",
"text",
"=",
"str",
"(",
"genre",
")",
")",
"return",
"frames"
] | 38e62c8dc35c72b16554f5dbe7c0fde91acc3411 |
test | MakeID3v1 | Return an ID3v1.1 tag string from a dict of ID3v2.4 frames. | mutagen/id3.py | def MakeID3v1(id3):
"""Return an ID3v1.1 tag string from a dict of ID3v2.4 frames."""
v1 = {}
for v2id, name in {"TIT2": "title", "TPE1": "artist",
"TALB": "album"}.items():
if v2id in id3:
text = id3[v2id].text[0].encode('latin1', 'replace')[:30]
else:
text = b''
v1[name] = text + (b'\x00' * (30 - len(text)))
if "COMM" in id3:
cmnt = id3["COMM"].text[0].encode('latin1', 'replace')[:28]
else:
cmnt = b''
v1['comment'] = cmnt + (b'\x00' * (29 - len(cmnt)))
if "TRCK" in id3:
try:
v1["track"] = chr_(+id3["TRCK"])
except ValueError:
v1["track"] = b'\x00'
else:
v1["track"] = b'\x00'
if "TCON" in id3:
try:
genre = id3["TCON"].genres[0]
except IndexError:
pass
else:
if genre in TCON.GENRES:
v1["genre"] = chr_(TCON.GENRES.index(genre))
if "genre" not in v1:
v1["genre"] = b"\xff"
if "TDRC" in id3:
year = text_type(id3["TDRC"]).encode('latin1', 'replace')
elif "TYER" in id3:
year = text_type(id3["TYER"]).encode('latin1', 'replace')
else:
year = b''
v1['year'] = (year + b'\x00\x00\x00\x00')[:4]
return (b'TAG' +
v1['title'] +
v1['artist'] +
v1['album'] +
v1['year'] +
v1['comment'] +
v1['track'] +
v1['genre']) | def MakeID3v1(id3):
"""Return an ID3v1.1 tag string from a dict of ID3v2.4 frames."""
v1 = {}
for v2id, name in {"TIT2": "title", "TPE1": "artist",
"TALB": "album"}.items():
if v2id in id3:
text = id3[v2id].text[0].encode('latin1', 'replace')[:30]
else:
text = b''
v1[name] = text + (b'\x00' * (30 - len(text)))
if "COMM" in id3:
cmnt = id3["COMM"].text[0].encode('latin1', 'replace')[:28]
else:
cmnt = b''
v1['comment'] = cmnt + (b'\x00' * (29 - len(cmnt)))
if "TRCK" in id3:
try:
v1["track"] = chr_(+id3["TRCK"])
except ValueError:
v1["track"] = b'\x00'
else:
v1["track"] = b'\x00'
if "TCON" in id3:
try:
genre = id3["TCON"].genres[0]
except IndexError:
pass
else:
if genre in TCON.GENRES:
v1["genre"] = chr_(TCON.GENRES.index(genre))
if "genre" not in v1:
v1["genre"] = b"\xff"
if "TDRC" in id3:
year = text_type(id3["TDRC"]).encode('latin1', 'replace')
elif "TYER" in id3:
year = text_type(id3["TYER"]).encode('latin1', 'replace')
else:
year = b''
v1['year'] = (year + b'\x00\x00\x00\x00')[:4]
return (b'TAG' +
v1['title'] +
v1['artist'] +
v1['album'] +
v1['year'] +
v1['comment'] +
v1['track'] +
v1['genre']) | [
"Return",
"an",
"ID3v1",
".",
"1",
"tag",
"string",
"from",
"a",
"dict",
"of",
"ID3v2",
".",
"4",
"frames",
"."
] | LordSputnik/mutagen | python | https://github.com/LordSputnik/mutagen/blob/38e62c8dc35c72b16554f5dbe7c0fde91acc3411/mutagen/id3.py#L833-L887 | [
"def",
"MakeID3v1",
"(",
"id3",
")",
":",
"v1",
"=",
"{",
"}",
"for",
"v2id",
",",
"name",
"in",
"{",
"\"TIT2\"",
":",
"\"title\"",
",",
"\"TPE1\"",
":",
"\"artist\"",
",",
"\"TALB\"",
":",
"\"album\"",
"}",
".",
"items",
"(",
")",
":",
"if",
"v2id",
"in",
"id3",
":",
"text",
"=",
"id3",
"[",
"v2id",
"]",
".",
"text",
"[",
"0",
"]",
".",
"encode",
"(",
"'latin1'",
",",
"'replace'",
")",
"[",
":",
"30",
"]",
"else",
":",
"text",
"=",
"b''",
"v1",
"[",
"name",
"]",
"=",
"text",
"+",
"(",
"b'\\x00'",
"*",
"(",
"30",
"-",
"len",
"(",
"text",
")",
")",
")",
"if",
"\"COMM\"",
"in",
"id3",
":",
"cmnt",
"=",
"id3",
"[",
"\"COMM\"",
"]",
".",
"text",
"[",
"0",
"]",
".",
"encode",
"(",
"'latin1'",
",",
"'replace'",
")",
"[",
":",
"28",
"]",
"else",
":",
"cmnt",
"=",
"b''",
"v1",
"[",
"'comment'",
"]",
"=",
"cmnt",
"+",
"(",
"b'\\x00'",
"*",
"(",
"29",
"-",
"len",
"(",
"cmnt",
")",
")",
")",
"if",
"\"TRCK\"",
"in",
"id3",
":",
"try",
":",
"v1",
"[",
"\"track\"",
"]",
"=",
"chr_",
"(",
"+",
"id3",
"[",
"\"TRCK\"",
"]",
")",
"except",
"ValueError",
":",
"v1",
"[",
"\"track\"",
"]",
"=",
"b'\\x00'",
"else",
":",
"v1",
"[",
"\"track\"",
"]",
"=",
"b'\\x00'",
"if",
"\"TCON\"",
"in",
"id3",
":",
"try",
":",
"genre",
"=",
"id3",
"[",
"\"TCON\"",
"]",
".",
"genres",
"[",
"0",
"]",
"except",
"IndexError",
":",
"pass",
"else",
":",
"if",
"genre",
"in",
"TCON",
".",
"GENRES",
":",
"v1",
"[",
"\"genre\"",
"]",
"=",
"chr_",
"(",
"TCON",
".",
"GENRES",
".",
"index",
"(",
"genre",
")",
")",
"if",
"\"genre\"",
"not",
"in",
"v1",
":",
"v1",
"[",
"\"genre\"",
"]",
"=",
"b\"\\xff\"",
"if",
"\"TDRC\"",
"in",
"id3",
":",
"year",
"=",
"text_type",
"(",
"id3",
"[",
"\"TDRC\"",
"]",
")",
".",
"encode",
"(",
"'latin1'",
",",
"'replace'",
")",
"elif",
"\"TYER\"",
"in",
"id3",
":",
"year",
"=",
"text_type",
"(",
"id3",
"[",
"\"TYER\"",
"]",
")",
".",
"encode",
"(",
"'latin1'",
",",
"'replace'",
")",
"else",
":",
"year",
"=",
"b''",
"v1",
"[",
"'year'",
"]",
"=",
"(",
"year",
"+",
"b'\\x00\\x00\\x00\\x00'",
")",
"[",
":",
"4",
"]",
"return",
"(",
"b'TAG'",
"+",
"v1",
"[",
"'title'",
"]",
"+",
"v1",
"[",
"'artist'",
"]",
"+",
"v1",
"[",
"'album'",
"]",
"+",
"v1",
"[",
"'year'",
"]",
"+",
"v1",
"[",
"'comment'",
"]",
"+",
"v1",
"[",
"'track'",
"]",
"+",
"v1",
"[",
"'genre'",
"]",
")"
] | 38e62c8dc35c72b16554f5dbe7c0fde91acc3411 |
test | ID3.__fullread | Read a certain number of bytes from the source file. | mutagen/id3.py | def __fullread(self, size):
""" Read a certain number of bytes from the source file. """
try:
if size < 0:
raise ValueError('Requested bytes (%s) less than zero' % size)
if size > self.__filesize:
raise EOFError('Requested %#x of %#x (%s)' % (
int(size), int(self.__filesize), self.filename))
except AttributeError:
pass
data = self._fileobj.read(size)
if len(data) != size:
raise EOFError
self.__readbytes += size
return data | def __fullread(self, size):
""" Read a certain number of bytes from the source file. """
try:
if size < 0:
raise ValueError('Requested bytes (%s) less than zero' % size)
if size > self.__filesize:
raise EOFError('Requested %#x of %#x (%s)' % (
int(size), int(self.__filesize), self.filename))
except AttributeError:
pass
data = self._fileobj.read(size)
if len(data) != size:
raise EOFError
self.__readbytes += size
return data | [
"Read",
"a",
"certain",
"number",
"of",
"bytes",
"from",
"the",
"source",
"file",
"."
] | LordSputnik/mutagen | python | https://github.com/LordSputnik/mutagen/blob/38e62c8dc35c72b16554f5dbe7c0fde91acc3411/mutagen/id3.py#L78-L93 | [
"def",
"__fullread",
"(",
"self",
",",
"size",
")",
":",
"try",
":",
"if",
"size",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"'Requested bytes (%s) less than zero'",
"%",
"size",
")",
"if",
"size",
">",
"self",
".",
"__filesize",
":",
"raise",
"EOFError",
"(",
"'Requested %#x of %#x (%s)'",
"%",
"(",
"int",
"(",
"size",
")",
",",
"int",
"(",
"self",
".",
"__filesize",
")",
",",
"self",
".",
"filename",
")",
")",
"except",
"AttributeError",
":",
"pass",
"data",
"=",
"self",
".",
"_fileobj",
".",
"read",
"(",
"size",
")",
"if",
"len",
"(",
"data",
")",
"!=",
"size",
":",
"raise",
"EOFError",
"self",
".",
"__readbytes",
"+=",
"size",
"return",
"data"
] | 38e62c8dc35c72b16554f5dbe7c0fde91acc3411 |
test | ID3.load | Load tags from a filename.
Keyword arguments:
* filename -- filename to load tag data from
* known_frames -- dict mapping frame IDs to Frame objects
* translate -- Update all tags to ID3v2.3/4 internally. If you
intend to save, this must be true or you have to
call update_to_v23() / update_to_v24() manually.
* v2_version -- if update_to_v23 or update_to_v24 get called (3 or 4)
Example of loading a custom frame::
my_frames = dict(mutagen.id3.Frames)
class XMYF(Frame): ...
my_frames["XMYF"] = XMYF
mutagen.id3.ID3(filename, known_frames=my_frames) | mutagen/id3.py | def load(self, filename, known_frames=None, translate=True, v2_version=4):
"""Load tags from a filename.
Keyword arguments:
* filename -- filename to load tag data from
* known_frames -- dict mapping frame IDs to Frame objects
* translate -- Update all tags to ID3v2.3/4 internally. If you
intend to save, this must be true or you have to
call update_to_v23() / update_to_v24() manually.
* v2_version -- if update_to_v23 or update_to_v24 get called (3 or 4)
Example of loading a custom frame::
my_frames = dict(mutagen.id3.Frames)
class XMYF(Frame): ...
my_frames["XMYF"] = XMYF
mutagen.id3.ID3(filename, known_frames=my_frames)
"""
if not v2_version in (3, 4):
raise ValueError("Only 3 and 4 possible for v2_version")
from os.path import getsize
self.filename = filename
self.__known_frames = known_frames
self._fileobj = open(filename, 'rb')
self.__filesize = getsize(filename)
try:
try:
self._load_header()
except EOFError:
self.size = 0
raise ID3NoHeaderError("%s: too small (%d bytes)" % (
filename, self.__filesize))
except (ID3NoHeaderError, ID3UnsupportedVersionError) as err:
self.size = 0
import sys
stack = sys.exc_info()[2]
try:
self._fileobj.seek(-128, 2)
except EnvironmentError:
reraise(err, None, stack)
else:
frames = ParseID3v1(self._fileobj.read(128))
if frames is not None:
self.version = self._V11
for v in frames.values():
self.add(v)
else:
reraise(err, None, stack)
else:
frames = self.__known_frames
if frames is None:
if self._V23 <= self.version:
frames = Frames
elif self._V22 <= self.version:
frames = Frames_2_2
data = self.__fullread(self.size - 10)
for frame in self.__read_frames(data, frames=frames):
if isinstance(frame, Frame):
self.add(frame)
else:
self.unknown_frames.append(frame)
self.__unknown_version = self.version
finally:
self._fileobj.close()
del self._fileobj
del self.__filesize
if translate:
if v2_version == 3:
self.update_to_v23()
else:
self.update_to_v24() | def load(self, filename, known_frames=None, translate=True, v2_version=4):
"""Load tags from a filename.
Keyword arguments:
* filename -- filename to load tag data from
* known_frames -- dict mapping frame IDs to Frame objects
* translate -- Update all tags to ID3v2.3/4 internally. If you
intend to save, this must be true or you have to
call update_to_v23() / update_to_v24() manually.
* v2_version -- if update_to_v23 or update_to_v24 get called (3 or 4)
Example of loading a custom frame::
my_frames = dict(mutagen.id3.Frames)
class XMYF(Frame): ...
my_frames["XMYF"] = XMYF
mutagen.id3.ID3(filename, known_frames=my_frames)
"""
if not v2_version in (3, 4):
raise ValueError("Only 3 and 4 possible for v2_version")
from os.path import getsize
self.filename = filename
self.__known_frames = known_frames
self._fileobj = open(filename, 'rb')
self.__filesize = getsize(filename)
try:
try:
self._load_header()
except EOFError:
self.size = 0
raise ID3NoHeaderError("%s: too small (%d bytes)" % (
filename, self.__filesize))
except (ID3NoHeaderError, ID3UnsupportedVersionError) as err:
self.size = 0
import sys
stack = sys.exc_info()[2]
try:
self._fileobj.seek(-128, 2)
except EnvironmentError:
reraise(err, None, stack)
else:
frames = ParseID3v1(self._fileobj.read(128))
if frames is not None:
self.version = self._V11
for v in frames.values():
self.add(v)
else:
reraise(err, None, stack)
else:
frames = self.__known_frames
if frames is None:
if self._V23 <= self.version:
frames = Frames
elif self._V22 <= self.version:
frames = Frames_2_2
data = self.__fullread(self.size - 10)
for frame in self.__read_frames(data, frames=frames):
if isinstance(frame, Frame):
self.add(frame)
else:
self.unknown_frames.append(frame)
self.__unknown_version = self.version
finally:
self._fileobj.close()
del self._fileobj
del self.__filesize
if translate:
if v2_version == 3:
self.update_to_v23()
else:
self.update_to_v24() | [
"Load",
"tags",
"from",
"a",
"filename",
"."
] | LordSputnik/mutagen | python | https://github.com/LordSputnik/mutagen/blob/38e62c8dc35c72b16554f5dbe7c0fde91acc3411/mutagen/id3.py#L95-L169 | [
"def",
"load",
"(",
"self",
",",
"filename",
",",
"known_frames",
"=",
"None",
",",
"translate",
"=",
"True",
",",
"v2_version",
"=",
"4",
")",
":",
"if",
"not",
"v2_version",
"in",
"(",
"3",
",",
"4",
")",
":",
"raise",
"ValueError",
"(",
"\"Only 3 and 4 possible for v2_version\"",
")",
"from",
"os",
".",
"path",
"import",
"getsize",
"self",
".",
"filename",
"=",
"filename",
"self",
".",
"__known_frames",
"=",
"known_frames",
"self",
".",
"_fileobj",
"=",
"open",
"(",
"filename",
",",
"'rb'",
")",
"self",
".",
"__filesize",
"=",
"getsize",
"(",
"filename",
")",
"try",
":",
"try",
":",
"self",
".",
"_load_header",
"(",
")",
"except",
"EOFError",
":",
"self",
".",
"size",
"=",
"0",
"raise",
"ID3NoHeaderError",
"(",
"\"%s: too small (%d bytes)\"",
"%",
"(",
"filename",
",",
"self",
".",
"__filesize",
")",
")",
"except",
"(",
"ID3NoHeaderError",
",",
"ID3UnsupportedVersionError",
")",
"as",
"err",
":",
"self",
".",
"size",
"=",
"0",
"import",
"sys",
"stack",
"=",
"sys",
".",
"exc_info",
"(",
")",
"[",
"2",
"]",
"try",
":",
"self",
".",
"_fileobj",
".",
"seek",
"(",
"-",
"128",
",",
"2",
")",
"except",
"EnvironmentError",
":",
"reraise",
"(",
"err",
",",
"None",
",",
"stack",
")",
"else",
":",
"frames",
"=",
"ParseID3v1",
"(",
"self",
".",
"_fileobj",
".",
"read",
"(",
"128",
")",
")",
"if",
"frames",
"is",
"not",
"None",
":",
"self",
".",
"version",
"=",
"self",
".",
"_V11",
"for",
"v",
"in",
"frames",
".",
"values",
"(",
")",
":",
"self",
".",
"add",
"(",
"v",
")",
"else",
":",
"reraise",
"(",
"err",
",",
"None",
",",
"stack",
")",
"else",
":",
"frames",
"=",
"self",
".",
"__known_frames",
"if",
"frames",
"is",
"None",
":",
"if",
"self",
".",
"_V23",
"<=",
"self",
".",
"version",
":",
"frames",
"=",
"Frames",
"elif",
"self",
".",
"_V22",
"<=",
"self",
".",
"version",
":",
"frames",
"=",
"Frames_2_2",
"data",
"=",
"self",
".",
"__fullread",
"(",
"self",
".",
"size",
"-",
"10",
")",
"for",
"frame",
"in",
"self",
".",
"__read_frames",
"(",
"data",
",",
"frames",
"=",
"frames",
")",
":",
"if",
"isinstance",
"(",
"frame",
",",
"Frame",
")",
":",
"self",
".",
"add",
"(",
"frame",
")",
"else",
":",
"self",
".",
"unknown_frames",
".",
"append",
"(",
"frame",
")",
"self",
".",
"__unknown_version",
"=",
"self",
".",
"version",
"finally",
":",
"self",
".",
"_fileobj",
".",
"close",
"(",
")",
"del",
"self",
".",
"_fileobj",
"del",
"self",
".",
"__filesize",
"if",
"translate",
":",
"if",
"v2_version",
"==",
"3",
":",
"self",
".",
"update_to_v23",
"(",
")",
"else",
":",
"self",
".",
"update_to_v24",
"(",
")"
] | 38e62c8dc35c72b16554f5dbe7c0fde91acc3411 |
test | ID3.getall | Return all frames with a given name (the list may be empty).
This is best explained by examples::
id3.getall('TIT2') == [id3['TIT2']]
id3.getall('TTTT') == []
id3.getall('TXXX') == [TXXX(desc='woo', text='bar'),
TXXX(desc='baz', text='quuuux'), ...]
Since this is based on the frame's HashKey, which is
colon-separated, you can use it to do things like
``getall('COMM:MusicMatch')`` or ``getall('TXXX:QuodLibet:')``. | mutagen/id3.py | def getall(self, key):
"""Return all frames with a given name (the list may be empty).
This is best explained by examples::
id3.getall('TIT2') == [id3['TIT2']]
id3.getall('TTTT') == []
id3.getall('TXXX') == [TXXX(desc='woo', text='bar'),
TXXX(desc='baz', text='quuuux'), ...]
Since this is based on the frame's HashKey, which is
colon-separated, you can use it to do things like
``getall('COMM:MusicMatch')`` or ``getall('TXXX:QuodLibet:')``.
"""
if key in self:
return [self[key]]
else:
key = key + ':'
return [v for s, v in self.items() if s.startswith(key)] | def getall(self, key):
"""Return all frames with a given name (the list may be empty).
This is best explained by examples::
id3.getall('TIT2') == [id3['TIT2']]
id3.getall('TTTT') == []
id3.getall('TXXX') == [TXXX(desc='woo', text='bar'),
TXXX(desc='baz', text='quuuux'), ...]
Since this is based on the frame's HashKey, which is
colon-separated, you can use it to do things like
``getall('COMM:MusicMatch')`` or ``getall('TXXX:QuodLibet:')``.
"""
if key in self:
return [self[key]]
else:
key = key + ':'
return [v for s, v in self.items() if s.startswith(key)] | [
"Return",
"all",
"frames",
"with",
"a",
"given",
"name",
"(",
"the",
"list",
"may",
"be",
"empty",
")",
"."
] | LordSputnik/mutagen | python | https://github.com/LordSputnik/mutagen/blob/38e62c8dc35c72b16554f5dbe7c0fde91acc3411/mutagen/id3.py#L171-L189 | [
"def",
"getall",
"(",
"self",
",",
"key",
")",
":",
"if",
"key",
"in",
"self",
":",
"return",
"[",
"self",
"[",
"key",
"]",
"]",
"else",
":",
"key",
"=",
"key",
"+",
"':'",
"return",
"[",
"v",
"for",
"s",
",",
"v",
"in",
"self",
".",
"items",
"(",
")",
"if",
"s",
".",
"startswith",
"(",
"key",
")",
"]"
] | 38e62c8dc35c72b16554f5dbe7c0fde91acc3411 |
test | ID3.delall | Delete all tags of a given kind; see getall. | mutagen/id3.py | def delall(self, key):
"""Delete all tags of a given kind; see getall."""
if key in self:
del(self[key])
else:
key = key + ":"
for k in self.keys():
if k.startswith(key):
del(self[k]) | def delall(self, key):
"""Delete all tags of a given kind; see getall."""
if key in self:
del(self[key])
else:
key = key + ":"
for k in self.keys():
if k.startswith(key):
del(self[k]) | [
"Delete",
"all",
"tags",
"of",
"a",
"given",
"kind",
";",
"see",
"getall",
"."
] | LordSputnik/mutagen | python | https://github.com/LordSputnik/mutagen/blob/38e62c8dc35c72b16554f5dbe7c0fde91acc3411/mutagen/id3.py#L191-L199 | [
"def",
"delall",
"(",
"self",
",",
"key",
")",
":",
"if",
"key",
"in",
"self",
":",
"del",
"(",
"self",
"[",
"key",
"]",
")",
"else",
":",
"key",
"=",
"key",
"+",
"\":\"",
"for",
"k",
"in",
"self",
".",
"keys",
"(",
")",
":",
"if",
"k",
".",
"startswith",
"(",
"key",
")",
":",
"del",
"(",
"self",
"[",
"k",
"]",
")"
] | 38e62c8dc35c72b16554f5dbe7c0fde91acc3411 |
test | ID3.loaded_frame | Deprecated; use the add method. | mutagen/id3.py | def loaded_frame(self, tag):
"""Deprecated; use the add method."""
# turn 2.2 into 2.3/2.4 tags
if len(type(tag).__name__) == 3:
tag = type(tag).__base__(tag)
self[tag.HashKey] = tag | def loaded_frame(self, tag):
"""Deprecated; use the add method."""
# turn 2.2 into 2.3/2.4 tags
if len(type(tag).__name__) == 3:
tag = type(tag).__base__(tag)
self[tag.HashKey] = tag | [
"Deprecated",
";",
"use",
"the",
"add",
"method",
"."
] | LordSputnik/mutagen | python | https://github.com/LordSputnik/mutagen/blob/38e62c8dc35c72b16554f5dbe7c0fde91acc3411/mutagen/id3.py#L222-L227 | [
"def",
"loaded_frame",
"(",
"self",
",",
"tag",
")",
":",
"# turn 2.2 into 2.3/2.4 tags",
"if",
"len",
"(",
"type",
"(",
"tag",
")",
".",
"__name__",
")",
"==",
"3",
":",
"tag",
"=",
"type",
"(",
"tag",
")",
".",
"__base__",
"(",
"tag",
")",
"self",
"[",
"tag",
".",
"HashKey",
"]",
"=",
"tag"
] | 38e62c8dc35c72b16554f5dbe7c0fde91acc3411 |
test | ID3.save | Save changes to a file.
If no filename is given, the one most recently loaded is used.
Keyword arguments:
v1 -- if 0, ID3v1 tags will be removed
if 1, ID3v1 tags will be updated but not added
if 2, ID3v1 tags will be created and/or updated
v2 -- version of ID3v2 tags (3 or 4).
By default Mutagen saves ID3v2.4 tags. If you want to save ID3v2.3
tags, you must call method update_to_v23 before saving the file.
v23_sep -- the separator used to join multiple text values
if v2_version == 3. Defaults to '/' but if it's None
will be the ID3v2v2.4 null separator.
The lack of a way to update only an ID3v1 tag is intentional. | mutagen/id3.py | def save(self, filename=None, v1=1, v2_version=4, v23_sep='/'):
"""Save changes to a file.
If no filename is given, the one most recently loaded is used.
Keyword arguments:
v1 -- if 0, ID3v1 tags will be removed
if 1, ID3v1 tags will be updated but not added
if 2, ID3v1 tags will be created and/or updated
v2 -- version of ID3v2 tags (3 or 4).
By default Mutagen saves ID3v2.4 tags. If you want to save ID3v2.3
tags, you must call method update_to_v23 before saving the file.
v23_sep -- the separator used to join multiple text values
if v2_version == 3. Defaults to '/' but if it's None
will be the ID3v2v2.4 null separator.
The lack of a way to update only an ID3v1 tag is intentional.
"""
framedata = self._prepare_framedata(v2_version, v23_sep)
framesize = len(framedata)
if not framedata:
try:
self.delete(filename)
except EnvironmentError as err:
from errno import ENOENT
if err.errno != ENOENT:
raise
return
if filename is None:
filename = self.filename
try:
f = open(filename, 'rb+')
except IOError as err:
from errno import ENOENT
if err.errno != ENOENT:
raise
f = open(filename, 'ab') # create, then reopen
f = open(filename, 'rb+')
try:
idata = f.read(10)
header = self._prepare_id3_header(idata, framesize, v2_version)
header, outsize, insize = header
data = header + framedata + (b'\x00' * (outsize - framesize))
if (insize < outsize):
insert_bytes(f, outsize-insize, insize+10)
f.seek(0)
f.write(data)
try:
f.seek(-128, 2)
except IOError as err:
# If the file is too small, that's OK - it just means
# we're certain it doesn't have a v1 tag.
from errno import EINVAL
if err.errno != EINVAL:
# If we failed to see for some other reason, bail out.
raise
# Since we're sure this isn't a v1 tag, don't read it.
f.seek(0, 2)
data = f.read(128)
try:
idx = data.index(b"TAG")
except ValueError:
offset = 0
has_v1 = False
else:
offset = idx - len(data)
has_v1 = True
f.seek(offset, 2)
if v1 == 1 and has_v1 or v1 == 2:
f.write(MakeID3v1(self))
else:
f.truncate()
finally:
f.close() | def save(self, filename=None, v1=1, v2_version=4, v23_sep='/'):
"""Save changes to a file.
If no filename is given, the one most recently loaded is used.
Keyword arguments:
v1 -- if 0, ID3v1 tags will be removed
if 1, ID3v1 tags will be updated but not added
if 2, ID3v1 tags will be created and/or updated
v2 -- version of ID3v2 tags (3 or 4).
By default Mutagen saves ID3v2.4 tags. If you want to save ID3v2.3
tags, you must call method update_to_v23 before saving the file.
v23_sep -- the separator used to join multiple text values
if v2_version == 3. Defaults to '/' but if it's None
will be the ID3v2v2.4 null separator.
The lack of a way to update only an ID3v1 tag is intentional.
"""
framedata = self._prepare_framedata(v2_version, v23_sep)
framesize = len(framedata)
if not framedata:
try:
self.delete(filename)
except EnvironmentError as err:
from errno import ENOENT
if err.errno != ENOENT:
raise
return
if filename is None:
filename = self.filename
try:
f = open(filename, 'rb+')
except IOError as err:
from errno import ENOENT
if err.errno != ENOENT:
raise
f = open(filename, 'ab') # create, then reopen
f = open(filename, 'rb+')
try:
idata = f.read(10)
header = self._prepare_id3_header(idata, framesize, v2_version)
header, outsize, insize = header
data = header + framedata + (b'\x00' * (outsize - framesize))
if (insize < outsize):
insert_bytes(f, outsize-insize, insize+10)
f.seek(0)
f.write(data)
try:
f.seek(-128, 2)
except IOError as err:
# If the file is too small, that's OK - it just means
# we're certain it doesn't have a v1 tag.
from errno import EINVAL
if err.errno != EINVAL:
# If we failed to see for some other reason, bail out.
raise
# Since we're sure this isn't a v1 tag, don't read it.
f.seek(0, 2)
data = f.read(128)
try:
idx = data.index(b"TAG")
except ValueError:
offset = 0
has_v1 = False
else:
offset = idx - len(data)
has_v1 = True
f.seek(offset, 2)
if v1 == 1 and has_v1 or v1 == 2:
f.write(MakeID3v1(self))
else:
f.truncate()
finally:
f.close() | [
"Save",
"changes",
"to",
"a",
"file",
"."
] | LordSputnik/mutagen | python | https://github.com/LordSputnik/mutagen/blob/38e62c8dc35c72b16554f5dbe7c0fde91acc3411/mutagen/id3.py#L455-L540 | [
"def",
"save",
"(",
"self",
",",
"filename",
"=",
"None",
",",
"v1",
"=",
"1",
",",
"v2_version",
"=",
"4",
",",
"v23_sep",
"=",
"'/'",
")",
":",
"framedata",
"=",
"self",
".",
"_prepare_framedata",
"(",
"v2_version",
",",
"v23_sep",
")",
"framesize",
"=",
"len",
"(",
"framedata",
")",
"if",
"not",
"framedata",
":",
"try",
":",
"self",
".",
"delete",
"(",
"filename",
")",
"except",
"EnvironmentError",
"as",
"err",
":",
"from",
"errno",
"import",
"ENOENT",
"if",
"err",
".",
"errno",
"!=",
"ENOENT",
":",
"raise",
"return",
"if",
"filename",
"is",
"None",
":",
"filename",
"=",
"self",
".",
"filename",
"try",
":",
"f",
"=",
"open",
"(",
"filename",
",",
"'rb+'",
")",
"except",
"IOError",
"as",
"err",
":",
"from",
"errno",
"import",
"ENOENT",
"if",
"err",
".",
"errno",
"!=",
"ENOENT",
":",
"raise",
"f",
"=",
"open",
"(",
"filename",
",",
"'ab'",
")",
"# create, then reopen",
"f",
"=",
"open",
"(",
"filename",
",",
"'rb+'",
")",
"try",
":",
"idata",
"=",
"f",
".",
"read",
"(",
"10",
")",
"header",
"=",
"self",
".",
"_prepare_id3_header",
"(",
"idata",
",",
"framesize",
",",
"v2_version",
")",
"header",
",",
"outsize",
",",
"insize",
"=",
"header",
"data",
"=",
"header",
"+",
"framedata",
"+",
"(",
"b'\\x00'",
"*",
"(",
"outsize",
"-",
"framesize",
")",
")",
"if",
"(",
"insize",
"<",
"outsize",
")",
":",
"insert_bytes",
"(",
"f",
",",
"outsize",
"-",
"insize",
",",
"insize",
"+",
"10",
")",
"f",
".",
"seek",
"(",
"0",
")",
"f",
".",
"write",
"(",
"data",
")",
"try",
":",
"f",
".",
"seek",
"(",
"-",
"128",
",",
"2",
")",
"except",
"IOError",
"as",
"err",
":",
"# If the file is too small, that's OK - it just means",
"# we're certain it doesn't have a v1 tag.",
"from",
"errno",
"import",
"EINVAL",
"if",
"err",
".",
"errno",
"!=",
"EINVAL",
":",
"# If we failed to see for some other reason, bail out.",
"raise",
"# Since we're sure this isn't a v1 tag, don't read it.",
"f",
".",
"seek",
"(",
"0",
",",
"2",
")",
"data",
"=",
"f",
".",
"read",
"(",
"128",
")",
"try",
":",
"idx",
"=",
"data",
".",
"index",
"(",
"b\"TAG\"",
")",
"except",
"ValueError",
":",
"offset",
"=",
"0",
"has_v1",
"=",
"False",
"else",
":",
"offset",
"=",
"idx",
"-",
"len",
"(",
"data",
")",
"has_v1",
"=",
"True",
"f",
".",
"seek",
"(",
"offset",
",",
"2",
")",
"if",
"v1",
"==",
"1",
"and",
"has_v1",
"or",
"v1",
"==",
"2",
":",
"f",
".",
"write",
"(",
"MakeID3v1",
"(",
"self",
")",
")",
"else",
":",
"f",
".",
"truncate",
"(",
")",
"finally",
":",
"f",
".",
"close",
"(",
")"
] | 38e62c8dc35c72b16554f5dbe7c0fde91acc3411 |
test | ID3.delete | Remove tags from a file.
If no filename is given, the one most recently loaded is used.
Keyword arguments:
* delete_v1 -- delete any ID3v1 tag
* delete_v2 -- delete any ID3v2 tag | mutagen/id3.py | def delete(self, filename=None, delete_v1=True, delete_v2=True):
"""Remove tags from a file.
If no filename is given, the one most recently loaded is used.
Keyword arguments:
* delete_v1 -- delete any ID3v1 tag
* delete_v2 -- delete any ID3v2 tag
"""
if filename is None:
filename = self.filename
delete(filename, delete_v1, delete_v2)
self.clear() | def delete(self, filename=None, delete_v1=True, delete_v2=True):
"""Remove tags from a file.
If no filename is given, the one most recently loaded is used.
Keyword arguments:
* delete_v1 -- delete any ID3v1 tag
* delete_v2 -- delete any ID3v2 tag
"""
if filename is None:
filename = self.filename
delete(filename, delete_v1, delete_v2)
self.clear() | [
"Remove",
"tags",
"from",
"a",
"file",
"."
] | LordSputnik/mutagen | python | https://github.com/LordSputnik/mutagen/blob/38e62c8dc35c72b16554f5dbe7c0fde91acc3411/mutagen/id3.py#L542-L555 | [
"def",
"delete",
"(",
"self",
",",
"filename",
"=",
"None",
",",
"delete_v1",
"=",
"True",
",",
"delete_v2",
"=",
"True",
")",
":",
"if",
"filename",
"is",
"None",
":",
"filename",
"=",
"self",
".",
"filename",
"delete",
"(",
"filename",
",",
"delete_v1",
",",
"delete_v2",
")",
"self",
".",
"clear",
"(",
")"
] | 38e62c8dc35c72b16554f5dbe7c0fde91acc3411 |
test | ID3.__update_common | Updates done by both v23 and v24 update | mutagen/id3.py | def __update_common(self):
"""Updates done by both v23 and v24 update"""
if "TCON" in self:
# Get rid of "(xx)Foobr" format.
self["TCON"].genres = self["TCON"].genres
if self.version < self._V23:
# ID3v2.2 PIC frames are slightly different.
pics = self.getall("APIC")
mimes = {"PNG": "image/png", "JPG": "image/jpeg"}
self.delall("APIC")
for pic in pics:
newpic = APIC(
encoding=pic.encoding, mime=mimes.get(pic.mime, pic.mime),
type=pic.type, desc=pic.desc, data=pic.data)
self.add(newpic)
# ID3v2.2 LNK frames are just way too different to upgrade.
self.delall("LINK") | def __update_common(self):
"""Updates done by both v23 and v24 update"""
if "TCON" in self:
# Get rid of "(xx)Foobr" format.
self["TCON"].genres = self["TCON"].genres
if self.version < self._V23:
# ID3v2.2 PIC frames are slightly different.
pics = self.getall("APIC")
mimes = {"PNG": "image/png", "JPG": "image/jpeg"}
self.delall("APIC")
for pic in pics:
newpic = APIC(
encoding=pic.encoding, mime=mimes.get(pic.mime, pic.mime),
type=pic.type, desc=pic.desc, data=pic.data)
self.add(newpic)
# ID3v2.2 LNK frames are just way too different to upgrade.
self.delall("LINK") | [
"Updates",
"done",
"by",
"both",
"v23",
"and",
"v24",
"update"
] | LordSputnik/mutagen | python | https://github.com/LordSputnik/mutagen/blob/38e62c8dc35c72b16554f5dbe7c0fde91acc3411/mutagen/id3.py#L590-L609 | [
"def",
"__update_common",
"(",
"self",
")",
":",
"if",
"\"TCON\"",
"in",
"self",
":",
"# Get rid of \"(xx)Foobr\" format.",
"self",
"[",
"\"TCON\"",
"]",
".",
"genres",
"=",
"self",
"[",
"\"TCON\"",
"]",
".",
"genres",
"if",
"self",
".",
"version",
"<",
"self",
".",
"_V23",
":",
"# ID3v2.2 PIC frames are slightly different.",
"pics",
"=",
"self",
".",
"getall",
"(",
"\"APIC\"",
")",
"mimes",
"=",
"{",
"\"PNG\"",
":",
"\"image/png\"",
",",
"\"JPG\"",
":",
"\"image/jpeg\"",
"}",
"self",
".",
"delall",
"(",
"\"APIC\"",
")",
"for",
"pic",
"in",
"pics",
":",
"newpic",
"=",
"APIC",
"(",
"encoding",
"=",
"pic",
".",
"encoding",
",",
"mime",
"=",
"mimes",
".",
"get",
"(",
"pic",
".",
"mime",
",",
"pic",
".",
"mime",
")",
",",
"type",
"=",
"pic",
".",
"type",
",",
"desc",
"=",
"pic",
".",
"desc",
",",
"data",
"=",
"pic",
".",
"data",
")",
"self",
".",
"add",
"(",
"newpic",
")",
"# ID3v2.2 LNK frames are just way too different to upgrade.",
"self",
".",
"delall",
"(",
"\"LINK\"",
")"
] | 38e62c8dc35c72b16554f5dbe7c0fde91acc3411 |
test | ID3.update_to_v24 | Convert older tags into an ID3v2.4 tag.
This updates old ID3v2 frames to ID3v2.4 ones (e.g. TYER to
TDRC). If you intend to save tags, you must call this function
at some point; it is called by default when loading the tag. | mutagen/id3.py | def update_to_v24(self):
"""Convert older tags into an ID3v2.4 tag.
This updates old ID3v2 frames to ID3v2.4 ones (e.g. TYER to
TDRC). If you intend to save tags, you must call this function
at some point; it is called by default when loading the tag.
"""
self.__update_common()
if self.__unknown_version == self._V23:
# convert unknown 2.3 frames (flags/size) to 2.4
converted = []
for frame in self.unknown_frames:
try:
name, size, flags = unpack('>4sLH', frame[:10])
frame = BinaryFrame.fromData(self, flags, frame[10:])
except (struct.error, error):
continue
name = name.decode('ascii')
converted.append(self.__save_frame(frame, name=name))
self.unknown_frames[:] = converted
self.__unknown_version = self._V24
# TDAT, TYER, and TIME have been turned into TDRC.
try:
date = text_type(self.get("TYER", ""))
if date.strip(u"\x00"):
self.pop("TYER")
dat = text_type(self.get("TDAT", ""))
if dat.strip("\x00"):
self.pop("TDAT")
date = "%s-%s-%s" % (date, dat[2:], dat[:2])
time = text_type(self.get("TIME", ""))
if time.strip("\x00"):
self.pop("TIME")
date += "T%s:%s:00" % (time[:2], time[2:])
if "TDRC" not in self:
self.add(TDRC(encoding=0, text=date))
except UnicodeDecodeError:
# Old ID3 tags have *lots* of Unicode problems, so if TYER
# is bad, just chuck the frames.
pass
# TORY can be the first part of a TDOR.
if "TORY" in self:
f = self.pop("TORY")
if "TDOR" not in self:
try:
self.add(TDOR(encoding=0, text=str(f)))
except UnicodeDecodeError:
pass
# IPLS is now TIPL.
if "IPLS" in self:
f = self.pop("IPLS")
if "TIPL" not in self:
self.add(TIPL(encoding=f.encoding, people=f.people))
# These can't be trivially translated to any ID3v2.4 tags, or
# should have been removed already.
for key in ["RVAD", "EQUA", "TRDA", "TSIZ", "TDAT", "TIME", "CRM"]:
if key in self:
del(self[key]) | def update_to_v24(self):
"""Convert older tags into an ID3v2.4 tag.
This updates old ID3v2 frames to ID3v2.4 ones (e.g. TYER to
TDRC). If you intend to save tags, you must call this function
at some point; it is called by default when loading the tag.
"""
self.__update_common()
if self.__unknown_version == self._V23:
# convert unknown 2.3 frames (flags/size) to 2.4
converted = []
for frame in self.unknown_frames:
try:
name, size, flags = unpack('>4sLH', frame[:10])
frame = BinaryFrame.fromData(self, flags, frame[10:])
except (struct.error, error):
continue
name = name.decode('ascii')
converted.append(self.__save_frame(frame, name=name))
self.unknown_frames[:] = converted
self.__unknown_version = self._V24
# TDAT, TYER, and TIME have been turned into TDRC.
try:
date = text_type(self.get("TYER", ""))
if date.strip(u"\x00"):
self.pop("TYER")
dat = text_type(self.get("TDAT", ""))
if dat.strip("\x00"):
self.pop("TDAT")
date = "%s-%s-%s" % (date, dat[2:], dat[:2])
time = text_type(self.get("TIME", ""))
if time.strip("\x00"):
self.pop("TIME")
date += "T%s:%s:00" % (time[:2], time[2:])
if "TDRC" not in self:
self.add(TDRC(encoding=0, text=date))
except UnicodeDecodeError:
# Old ID3 tags have *lots* of Unicode problems, so if TYER
# is bad, just chuck the frames.
pass
# TORY can be the first part of a TDOR.
if "TORY" in self:
f = self.pop("TORY")
if "TDOR" not in self:
try:
self.add(TDOR(encoding=0, text=str(f)))
except UnicodeDecodeError:
pass
# IPLS is now TIPL.
if "IPLS" in self:
f = self.pop("IPLS")
if "TIPL" not in self:
self.add(TIPL(encoding=f.encoding, people=f.people))
# These can't be trivially translated to any ID3v2.4 tags, or
# should have been removed already.
for key in ["RVAD", "EQUA", "TRDA", "TSIZ", "TDAT", "TIME", "CRM"]:
if key in self:
del(self[key]) | [
"Convert",
"older",
"tags",
"into",
"an",
"ID3v2",
".",
"4",
"tag",
"."
] | LordSputnik/mutagen | python | https://github.com/LordSputnik/mutagen/blob/38e62c8dc35c72b16554f5dbe7c0fde91acc3411/mutagen/id3.py#L611-L674 | [
"def",
"update_to_v24",
"(",
"self",
")",
":",
"self",
".",
"__update_common",
"(",
")",
"if",
"self",
".",
"__unknown_version",
"==",
"self",
".",
"_V23",
":",
"# convert unknown 2.3 frames (flags/size) to 2.4",
"converted",
"=",
"[",
"]",
"for",
"frame",
"in",
"self",
".",
"unknown_frames",
":",
"try",
":",
"name",
",",
"size",
",",
"flags",
"=",
"unpack",
"(",
"'>4sLH'",
",",
"frame",
"[",
":",
"10",
"]",
")",
"frame",
"=",
"BinaryFrame",
".",
"fromData",
"(",
"self",
",",
"flags",
",",
"frame",
"[",
"10",
":",
"]",
")",
"except",
"(",
"struct",
".",
"error",
",",
"error",
")",
":",
"continue",
"name",
"=",
"name",
".",
"decode",
"(",
"'ascii'",
")",
"converted",
".",
"append",
"(",
"self",
".",
"__save_frame",
"(",
"frame",
",",
"name",
"=",
"name",
")",
")",
"self",
".",
"unknown_frames",
"[",
":",
"]",
"=",
"converted",
"self",
".",
"__unknown_version",
"=",
"self",
".",
"_V24",
"# TDAT, TYER, and TIME have been turned into TDRC.",
"try",
":",
"date",
"=",
"text_type",
"(",
"self",
".",
"get",
"(",
"\"TYER\"",
",",
"\"\"",
")",
")",
"if",
"date",
".",
"strip",
"(",
"u\"\\x00\"",
")",
":",
"self",
".",
"pop",
"(",
"\"TYER\"",
")",
"dat",
"=",
"text_type",
"(",
"self",
".",
"get",
"(",
"\"TDAT\"",
",",
"\"\"",
")",
")",
"if",
"dat",
".",
"strip",
"(",
"\"\\x00\"",
")",
":",
"self",
".",
"pop",
"(",
"\"TDAT\"",
")",
"date",
"=",
"\"%s-%s-%s\"",
"%",
"(",
"date",
",",
"dat",
"[",
"2",
":",
"]",
",",
"dat",
"[",
":",
"2",
"]",
")",
"time",
"=",
"text_type",
"(",
"self",
".",
"get",
"(",
"\"TIME\"",
",",
"\"\"",
")",
")",
"if",
"time",
".",
"strip",
"(",
"\"\\x00\"",
")",
":",
"self",
".",
"pop",
"(",
"\"TIME\"",
")",
"date",
"+=",
"\"T%s:%s:00\"",
"%",
"(",
"time",
"[",
":",
"2",
"]",
",",
"time",
"[",
"2",
":",
"]",
")",
"if",
"\"TDRC\"",
"not",
"in",
"self",
":",
"self",
".",
"add",
"(",
"TDRC",
"(",
"encoding",
"=",
"0",
",",
"text",
"=",
"date",
")",
")",
"except",
"UnicodeDecodeError",
":",
"# Old ID3 tags have *lots* of Unicode problems, so if TYER",
"# is bad, just chuck the frames.",
"pass",
"# TORY can be the first part of a TDOR.",
"if",
"\"TORY\"",
"in",
"self",
":",
"f",
"=",
"self",
".",
"pop",
"(",
"\"TORY\"",
")",
"if",
"\"TDOR\"",
"not",
"in",
"self",
":",
"try",
":",
"self",
".",
"add",
"(",
"TDOR",
"(",
"encoding",
"=",
"0",
",",
"text",
"=",
"str",
"(",
"f",
")",
")",
")",
"except",
"UnicodeDecodeError",
":",
"pass",
"# IPLS is now TIPL.",
"if",
"\"IPLS\"",
"in",
"self",
":",
"f",
"=",
"self",
".",
"pop",
"(",
"\"IPLS\"",
")",
"if",
"\"TIPL\"",
"not",
"in",
"self",
":",
"self",
".",
"add",
"(",
"TIPL",
"(",
"encoding",
"=",
"f",
".",
"encoding",
",",
"people",
"=",
"f",
".",
"people",
")",
")",
"# These can't be trivially translated to any ID3v2.4 tags, or",
"# should have been removed already.",
"for",
"key",
"in",
"[",
"\"RVAD\"",
",",
"\"EQUA\"",
",",
"\"TRDA\"",
",",
"\"TSIZ\"",
",",
"\"TDAT\"",
",",
"\"TIME\"",
",",
"\"CRM\"",
"]",
":",
"if",
"key",
"in",
"self",
":",
"del",
"(",
"self",
"[",
"key",
"]",
")"
] | 38e62c8dc35c72b16554f5dbe7c0fde91acc3411 |
test | ID3.update_to_v23 | Convert older (and newer) tags into an ID3v2.3 tag.
This updates incompatible ID3v2 frames to ID3v2.3 ones. If you
intend to save tags as ID3v2.3, you must call this function
at some point.
If you want to to go off spec and include some v2.4 frames
in v2.3, remove them before calling this and add them back afterwards. | mutagen/id3.py | def update_to_v23(self):
"""Convert older (and newer) tags into an ID3v2.3 tag.
This updates incompatible ID3v2 frames to ID3v2.3 ones. If you
intend to save tags as ID3v2.3, you must call this function
at some point.
If you want to to go off spec and include some v2.4 frames
in v2.3, remove them before calling this and add them back afterwards.
"""
self.__update_common()
# we could downgrade unknown v2.4 frames here, but given that
# the main reason to save v2.3 is compatibility and this
# might increase the chance of some parser breaking.. better not
# TMCL, TIPL -> TIPL
if "TIPL" in self or "TMCL" in self:
people = []
if "TIPL" in self:
f = self.pop("TIPL")
people.extend(f.people)
if "TMCL" in self:
f = self.pop("TMCL")
people.extend(f.people)
if "IPLS" not in self:
self.add(IPLS(encoding=f.encoding, people=people))
# TDOR -> TORY
if "TDOR" in self:
f = self.pop("TDOR")
if f.text:
d = f.text[0]
if d.year and "TORY" not in self:
self.add(TORY(encoding=f.encoding, text="%04d" % d.year))
# TDRC -> TYER, TDAT, TIME
if "TDRC" in self:
f = self.pop("TDRC")
if f.text:
d = f.text[0]
if d.year and "TYER" not in self:
self.add(TYER(encoding=f.encoding, text="%04d" % d.year))
if d.month and d.day and "TDAT" not in self:
self.add(TDAT(encoding=f.encoding,
text="%02d%02d" % (d.day, d.month)))
if d.hour and d.minute and "TIME" not in self:
self.add(TIME(encoding=f.encoding,
text="%02d%02d" % (d.hour, d.minute)))
# New frames added in v2.4
v24_frames = [
'ASPI', 'EQU2', 'RVA2', 'SEEK', 'SIGN', 'TDEN', 'TDOR',
'TDRC', 'TDRL', 'TDTG', 'TIPL', 'TMCL', 'TMOO', 'TPRO',
'TSOA', 'TSOP', 'TSOT', 'TSST',
]
for key in v24_frames:
if key in self:
del(self[key]) | def update_to_v23(self):
"""Convert older (and newer) tags into an ID3v2.3 tag.
This updates incompatible ID3v2 frames to ID3v2.3 ones. If you
intend to save tags as ID3v2.3, you must call this function
at some point.
If you want to to go off spec and include some v2.4 frames
in v2.3, remove them before calling this and add them back afterwards.
"""
self.__update_common()
# we could downgrade unknown v2.4 frames here, but given that
# the main reason to save v2.3 is compatibility and this
# might increase the chance of some parser breaking.. better not
# TMCL, TIPL -> TIPL
if "TIPL" in self or "TMCL" in self:
people = []
if "TIPL" in self:
f = self.pop("TIPL")
people.extend(f.people)
if "TMCL" in self:
f = self.pop("TMCL")
people.extend(f.people)
if "IPLS" not in self:
self.add(IPLS(encoding=f.encoding, people=people))
# TDOR -> TORY
if "TDOR" in self:
f = self.pop("TDOR")
if f.text:
d = f.text[0]
if d.year and "TORY" not in self:
self.add(TORY(encoding=f.encoding, text="%04d" % d.year))
# TDRC -> TYER, TDAT, TIME
if "TDRC" in self:
f = self.pop("TDRC")
if f.text:
d = f.text[0]
if d.year and "TYER" not in self:
self.add(TYER(encoding=f.encoding, text="%04d" % d.year))
if d.month and d.day and "TDAT" not in self:
self.add(TDAT(encoding=f.encoding,
text="%02d%02d" % (d.day, d.month)))
if d.hour and d.minute and "TIME" not in self:
self.add(TIME(encoding=f.encoding,
text="%02d%02d" % (d.hour, d.minute)))
# New frames added in v2.4
v24_frames = [
'ASPI', 'EQU2', 'RVA2', 'SEEK', 'SIGN', 'TDEN', 'TDOR',
'TDRC', 'TDRL', 'TDTG', 'TIPL', 'TMCL', 'TMOO', 'TPRO',
'TSOA', 'TSOP', 'TSOT', 'TSST',
]
for key in v24_frames:
if key in self:
del(self[key]) | [
"Convert",
"older",
"(",
"and",
"newer",
")",
"tags",
"into",
"an",
"ID3v2",
".",
"3",
"tag",
"."
] | LordSputnik/mutagen | python | https://github.com/LordSputnik/mutagen/blob/38e62c8dc35c72b16554f5dbe7c0fde91acc3411/mutagen/id3.py#L676-L736 | [
"def",
"update_to_v23",
"(",
"self",
")",
":",
"self",
".",
"__update_common",
"(",
")",
"# we could downgrade unknown v2.4 frames here, but given that",
"# the main reason to save v2.3 is compatibility and this",
"# might increase the chance of some parser breaking.. better not",
"# TMCL, TIPL -> TIPL",
"if",
"\"TIPL\"",
"in",
"self",
"or",
"\"TMCL\"",
"in",
"self",
":",
"people",
"=",
"[",
"]",
"if",
"\"TIPL\"",
"in",
"self",
":",
"f",
"=",
"self",
".",
"pop",
"(",
"\"TIPL\"",
")",
"people",
".",
"extend",
"(",
"f",
".",
"people",
")",
"if",
"\"TMCL\"",
"in",
"self",
":",
"f",
"=",
"self",
".",
"pop",
"(",
"\"TMCL\"",
")",
"people",
".",
"extend",
"(",
"f",
".",
"people",
")",
"if",
"\"IPLS\"",
"not",
"in",
"self",
":",
"self",
".",
"add",
"(",
"IPLS",
"(",
"encoding",
"=",
"f",
".",
"encoding",
",",
"people",
"=",
"people",
")",
")",
"# TDOR -> TORY",
"if",
"\"TDOR\"",
"in",
"self",
":",
"f",
"=",
"self",
".",
"pop",
"(",
"\"TDOR\"",
")",
"if",
"f",
".",
"text",
":",
"d",
"=",
"f",
".",
"text",
"[",
"0",
"]",
"if",
"d",
".",
"year",
"and",
"\"TORY\"",
"not",
"in",
"self",
":",
"self",
".",
"add",
"(",
"TORY",
"(",
"encoding",
"=",
"f",
".",
"encoding",
",",
"text",
"=",
"\"%04d\"",
"%",
"d",
".",
"year",
")",
")",
"# TDRC -> TYER, TDAT, TIME",
"if",
"\"TDRC\"",
"in",
"self",
":",
"f",
"=",
"self",
".",
"pop",
"(",
"\"TDRC\"",
")",
"if",
"f",
".",
"text",
":",
"d",
"=",
"f",
".",
"text",
"[",
"0",
"]",
"if",
"d",
".",
"year",
"and",
"\"TYER\"",
"not",
"in",
"self",
":",
"self",
".",
"add",
"(",
"TYER",
"(",
"encoding",
"=",
"f",
".",
"encoding",
",",
"text",
"=",
"\"%04d\"",
"%",
"d",
".",
"year",
")",
")",
"if",
"d",
".",
"month",
"and",
"d",
".",
"day",
"and",
"\"TDAT\"",
"not",
"in",
"self",
":",
"self",
".",
"add",
"(",
"TDAT",
"(",
"encoding",
"=",
"f",
".",
"encoding",
",",
"text",
"=",
"\"%02d%02d\"",
"%",
"(",
"d",
".",
"day",
",",
"d",
".",
"month",
")",
")",
")",
"if",
"d",
".",
"hour",
"and",
"d",
".",
"minute",
"and",
"\"TIME\"",
"not",
"in",
"self",
":",
"self",
".",
"add",
"(",
"TIME",
"(",
"encoding",
"=",
"f",
".",
"encoding",
",",
"text",
"=",
"\"%02d%02d\"",
"%",
"(",
"d",
".",
"hour",
",",
"d",
".",
"minute",
")",
")",
")",
"# New frames added in v2.4",
"v24_frames",
"=",
"[",
"'ASPI'",
",",
"'EQU2'",
",",
"'RVA2'",
",",
"'SEEK'",
",",
"'SIGN'",
",",
"'TDEN'",
",",
"'TDOR'",
",",
"'TDRC'",
",",
"'TDRL'",
",",
"'TDTG'",
",",
"'TIPL'",
",",
"'TMCL'",
",",
"'TMOO'",
",",
"'TPRO'",
",",
"'TSOA'",
",",
"'TSOP'",
",",
"'TSOT'",
",",
"'TSST'",
",",
"]",
"for",
"key",
"in",
"v24_frames",
":",
"if",
"key",
"in",
"self",
":",
"del",
"(",
"self",
"[",
"key",
"]",
")"
] | 38e62c8dc35c72b16554f5dbe7c0fde91acc3411 |
test | ID3FileType.load | Load stream and tag information from a file.
A custom tag reader may be used in instead of the default
mutagen.id3.ID3 object, e.g. an EasyID3 reader. | mutagen/id3.py | def load(self, filename, ID3=None, **kwargs):
"""Load stream and tag information from a file.
A custom tag reader may be used in instead of the default
mutagen.id3.ID3 object, e.g. an EasyID3 reader.
"""
if ID3 is None:
ID3 = self.ID3
else:
# If this was initialized with EasyID3, remember that for
# when tags are auto-instantiated in add_tags.
self.ID3 = ID3
self.filename = filename
try:
self.tags = ID3(filename, **kwargs)
except error:
self.tags = None
if self.tags is not None:
try:
offset = self.tags.size
except AttributeError:
offset = None
else:
offset = None
try:
fileobj = open(filename, "rb")
self.info = self._Info(fileobj, offset)
finally:
fileobj.close() | def load(self, filename, ID3=None, **kwargs):
"""Load stream and tag information from a file.
A custom tag reader may be used in instead of the default
mutagen.id3.ID3 object, e.g. an EasyID3 reader.
"""
if ID3 is None:
ID3 = self.ID3
else:
# If this was initialized with EasyID3, remember that for
# when tags are auto-instantiated in add_tags.
self.ID3 = ID3
self.filename = filename
try:
self.tags = ID3(filename, **kwargs)
except error:
self.tags = None
if self.tags is not None:
try:
offset = self.tags.size
except AttributeError:
offset = None
else:
offset = None
try:
fileobj = open(filename, "rb")
self.info = self._Info(fileobj, offset)
finally:
fileobj.close() | [
"Load",
"stream",
"and",
"tag",
"information",
"from",
"a",
"file",
"."
] | LordSputnik/mutagen | python | https://github.com/LordSputnik/mutagen/blob/38e62c8dc35c72b16554f5dbe7c0fde91acc3411/mutagen/id3.py#L923-L952 | [
"def",
"load",
"(",
"self",
",",
"filename",
",",
"ID3",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"ID3",
"is",
"None",
":",
"ID3",
"=",
"self",
".",
"ID3",
"else",
":",
"# If this was initialized with EasyID3, remember that for",
"# when tags are auto-instantiated in add_tags.",
"self",
".",
"ID3",
"=",
"ID3",
"self",
".",
"filename",
"=",
"filename",
"try",
":",
"self",
".",
"tags",
"=",
"ID3",
"(",
"filename",
",",
"*",
"*",
"kwargs",
")",
"except",
"error",
":",
"self",
".",
"tags",
"=",
"None",
"if",
"self",
".",
"tags",
"is",
"not",
"None",
":",
"try",
":",
"offset",
"=",
"self",
".",
"tags",
".",
"size",
"except",
"AttributeError",
":",
"offset",
"=",
"None",
"else",
":",
"offset",
"=",
"None",
"try",
":",
"fileobj",
"=",
"open",
"(",
"filename",
",",
"\"rb\"",
")",
"self",
".",
"info",
"=",
"self",
".",
"_Info",
"(",
"fileobj",
",",
"offset",
")",
"finally",
":",
"fileobj",
".",
"close",
"(",
")"
] | 38e62c8dc35c72b16554f5dbe7c0fde91acc3411 |
test | Sound.unload | Release all resources associated with the sound. | bacon/sound.py | def unload(self):
'''Release all resources associated with the sound.'''
if self._handle != -1:
lib.UnloadSound(self._handle)
self._handle = -1 | def unload(self):
'''Release all resources associated with the sound.'''
if self._handle != -1:
lib.UnloadSound(self._handle)
self._handle = -1 | [
"Release",
"all",
"resources",
"associated",
"with",
"the",
"sound",
"."
] | aholkner/bacon | python | https://github.com/aholkner/bacon/blob/edf3810dcb211942d392a8637945871399b0650d/bacon/sound.py#L41-L45 | [
"def",
"unload",
"(",
"self",
")",
":",
"if",
"self",
".",
"_handle",
"!=",
"-",
"1",
":",
"lib",
".",
"UnloadSound",
"(",
"self",
".",
"_handle",
")",
"self",
".",
"_handle",
"=",
"-",
"1"
] | edf3810dcb211942d392a8637945871399b0650d |
test | Sound.play | Play the sound as a `one-shot`.
The sound will be played to completion. If the sound is played more than once at a time, it will mix
with all previous instances of itself. If you need more control over the playback of sounds, see
:class:`Voice`.
:param gain: optional volume level to play the sound back at, between 0.0 and 1.0 (defaults to 1.0)
:param pan: optional stereo pan, between -1.0 (left) and 1.0 (right)
:param pitch: optional sampling rate modification, between 0.4 and 16.0, where 1.0 represents the original pitch | bacon/sound.py | def play(self, gain=None, pan=None, pitch=None):
'''Play the sound as a `one-shot`.
The sound will be played to completion. If the sound is played more than once at a time, it will mix
with all previous instances of itself. If you need more control over the playback of sounds, see
:class:`Voice`.
:param gain: optional volume level to play the sound back at, between 0.0 and 1.0 (defaults to 1.0)
:param pan: optional stereo pan, between -1.0 (left) and 1.0 (right)
:param pitch: optional sampling rate modification, between 0.4 and 16.0, where 1.0 represents the original pitch
'''
if gain is None and pan is None and pitch is None:
lib.PlaySound(self._handle)
else:
voice = Voice(self)
if gain is not None:
voice.gain = gain
if pan is not None:
voice.pan = pan
if pitch is not None:
voice.pitch = pitch
voice.play() | def play(self, gain=None, pan=None, pitch=None):
'''Play the sound as a `one-shot`.
The sound will be played to completion. If the sound is played more than once at a time, it will mix
with all previous instances of itself. If you need more control over the playback of sounds, see
:class:`Voice`.
:param gain: optional volume level to play the sound back at, between 0.0 and 1.0 (defaults to 1.0)
:param pan: optional stereo pan, between -1.0 (left) and 1.0 (right)
:param pitch: optional sampling rate modification, between 0.4 and 16.0, where 1.0 represents the original pitch
'''
if gain is None and pan is None and pitch is None:
lib.PlaySound(self._handle)
else:
voice = Voice(self)
if gain is not None:
voice.gain = gain
if pan is not None:
voice.pan = pan
if pitch is not None:
voice.pitch = pitch
voice.play() | [
"Play",
"the",
"sound",
"as",
"a",
"one",
"-",
"shot",
"."
] | aholkner/bacon | python | https://github.com/aholkner/bacon/blob/edf3810dcb211942d392a8637945871399b0650d/bacon/sound.py#L47-L68 | [
"def",
"play",
"(",
"self",
",",
"gain",
"=",
"None",
",",
"pan",
"=",
"None",
",",
"pitch",
"=",
"None",
")",
":",
"if",
"gain",
"is",
"None",
"and",
"pan",
"is",
"None",
"and",
"pitch",
"is",
"None",
":",
"lib",
".",
"PlaySound",
"(",
"self",
".",
"_handle",
")",
"else",
":",
"voice",
"=",
"Voice",
"(",
"self",
")",
"if",
"gain",
"is",
"not",
"None",
":",
"voice",
".",
"gain",
"=",
"gain",
"if",
"pan",
"is",
"not",
"None",
":",
"voice",
".",
"pan",
"=",
"pan",
"if",
"pitch",
"is",
"not",
"None",
":",
"voice",
".",
"pitch",
"=",
"pitch",
"voice",
".",
"play",
"(",
")"
] | edf3810dcb211942d392a8637945871399b0650d |
test | Voice.set_loop_points | Set the loop points within the sound.
The sound must have been created with ``loop=True``. The default parameters cause the loop points to be set to
the entire sound duration.
:note: There is currently no API for converting sample numbers to times.
:param start_sample: sample number to loop back to
:param end_sample: sample number to loop at | bacon/sound.py | def set_loop_points(self, start_sample=-1, end_sample=0):
'''Set the loop points within the sound.
The sound must have been created with ``loop=True``. The default parameters cause the loop points to be set to
the entire sound duration.
:note: There is currently no API for converting sample numbers to times.
:param start_sample: sample number to loop back to
:param end_sample: sample number to loop at
'''
lib.SetVoiceLoopPoints(self._handle, start_sample, end_sample) | def set_loop_points(self, start_sample=-1, end_sample=0):
'''Set the loop points within the sound.
The sound must have been created with ``loop=True``. The default parameters cause the loop points to be set to
the entire sound duration.
:note: There is currently no API for converting sample numbers to times.
:param start_sample: sample number to loop back to
:param end_sample: sample number to loop at
'''
lib.SetVoiceLoopPoints(self._handle, start_sample, end_sample) | [
"Set",
"the",
"loop",
"points",
"within",
"the",
"sound",
"."
] | aholkner/bacon | python | https://github.com/aholkner/bacon/blob/edf3810dcb211942d392a8637945871399b0650d/bacon/sound.py#L169-L179 | [
"def",
"set_loop_points",
"(",
"self",
",",
"start_sample",
"=",
"-",
"1",
",",
"end_sample",
"=",
"0",
")",
":",
"lib",
".",
"SetVoiceLoopPoints",
"(",
"self",
".",
"_handle",
",",
"start_sample",
",",
"end_sample",
")"
] | edf3810dcb211942d392a8637945871399b0650d |
test | list_hosted_zones_parser | Parses the API responses for the
:py:meth:`route53.connection.Route53Connection.list_hosted_zones` method.
:param lxml.etree._Element root: The root node of the etree parsed
response from the API.
:param Route53Connection connection: The connection instance used to
query the API.
:rtype: HostedZone
:returns: A generator of fully formed HostedZone instances. | route53/xml_parsers/list_hosted_zones.py | def list_hosted_zones_parser(root, connection):
"""
Parses the API responses for the
:py:meth:`route53.connection.Route53Connection.list_hosted_zones` method.
:param lxml.etree._Element root: The root node of the etree parsed
response from the API.
:param Route53Connection connection: The connection instance used to
query the API.
:rtype: HostedZone
:returns: A generator of fully formed HostedZone instances.
"""
# The rest of the list pagination tags are handled higher up in the stack.
# We'll just worry about the HostedZones tag, which has HostedZone tags
# nested beneath it.
zones = root.find('./{*}HostedZones')
for zone in zones:
yield parse_hosted_zone(zone, connection) | def list_hosted_zones_parser(root, connection):
"""
Parses the API responses for the
:py:meth:`route53.connection.Route53Connection.list_hosted_zones` method.
:param lxml.etree._Element root: The root node of the etree parsed
response from the API.
:param Route53Connection connection: The connection instance used to
query the API.
:rtype: HostedZone
:returns: A generator of fully formed HostedZone instances.
"""
# The rest of the list pagination tags are handled higher up in the stack.
# We'll just worry about the HostedZones tag, which has HostedZone tags
# nested beneath it.
zones = root.find('./{*}HostedZones')
for zone in zones:
yield parse_hosted_zone(zone, connection) | [
"Parses",
"the",
"API",
"responses",
"for",
"the",
":",
"py",
":",
"meth",
":",
"route53",
".",
"connection",
".",
"Route53Connection",
".",
"list_hosted_zones",
"method",
"."
] | gtaylor/python-route53 | python | https://github.com/gtaylor/python-route53/blob/b9fc7e258a79551c9ed61e4a71668b7f06f9e774/route53/xml_parsers/list_hosted_zones.py#L3-L22 | [
"def",
"list_hosted_zones_parser",
"(",
"root",
",",
"connection",
")",
":",
"# The rest of the list pagination tags are handled higher up in the stack.",
"# We'll just worry about the HostedZones tag, which has HostedZone tags",
"# nested beneath it.",
"zones",
"=",
"root",
".",
"find",
"(",
"'./{*}HostedZones'",
")",
"for",
"zone",
"in",
"zones",
":",
"yield",
"parse_hosted_zone",
"(",
"zone",
",",
"connection",
")"
] | b9fc7e258a79551c9ed61e4a71668b7f06f9e774 |
test | adobe_glyph_values | return the list of glyph names and their unicode values | native/Vendor/FreeType/src/tools/glnames.py | def adobe_glyph_values():
"""return the list of glyph names and their unicode values"""
lines = string.split( adobe_glyph_list, '\n' )
glyphs = []
values = []
for line in lines:
if line:
fields = string.split( line, ';' )
# print fields[1] + ' - ' + fields[0]
subfields = string.split( fields[1], ' ' )
if len( subfields ) == 1:
glyphs.append( fields[0] )
values.append( fields[1] )
return glyphs, values | def adobe_glyph_values():
"""return the list of glyph names and their unicode values"""
lines = string.split( adobe_glyph_list, '\n' )
glyphs = []
values = []
for line in lines:
if line:
fields = string.split( line, ';' )
# print fields[1] + ' - ' + fields[0]
subfields = string.split( fields[1], ' ' )
if len( subfields ) == 1:
glyphs.append( fields[0] )
values.append( fields[1] )
return glyphs, values | [
"return",
"the",
"list",
"of",
"glyph",
"names",
"and",
"their",
"unicode",
"values"
] | aholkner/bacon | python | https://github.com/aholkner/bacon/blob/edf3810dcb211942d392a8637945871399b0650d/native/Vendor/FreeType/src/tools/glnames.py#L5152-L5168 | [
"def",
"adobe_glyph_values",
"(",
")",
":",
"lines",
"=",
"string",
".",
"split",
"(",
"adobe_glyph_list",
",",
"'\\n'",
")",
"glyphs",
"=",
"[",
"]",
"values",
"=",
"[",
"]",
"for",
"line",
"in",
"lines",
":",
"if",
"line",
":",
"fields",
"=",
"string",
".",
"split",
"(",
"line",
",",
"';'",
")",
"# print fields[1] + ' - ' + fields[0]",
"subfields",
"=",
"string",
".",
"split",
"(",
"fields",
"[",
"1",
"]",
",",
"' '",
")",
"if",
"len",
"(",
"subfields",
")",
"==",
"1",
":",
"glyphs",
".",
"append",
"(",
"fields",
"[",
"0",
"]",
")",
"values",
".",
"append",
"(",
"fields",
"[",
"1",
"]",
")",
"return",
"glyphs",
",",
"values"
] | edf3810dcb211942d392a8637945871399b0650d |
test | filter_glyph_names | filter `alist' by taking _out_ all glyph names that are in `filter | native/Vendor/FreeType/src/tools/glnames.py | def filter_glyph_names( alist, filter ):
"""filter `alist' by taking _out_ all glyph names that are in `filter'"""
count = 0
extras = []
for name in alist:
try:
filtered_index = filter.index( name )
except:
extras.append( name )
return extras | def filter_glyph_names( alist, filter ):
"""filter `alist' by taking _out_ all glyph names that are in `filter'"""
count = 0
extras = []
for name in alist:
try:
filtered_index = filter.index( name )
except:
extras.append( name )
return extras | [
"filter",
"alist",
"by",
"taking",
"_out_",
"all",
"glyph",
"names",
"that",
"are",
"in",
"filter"
] | aholkner/bacon | python | https://github.com/aholkner/bacon/blob/edf3810dcb211942d392a8637945871399b0650d/native/Vendor/FreeType/src/tools/glnames.py#L5171-L5183 | [
"def",
"filter_glyph_names",
"(",
"alist",
",",
"filter",
")",
":",
"count",
"=",
"0",
"extras",
"=",
"[",
"]",
"for",
"name",
"in",
"alist",
":",
"try",
":",
"filtered_index",
"=",
"filter",
".",
"index",
"(",
"name",
")",
"except",
":",
"extras",
".",
"append",
"(",
"name",
")",
"return",
"extras"
] | edf3810dcb211942d392a8637945871399b0650d |
test | dump_encoding | dump a given encoding | native/Vendor/FreeType/src/tools/glnames.py | def dump_encoding( file, encoding_name, encoding_list ):
"""dump a given encoding"""
write = file.write
write( " /* the following are indices into the SID name table */\n" )
write( " static const unsigned short " + encoding_name +
"[" + repr( len( encoding_list ) ) + "] =\n" )
write( " {\n" )
line = " "
comma = ""
col = 0
for value in encoding_list:
line += comma
line += "%3d" % value
comma = ","
col += 1
if col == 16:
col = 0
comma = ",\n "
write( line + "\n };\n\n\n" ) | def dump_encoding( file, encoding_name, encoding_list ):
"""dump a given encoding"""
write = file.write
write( " /* the following are indices into the SID name table */\n" )
write( " static const unsigned short " + encoding_name +
"[" + repr( len( encoding_list ) ) + "] =\n" )
write( " {\n" )
line = " "
comma = ""
col = 0
for value in encoding_list:
line += comma
line += "%3d" % value
comma = ","
col += 1
if col == 16:
col = 0
comma = ",\n "
write( line + "\n };\n\n\n" ) | [
"dump",
"a",
"given",
"encoding"
] | aholkner/bacon | python | https://github.com/aholkner/bacon/blob/edf3810dcb211942d392a8637945871399b0650d/native/Vendor/FreeType/src/tools/glnames.py#L5186-L5207 | [
"def",
"dump_encoding",
"(",
"file",
",",
"encoding_name",
",",
"encoding_list",
")",
":",
"write",
"=",
"file",
".",
"write",
"write",
"(",
"\" /* the following are indices into the SID name table */\\n\"",
")",
"write",
"(",
"\" static const unsigned short \"",
"+",
"encoding_name",
"+",
"\"[\"",
"+",
"repr",
"(",
"len",
"(",
"encoding_list",
")",
")",
"+",
"\"] =\\n\"",
")",
"write",
"(",
"\" {\\n\"",
")",
"line",
"=",
"\" \"",
"comma",
"=",
"\"\"",
"col",
"=",
"0",
"for",
"value",
"in",
"encoding_list",
":",
"line",
"+=",
"comma",
"line",
"+=",
"\"%3d\"",
"%",
"value",
"comma",
"=",
"\",\"",
"col",
"+=",
"1",
"if",
"col",
"==",
"16",
":",
"col",
"=",
"0",
"comma",
"=",
"\",\\n \"",
"write",
"(",
"line",
"+",
"\"\\n };\\n\\n\\n\"",
")"
] | edf3810dcb211942d392a8637945871399b0650d |
test | dump_array | dumps a given encoding | native/Vendor/FreeType/src/tools/glnames.py | def dump_array( the_array, write, array_name ):
"""dumps a given encoding"""
write( " static const unsigned char " + array_name +
"[" + repr( len( the_array ) ) + "L] =\n" )
write( " {\n" )
line = ""
comma = " "
col = 0
for value in the_array:
line += comma
line += "%3d" % ord( value )
comma = ","
col += 1
if col == 16:
col = 0
comma = ",\n "
if len( line ) > 1024:
write( line )
line = ""
write( line + "\n };\n\n\n" ) | def dump_array( the_array, write, array_name ):
"""dumps a given encoding"""
write( " static const unsigned char " + array_name +
"[" + repr( len( the_array ) ) + "L] =\n" )
write( " {\n" )
line = ""
comma = " "
col = 0
for value in the_array:
line += comma
line += "%3d" % ord( value )
comma = ","
col += 1
if col == 16:
col = 0
comma = ",\n "
if len( line ) > 1024:
write( line )
line = ""
write( line + "\n };\n\n\n" ) | [
"dumps",
"a",
"given",
"encoding"
] | aholkner/bacon | python | https://github.com/aholkner/bacon/blob/edf3810dcb211942d392a8637945871399b0650d/native/Vendor/FreeType/src/tools/glnames.py#L5210-L5235 | [
"def",
"dump_array",
"(",
"the_array",
",",
"write",
",",
"array_name",
")",
":",
"write",
"(",
"\" static const unsigned char \"",
"+",
"array_name",
"+",
"\"[\"",
"+",
"repr",
"(",
"len",
"(",
"the_array",
")",
")",
"+",
"\"L] =\\n\"",
")",
"write",
"(",
"\" {\\n\"",
")",
"line",
"=",
"\"\"",
"comma",
"=",
"\" \"",
"col",
"=",
"0",
"for",
"value",
"in",
"the_array",
":",
"line",
"+=",
"comma",
"line",
"+=",
"\"%3d\"",
"%",
"ord",
"(",
"value",
")",
"comma",
"=",
"\",\"",
"col",
"+=",
"1",
"if",
"col",
"==",
"16",
":",
"col",
"=",
"0",
"comma",
"=",
"\",\\n \"",
"if",
"len",
"(",
"line",
")",
">",
"1024",
":",
"write",
"(",
"line",
")",
"line",
"=",
"\"\"",
"write",
"(",
"line",
"+",
"\"\\n };\\n\\n\\n\"",
")"
] | edf3810dcb211942d392a8637945871399b0650d |
test | main | main program body | native/Vendor/FreeType/src/tools/glnames.py | def main():
"""main program body"""
if len( sys.argv ) != 2:
print __doc__ % sys.argv[0]
sys.exit( 1 )
file = open( sys.argv[1], "w\n" )
write = file.write
count_sid = len( sid_standard_names )
# `mac_extras' contains the list of glyph names in the Macintosh standard
# encoding which are not in the SID Standard Names.
#
mac_extras = filter_glyph_names( mac_standard_names, sid_standard_names )
# `base_list' contains the names of our final glyph names table.
# It consists of the `mac_extras' glyph names, followed by the SID
# standard names.
#
mac_extras_count = len( mac_extras )
base_list = mac_extras + sid_standard_names
write( "/***************************************************************************/\n" )
write( "/* */\n" )
write( "/* %-71s*/\n" % os.path.basename( sys.argv[1] ) )
write( "/* */\n" )
write( "/* PostScript glyph names. */\n" )
write( "/* */\n" )
write( "/* Copyright 2005, 2008, 2011 by */\n" )
write( "/* David Turner, Robert Wilhelm, and Werner Lemberg. */\n" )
write( "/* */\n" )
write( "/* This file is part of the FreeType project, and may only be used, */\n" )
write( "/* modified, and distributed under the terms of the FreeType project */\n" )
write( "/* license, LICENSE.TXT. By continuing to use, modify, or distribute */\n" )
write( "/* this file you indicate that you have read the license and */\n" )
write( "/* understand and accept it fully. */\n" )
write( "/* */\n" )
write( "/***************************************************************************/\n" )
write( "\n" )
write( "\n" )
write( " /* This file has been generated automatically -- do not edit! */\n" )
write( "\n" )
write( "\n" )
# dump final glyph list (mac extras + sid standard names)
#
st = StringTable( base_list, "ft_standard_glyph_names" )
st.dump( file )
st.dump_sublist( file, "ft_mac_names",
"FT_NUM_MAC_NAMES", mac_standard_names )
st.dump_sublist( file, "ft_sid_names",
"FT_NUM_SID_NAMES", sid_standard_names )
dump_encoding( file, "t1_standard_encoding", t1_standard_encoding )
dump_encoding( file, "t1_expert_encoding", t1_expert_encoding )
# dump the AGL in its compressed form
#
agl_glyphs, agl_values = adobe_glyph_values()
dict = StringNode( "", 0 )
for g in range( len( agl_glyphs ) ):
dict.add( agl_glyphs[g], eval( "0x" + agl_values[g] ) )
dict = dict.optimize()
dict_len = dict.locate( 0 )
dict_array = dict.store( "" )
write( """\
/*
* This table is a compressed version of the Adobe Glyph List (AGL),
* optimized for efficient searching. It has been generated by the
* `glnames.py' python script located in the `src/tools' directory.
*
* The lookup function to get the Unicode value for a given string
* is defined below the table.
*/
#ifdef FT_CONFIG_OPTION_ADOBE_GLYPH_LIST
""" )
dump_array( dict_array, write, "ft_adobe_glyph_list" )
# write the lookup routine now
#
write( """\
/*
* This function searches the compressed table efficiently.
*/
static unsigned long
ft_get_adobe_glyph_index( const char* name,
const char* limit )
{
int c = 0;
int count, min, max;
const unsigned char* p = ft_adobe_glyph_list;
if ( name == 0 || name >= limit )
goto NotFound;
c = *name++;
count = p[1];
p += 2;
min = 0;
max = count;
while ( min < max )
{
int mid = ( min + max ) >> 1;
const unsigned char* q = p + mid * 2;
int c2;
q = ft_adobe_glyph_list + ( ( (int)q[0] << 8 ) | q[1] );
c2 = q[0] & 127;
if ( c2 == c )
{
p = q;
goto Found;
}
if ( c2 < c )
min = mid + 1;
else
max = mid;
}
goto NotFound;
Found:
for (;;)
{
/* assert (*p & 127) == c */
if ( name >= limit )
{
if ( (p[0] & 128) == 0 &&
(p[1] & 128) != 0 )
return (unsigned long)( ( (int)p[2] << 8 ) | p[3] );
goto NotFound;
}
c = *name++;
if ( p[0] & 128 )
{
p++;
if ( c != (p[0] & 127) )
goto NotFound;
continue;
}
p++;
count = p[0] & 127;
if ( p[0] & 128 )
p += 2;
p++;
for ( ; count > 0; count--, p += 2 )
{
int offset = ( (int)p[0] << 8 ) | p[1];
const unsigned char* q = ft_adobe_glyph_list + offset;
if ( c == ( q[0] & 127 ) )
{
p = q;
goto NextIter;
}
}
goto NotFound;
NextIter:
;
}
NotFound:
return 0;
}
#endif /* FT_CONFIG_OPTION_ADOBE_GLYPH_LIST */
""" )
if 0: # generate unit test, or don't
#
# now write the unit test to check that everything works OK
#
write( "#ifdef TEST\n\n" )
write( "static const char* const the_names[] = {\n" )
for name in agl_glyphs:
write( ' "' + name + '",\n' )
write( " 0\n};\n" )
write( "static const unsigned long the_values[] = {\n" )
for val in agl_values:
write( ' 0x' + val + ',\n' )
write( " 0\n};\n" )
write( """
#include <stdlib.h>
#include <stdio.h>
int
main( void )
{
int result = 0;
const char* const* names = the_names;
const unsigned long* values = the_values;
for ( ; *names; names++, values++ )
{
const char* name = *names;
unsigned long reference = *values;
unsigned long value;
value = ft_get_adobe_glyph_index( name, name + strlen( name ) );
if ( value != reference )
{
result = 1;
fprintf( stderr, "name '%s' => %04x instead of %04x\\n",
name, value, reference );
}
}
return result;
}
""" )
write( "#endif /* TEST */\n" )
write("\n/* END */\n") | def main():
"""main program body"""
if len( sys.argv ) != 2:
print __doc__ % sys.argv[0]
sys.exit( 1 )
file = open( sys.argv[1], "w\n" )
write = file.write
count_sid = len( sid_standard_names )
# `mac_extras' contains the list of glyph names in the Macintosh standard
# encoding which are not in the SID Standard Names.
#
mac_extras = filter_glyph_names( mac_standard_names, sid_standard_names )
# `base_list' contains the names of our final glyph names table.
# It consists of the `mac_extras' glyph names, followed by the SID
# standard names.
#
mac_extras_count = len( mac_extras )
base_list = mac_extras + sid_standard_names
write( "/***************************************************************************/\n" )
write( "/* */\n" )
write( "/* %-71s*/\n" % os.path.basename( sys.argv[1] ) )
write( "/* */\n" )
write( "/* PostScript glyph names. */\n" )
write( "/* */\n" )
write( "/* Copyright 2005, 2008, 2011 by */\n" )
write( "/* David Turner, Robert Wilhelm, and Werner Lemberg. */\n" )
write( "/* */\n" )
write( "/* This file is part of the FreeType project, and may only be used, */\n" )
write( "/* modified, and distributed under the terms of the FreeType project */\n" )
write( "/* license, LICENSE.TXT. By continuing to use, modify, or distribute */\n" )
write( "/* this file you indicate that you have read the license and */\n" )
write( "/* understand and accept it fully. */\n" )
write( "/* */\n" )
write( "/***************************************************************************/\n" )
write( "\n" )
write( "\n" )
write( " /* This file has been generated automatically -- do not edit! */\n" )
write( "\n" )
write( "\n" )
# dump final glyph list (mac extras + sid standard names)
#
st = StringTable( base_list, "ft_standard_glyph_names" )
st.dump( file )
st.dump_sublist( file, "ft_mac_names",
"FT_NUM_MAC_NAMES", mac_standard_names )
st.dump_sublist( file, "ft_sid_names",
"FT_NUM_SID_NAMES", sid_standard_names )
dump_encoding( file, "t1_standard_encoding", t1_standard_encoding )
dump_encoding( file, "t1_expert_encoding", t1_expert_encoding )
# dump the AGL in its compressed form
#
agl_glyphs, agl_values = adobe_glyph_values()
dict = StringNode( "", 0 )
for g in range( len( agl_glyphs ) ):
dict.add( agl_glyphs[g], eval( "0x" + agl_values[g] ) )
dict = dict.optimize()
dict_len = dict.locate( 0 )
dict_array = dict.store( "" )
write( """\
/*
* This table is a compressed version of the Adobe Glyph List (AGL),
* optimized for efficient searching. It has been generated by the
* `glnames.py' python script located in the `src/tools' directory.
*
* The lookup function to get the Unicode value for a given string
* is defined below the table.
*/
#ifdef FT_CONFIG_OPTION_ADOBE_GLYPH_LIST
""" )
dump_array( dict_array, write, "ft_adobe_glyph_list" )
# write the lookup routine now
#
write( """\
/*
* This function searches the compressed table efficiently.
*/
static unsigned long
ft_get_adobe_glyph_index( const char* name,
const char* limit )
{
int c = 0;
int count, min, max;
const unsigned char* p = ft_adobe_glyph_list;
if ( name == 0 || name >= limit )
goto NotFound;
c = *name++;
count = p[1];
p += 2;
min = 0;
max = count;
while ( min < max )
{
int mid = ( min + max ) >> 1;
const unsigned char* q = p + mid * 2;
int c2;
q = ft_adobe_glyph_list + ( ( (int)q[0] << 8 ) | q[1] );
c2 = q[0] & 127;
if ( c2 == c )
{
p = q;
goto Found;
}
if ( c2 < c )
min = mid + 1;
else
max = mid;
}
goto NotFound;
Found:
for (;;)
{
/* assert (*p & 127) == c */
if ( name >= limit )
{
if ( (p[0] & 128) == 0 &&
(p[1] & 128) != 0 )
return (unsigned long)( ( (int)p[2] << 8 ) | p[3] );
goto NotFound;
}
c = *name++;
if ( p[0] & 128 )
{
p++;
if ( c != (p[0] & 127) )
goto NotFound;
continue;
}
p++;
count = p[0] & 127;
if ( p[0] & 128 )
p += 2;
p++;
for ( ; count > 0; count--, p += 2 )
{
int offset = ( (int)p[0] << 8 ) | p[1];
const unsigned char* q = ft_adobe_glyph_list + offset;
if ( c == ( q[0] & 127 ) )
{
p = q;
goto NextIter;
}
}
goto NotFound;
NextIter:
;
}
NotFound:
return 0;
}
#endif /* FT_CONFIG_OPTION_ADOBE_GLYPH_LIST */
""" )
if 0: # generate unit test, or don't
#
# now write the unit test to check that everything works OK
#
write( "#ifdef TEST\n\n" )
write( "static const char* const the_names[] = {\n" )
for name in agl_glyphs:
write( ' "' + name + '",\n' )
write( " 0\n};\n" )
write( "static const unsigned long the_values[] = {\n" )
for val in agl_values:
write( ' 0x' + val + ',\n' )
write( " 0\n};\n" )
write( """
#include <stdlib.h>
#include <stdio.h>
int
main( void )
{
int result = 0;
const char* const* names = the_names;
const unsigned long* values = the_values;
for ( ; *names; names++, values++ )
{
const char* name = *names;
unsigned long reference = *values;
unsigned long value;
value = ft_get_adobe_glyph_index( name, name + strlen( name ) );
if ( value != reference )
{
result = 1;
fprintf( stderr, "name '%s' => %04x instead of %04x\\n",
name, value, reference );
}
}
return result;
}
""" )
write( "#endif /* TEST */\n" )
write("\n/* END */\n") | [
"main",
"program",
"body"
] | aholkner/bacon | python | https://github.com/aholkner/bacon/blob/edf3810dcb211942d392a8637945871399b0650d/native/Vendor/FreeType/src/tools/glnames.py#L5238-L5479 | [
"def",
"main",
"(",
")",
":",
"if",
"len",
"(",
"sys",
".",
"argv",
")",
"!=",
"2",
":",
"print",
"__doc__",
"%",
"sys",
".",
"argv",
"[",
"0",
"]",
"sys",
".",
"exit",
"(",
"1",
")",
"file",
"=",
"open",
"(",
"sys",
".",
"argv",
"[",
"1",
"]",
",",
"\"w\\n\"",
")",
"write",
"=",
"file",
".",
"write",
"count_sid",
"=",
"len",
"(",
"sid_standard_names",
")",
"# `mac_extras' contains the list of glyph names in the Macintosh standard",
"# encoding which are not in the SID Standard Names.",
"#",
"mac_extras",
"=",
"filter_glyph_names",
"(",
"mac_standard_names",
",",
"sid_standard_names",
")",
"# `base_list' contains the names of our final glyph names table.",
"# It consists of the `mac_extras' glyph names, followed by the SID",
"# standard names.",
"#",
"mac_extras_count",
"=",
"len",
"(",
"mac_extras",
")",
"base_list",
"=",
"mac_extras",
"+",
"sid_standard_names",
"write",
"(",
"\"/***************************************************************************/\\n\"",
")",
"write",
"(",
"\"/* */\\n\"",
")",
"write",
"(",
"\"/* %-71s*/\\n\"",
"%",
"os",
".",
"path",
".",
"basename",
"(",
"sys",
".",
"argv",
"[",
"1",
"]",
")",
")",
"write",
"(",
"\"/* */\\n\"",
")",
"write",
"(",
"\"/* PostScript glyph names. */\\n\"",
")",
"write",
"(",
"\"/* */\\n\"",
")",
"write",
"(",
"\"/* Copyright 2005, 2008, 2011 by */\\n\"",
")",
"write",
"(",
"\"/* David Turner, Robert Wilhelm, and Werner Lemberg. */\\n\"",
")",
"write",
"(",
"\"/* */\\n\"",
")",
"write",
"(",
"\"/* This file is part of the FreeType project, and may only be used, */\\n\"",
")",
"write",
"(",
"\"/* modified, and distributed under the terms of the FreeType project */\\n\"",
")",
"write",
"(",
"\"/* license, LICENSE.TXT. By continuing to use, modify, or distribute */\\n\"",
")",
"write",
"(",
"\"/* this file you indicate that you have read the license and */\\n\"",
")",
"write",
"(",
"\"/* understand and accept it fully. */\\n\"",
")",
"write",
"(",
"\"/* */\\n\"",
")",
"write",
"(",
"\"/***************************************************************************/\\n\"",
")",
"write",
"(",
"\"\\n\"",
")",
"write",
"(",
"\"\\n\"",
")",
"write",
"(",
"\" /* This file has been generated automatically -- do not edit! */\\n\"",
")",
"write",
"(",
"\"\\n\"",
")",
"write",
"(",
"\"\\n\"",
")",
"# dump final glyph list (mac extras + sid standard names)",
"#",
"st",
"=",
"StringTable",
"(",
"base_list",
",",
"\"ft_standard_glyph_names\"",
")",
"st",
".",
"dump",
"(",
"file",
")",
"st",
".",
"dump_sublist",
"(",
"file",
",",
"\"ft_mac_names\"",
",",
"\"FT_NUM_MAC_NAMES\"",
",",
"mac_standard_names",
")",
"st",
".",
"dump_sublist",
"(",
"file",
",",
"\"ft_sid_names\"",
",",
"\"FT_NUM_SID_NAMES\"",
",",
"sid_standard_names",
")",
"dump_encoding",
"(",
"file",
",",
"\"t1_standard_encoding\"",
",",
"t1_standard_encoding",
")",
"dump_encoding",
"(",
"file",
",",
"\"t1_expert_encoding\"",
",",
"t1_expert_encoding",
")",
"# dump the AGL in its compressed form",
"#",
"agl_glyphs",
",",
"agl_values",
"=",
"adobe_glyph_values",
"(",
")",
"dict",
"=",
"StringNode",
"(",
"\"\"",
",",
"0",
")",
"for",
"g",
"in",
"range",
"(",
"len",
"(",
"agl_glyphs",
")",
")",
":",
"dict",
".",
"add",
"(",
"agl_glyphs",
"[",
"g",
"]",
",",
"eval",
"(",
"\"0x\"",
"+",
"agl_values",
"[",
"g",
"]",
")",
")",
"dict",
"=",
"dict",
".",
"optimize",
"(",
")",
"dict_len",
"=",
"dict",
".",
"locate",
"(",
"0",
")",
"dict_array",
"=",
"dict",
".",
"store",
"(",
"\"\"",
")",
"write",
"(",
"\"\"\"\\\n /*\n * This table is a compressed version of the Adobe Glyph List (AGL),\n * optimized for efficient searching. It has been generated by the\n * `glnames.py' python script located in the `src/tools' directory.\n *\n * The lookup function to get the Unicode value for a given string\n * is defined below the table.\n */\n\n#ifdef FT_CONFIG_OPTION_ADOBE_GLYPH_LIST\n\n\"\"\"",
")",
"dump_array",
"(",
"dict_array",
",",
"write",
",",
"\"ft_adobe_glyph_list\"",
")",
"# write the lookup routine now",
"#",
"write",
"(",
"\"\"\"\\\n /*\n * This function searches the compressed table efficiently.\n */\n static unsigned long\n ft_get_adobe_glyph_index( const char* name,\n const char* limit )\n {\n int c = 0;\n int count, min, max;\n const unsigned char* p = ft_adobe_glyph_list;\n\n\n if ( name == 0 || name >= limit )\n goto NotFound;\n\n c = *name++;\n count = p[1];\n p += 2;\n\n min = 0;\n max = count;\n\n while ( min < max )\n {\n int mid = ( min + max ) >> 1;\n const unsigned char* q = p + mid * 2;\n int c2;\n\n\n q = ft_adobe_glyph_list + ( ( (int)q[0] << 8 ) | q[1] );\n\n c2 = q[0] & 127;\n if ( c2 == c )\n {\n p = q;\n goto Found;\n }\n if ( c2 < c )\n min = mid + 1;\n else\n max = mid;\n }\n goto NotFound;\n\n Found:\n for (;;)\n {\n /* assert (*p & 127) == c */\n\n if ( name >= limit )\n {\n if ( (p[0] & 128) == 0 &&\n (p[1] & 128) != 0 )\n return (unsigned long)( ( (int)p[2] << 8 ) | p[3] );\n\n goto NotFound;\n }\n c = *name++;\n if ( p[0] & 128 )\n {\n p++;\n if ( c != (p[0] & 127) )\n goto NotFound;\n\n continue;\n }\n\n p++;\n count = p[0] & 127;\n if ( p[0] & 128 )\n p += 2;\n\n p++;\n\n for ( ; count > 0; count--, p += 2 )\n {\n int offset = ( (int)p[0] << 8 ) | p[1];\n const unsigned char* q = ft_adobe_glyph_list + offset;\n\n if ( c == ( q[0] & 127 ) )\n {\n p = q;\n goto NextIter;\n }\n }\n goto NotFound;\n\n NextIter:\n ;\n }\n\n NotFound:\n return 0;\n }\n\n#endif /* FT_CONFIG_OPTION_ADOBE_GLYPH_LIST */\n\n\"\"\"",
")",
"if",
"0",
":",
"# generate unit test, or don't",
"#",
"# now write the unit test to check that everything works OK",
"#",
"write",
"(",
"\"#ifdef TEST\\n\\n\"",
")",
"write",
"(",
"\"static const char* const the_names[] = {\\n\"",
")",
"for",
"name",
"in",
"agl_glyphs",
":",
"write",
"(",
"' \"'",
"+",
"name",
"+",
"'\",\\n'",
")",
"write",
"(",
"\" 0\\n};\\n\"",
")",
"write",
"(",
"\"static const unsigned long the_values[] = {\\n\"",
")",
"for",
"val",
"in",
"agl_values",
":",
"write",
"(",
"' 0x'",
"+",
"val",
"+",
"',\\n'",
")",
"write",
"(",
"\" 0\\n};\\n\"",
")",
"write",
"(",
"\"\"\"\n#include <stdlib.h>\n#include <stdio.h>\n\n int\n main( void )\n {\n int result = 0;\n const char* const* names = the_names;\n const unsigned long* values = the_values;\n\n\n for ( ; *names; names++, values++ )\n {\n const char* name = *names;\n unsigned long reference = *values;\n unsigned long value;\n\n\n value = ft_get_adobe_glyph_index( name, name + strlen( name ) );\n if ( value != reference )\n {\n result = 1;\n fprintf( stderr, \"name '%s' => %04x instead of %04x\\\\n\",\n name, value, reference );\n }\n }\n\n return result;\n }\n\"\"\"",
")",
"write",
"(",
"\"#endif /* TEST */\\n\"",
")",
"write",
"(",
"\"\\n/* END */\\n\"",
")"
] | edf3810dcb211942d392a8637945871399b0650d |
test | file_exists | checks that a given file exists | native/Vendor/FreeType/src/tools/docmaker/utils.py | def file_exists( pathname ):
"""checks that a given file exists"""
result = 1
try:
file = open( pathname, "r" )
file.close()
except:
result = None
sys.stderr.write( pathname + " couldn't be accessed\n" )
return result | def file_exists( pathname ):
"""checks that a given file exists"""
result = 1
try:
file = open( pathname, "r" )
file.close()
except:
result = None
sys.stderr.write( pathname + " couldn't be accessed\n" )
return result | [
"checks",
"that",
"a",
"given",
"file",
"exists"
] | aholkner/bacon | python | https://github.com/aholkner/bacon/blob/edf3810dcb211942d392a8637945871399b0650d/native/Vendor/FreeType/src/tools/docmaker/utils.py#L93-L103 | [
"def",
"file_exists",
"(",
"pathname",
")",
":",
"result",
"=",
"1",
"try",
":",
"file",
"=",
"open",
"(",
"pathname",
",",
"\"r\"",
")",
"file",
".",
"close",
"(",
")",
"except",
":",
"result",
"=",
"None",
"sys",
".",
"stderr",
".",
"write",
"(",
"pathname",
"+",
"\" couldn't be accessed\\n\"",
")",
"return",
"result"
] | edf3810dcb211942d392a8637945871399b0650d |
test | make_file_list | builds a list of input files from command-line arguments | native/Vendor/FreeType/src/tools/docmaker/utils.py | def make_file_list( args = None ):
"""builds a list of input files from command-line arguments"""
file_list = []
# sys.stderr.write( repr( sys.argv[1 :] ) + '\n' )
if not args:
args = sys.argv[1 :]
for pathname in args:
if string.find( pathname, '*' ) >= 0:
newpath = glob.glob( pathname )
newpath.sort() # sort files -- this is important because
# of the order of files
else:
newpath = [pathname]
file_list.extend( newpath )
if len( file_list ) == 0:
file_list = None
else:
# now filter the file list to remove non-existing ones
file_list = filter( file_exists, file_list )
return file_list | def make_file_list( args = None ):
"""builds a list of input files from command-line arguments"""
file_list = []
# sys.stderr.write( repr( sys.argv[1 :] ) + '\n' )
if not args:
args = sys.argv[1 :]
for pathname in args:
if string.find( pathname, '*' ) >= 0:
newpath = glob.glob( pathname )
newpath.sort() # sort files -- this is important because
# of the order of files
else:
newpath = [pathname]
file_list.extend( newpath )
if len( file_list ) == 0:
file_list = None
else:
# now filter the file list to remove non-existing ones
file_list = filter( file_exists, file_list )
return file_list | [
"builds",
"a",
"list",
"of",
"input",
"files",
"from",
"command",
"-",
"line",
"arguments"
] | aholkner/bacon | python | https://github.com/aholkner/bacon/blob/edf3810dcb211942d392a8637945871399b0650d/native/Vendor/FreeType/src/tools/docmaker/utils.py#L106-L130 | [
"def",
"make_file_list",
"(",
"args",
"=",
"None",
")",
":",
"file_list",
"=",
"[",
"]",
"# sys.stderr.write( repr( sys.argv[1 :] ) + '\\n' )",
"if",
"not",
"args",
":",
"args",
"=",
"sys",
".",
"argv",
"[",
"1",
":",
"]",
"for",
"pathname",
"in",
"args",
":",
"if",
"string",
".",
"find",
"(",
"pathname",
",",
"'*'",
")",
">=",
"0",
":",
"newpath",
"=",
"glob",
".",
"glob",
"(",
"pathname",
")",
"newpath",
".",
"sort",
"(",
")",
"# sort files -- this is important because",
"# of the order of files",
"else",
":",
"newpath",
"=",
"[",
"pathname",
"]",
"file_list",
".",
"extend",
"(",
"newpath",
")",
"if",
"len",
"(",
"file_list",
")",
"==",
"0",
":",
"file_list",
"=",
"None",
"else",
":",
"# now filter the file list to remove non-existing ones",
"file_list",
"=",
"filter",
"(",
"file_exists",
",",
"file_list",
")",
"return",
"file_list"
] | edf3810dcb211942d392a8637945871399b0650d |
test | parse_hosted_zone | This a common parser that allows the passing of any valid HostedZone
tag. It will spit out the appropriate HostedZone object for the tag.
:param lxml.etree._Element e_zone: The root node of the etree parsed
response from the API.
:param Route53Connection connection: The connection instance used to
query the API.
:rtype: HostedZone
:returns: An instantiated HostedZone object. | route53/xml_parsers/common_hosted_zone.py | def parse_hosted_zone(e_zone, connection):
"""
This a common parser that allows the passing of any valid HostedZone
tag. It will spit out the appropriate HostedZone object for the tag.
:param lxml.etree._Element e_zone: The root node of the etree parsed
response from the API.
:param Route53Connection connection: The connection instance used to
query the API.
:rtype: HostedZone
:returns: An instantiated HostedZone object.
"""
# This dict will be used to instantiate a HostedZone instance to yield.
kwargs = {}
# Within HostedZone tags are a number of sub-tags that include info
# about the instance.
for e_field in e_zone:
# Cheesy way to strip off the namespace.
tag_name = e_field.tag.split('}')[1]
field_text = e_field.text
if tag_name == 'Config':
# Config has the Comment tag beneath it, needing
# special handling.
e_comment = e_field.find('./{*}Comment')
kwargs['comment'] = e_comment.text if e_comment is not None else None
continue
elif tag_name == 'Id':
# This comes back with a path prepended. Yank that sillyness.
field_text = field_text.strip('/hostedzone/')
# Map the XML tag name to a kwarg name.
kw_name = HOSTED_ZONE_TAG_TO_KWARG_MAP[tag_name]
# This will be the key/val pair used to instantiate the
# HostedZone instance.
kwargs[kw_name] = field_text
return HostedZone(connection, **kwargs) | def parse_hosted_zone(e_zone, connection):
"""
This a common parser that allows the passing of any valid HostedZone
tag. It will spit out the appropriate HostedZone object for the tag.
:param lxml.etree._Element e_zone: The root node of the etree parsed
response from the API.
:param Route53Connection connection: The connection instance used to
query the API.
:rtype: HostedZone
:returns: An instantiated HostedZone object.
"""
# This dict will be used to instantiate a HostedZone instance to yield.
kwargs = {}
# Within HostedZone tags are a number of sub-tags that include info
# about the instance.
for e_field in e_zone:
# Cheesy way to strip off the namespace.
tag_name = e_field.tag.split('}')[1]
field_text = e_field.text
if tag_name == 'Config':
# Config has the Comment tag beneath it, needing
# special handling.
e_comment = e_field.find('./{*}Comment')
kwargs['comment'] = e_comment.text if e_comment is not None else None
continue
elif tag_name == 'Id':
# This comes back with a path prepended. Yank that sillyness.
field_text = field_text.strip('/hostedzone/')
# Map the XML tag name to a kwarg name.
kw_name = HOSTED_ZONE_TAG_TO_KWARG_MAP[tag_name]
# This will be the key/val pair used to instantiate the
# HostedZone instance.
kwargs[kw_name] = field_text
return HostedZone(connection, **kwargs) | [
"This",
"a",
"common",
"parser",
"that",
"allows",
"the",
"passing",
"of",
"any",
"valid",
"HostedZone",
"tag",
".",
"It",
"will",
"spit",
"out",
"the",
"appropriate",
"HostedZone",
"object",
"for",
"the",
"tag",
"."
] | gtaylor/python-route53 | python | https://github.com/gtaylor/python-route53/blob/b9fc7e258a79551c9ed61e4a71668b7f06f9e774/route53/xml_parsers/common_hosted_zone.py#L17-L55 | [
"def",
"parse_hosted_zone",
"(",
"e_zone",
",",
"connection",
")",
":",
"# This dict will be used to instantiate a HostedZone instance to yield.",
"kwargs",
"=",
"{",
"}",
"# Within HostedZone tags are a number of sub-tags that include info",
"# about the instance.",
"for",
"e_field",
"in",
"e_zone",
":",
"# Cheesy way to strip off the namespace.",
"tag_name",
"=",
"e_field",
".",
"tag",
".",
"split",
"(",
"'}'",
")",
"[",
"1",
"]",
"field_text",
"=",
"e_field",
".",
"text",
"if",
"tag_name",
"==",
"'Config'",
":",
"# Config has the Comment tag beneath it, needing",
"# special handling.",
"e_comment",
"=",
"e_field",
".",
"find",
"(",
"'./{*}Comment'",
")",
"kwargs",
"[",
"'comment'",
"]",
"=",
"e_comment",
".",
"text",
"if",
"e_comment",
"is",
"not",
"None",
"else",
"None",
"continue",
"elif",
"tag_name",
"==",
"'Id'",
":",
"# This comes back with a path prepended. Yank that sillyness.",
"field_text",
"=",
"field_text",
".",
"strip",
"(",
"'/hostedzone/'",
")",
"# Map the XML tag name to a kwarg name.",
"kw_name",
"=",
"HOSTED_ZONE_TAG_TO_KWARG_MAP",
"[",
"tag_name",
"]",
"# This will be the key/val pair used to instantiate the",
"# HostedZone instance.",
"kwargs",
"[",
"kw_name",
"]",
"=",
"field_text",
"return",
"HostedZone",
"(",
"connection",
",",
"*",
"*",
"kwargs",
")"
] | b9fc7e258a79551c9ed61e4a71668b7f06f9e774 |
test | parse_delegation_set | Parses a DelegationSet tag. These often accompany HostedZone tags in
responses like CreateHostedZone and GetHostedZone.
:param HostedZone zone: An existing HostedZone instance to populate.
:param lxml.etree._Element e_delegation_set: A DelegationSet element. | route53/xml_parsers/common_hosted_zone.py | def parse_delegation_set(zone, e_delegation_set):
"""
Parses a DelegationSet tag. These often accompany HostedZone tags in
responses like CreateHostedZone and GetHostedZone.
:param HostedZone zone: An existing HostedZone instance to populate.
:param lxml.etree._Element e_delegation_set: A DelegationSet element.
"""
e_nameservers = e_delegation_set.find('./{*}NameServers')
nameservers = []
for e_nameserver in e_nameservers:
nameservers.append(e_nameserver.text)
zone._nameservers = nameservers | def parse_delegation_set(zone, e_delegation_set):
"""
Parses a DelegationSet tag. These often accompany HostedZone tags in
responses like CreateHostedZone and GetHostedZone.
:param HostedZone zone: An existing HostedZone instance to populate.
:param lxml.etree._Element e_delegation_set: A DelegationSet element.
"""
e_nameservers = e_delegation_set.find('./{*}NameServers')
nameservers = []
for e_nameserver in e_nameservers:
nameservers.append(e_nameserver.text)
zone._nameservers = nameservers | [
"Parses",
"a",
"DelegationSet",
"tag",
".",
"These",
"often",
"accompany",
"HostedZone",
"tags",
"in",
"responses",
"like",
"CreateHostedZone",
"and",
"GetHostedZone",
"."
] | gtaylor/python-route53 | python | https://github.com/gtaylor/python-route53/blob/b9fc7e258a79551c9ed61e4a71668b7f06f9e774/route53/xml_parsers/common_hosted_zone.py#L57-L72 | [
"def",
"parse_delegation_set",
"(",
"zone",
",",
"e_delegation_set",
")",
":",
"e_nameservers",
"=",
"e_delegation_set",
".",
"find",
"(",
"'./{*}NameServers'",
")",
"nameservers",
"=",
"[",
"]",
"for",
"e_nameserver",
"in",
"e_nameservers",
":",
"nameservers",
".",
"append",
"(",
"e_nameserver",
".",
"text",
")",
"zone",
".",
"_nameservers",
"=",
"nameservers"
] | b9fc7e258a79551c9ed61e4a71668b7f06f9e774 |
test | MetadataBlock.writeblocks | Render metadata block as a byte string. | mutagen/flac.py | def writeblocks(blocks):
"""Render metadata block as a byte string."""
data = []
codes = [[block.code, block.write()] for block in blocks]
codes[-1][0] |= 128
for code, datum in codes:
byte = chr_(code)
if len(datum) > 2**24:
raise error("block is too long to write")
length = struct.pack(">I", len(datum))[-3:]
data.append(byte + length + datum)
return b"".join(data) | def writeblocks(blocks):
"""Render metadata block as a byte string."""
data = []
codes = [[block.code, block.write()] for block in blocks]
codes[-1][0] |= 128
for code, datum in codes:
byte = chr_(code)
if len(datum) > 2**24:
raise error("block is too long to write")
length = struct.pack(">I", len(datum))[-3:]
data.append(byte + length + datum)
return b"".join(data) | [
"Render",
"metadata",
"block",
"as",
"a",
"byte",
"string",
"."
] | LordSputnik/mutagen | python | https://github.com/LordSputnik/mutagen/blob/38e62c8dc35c72b16554f5dbe7c0fde91acc3411/mutagen/flac.py#L109-L120 | [
"def",
"writeblocks",
"(",
"blocks",
")",
":",
"data",
"=",
"[",
"]",
"codes",
"=",
"[",
"[",
"block",
".",
"code",
",",
"block",
".",
"write",
"(",
")",
"]",
"for",
"block",
"in",
"blocks",
"]",
"codes",
"[",
"-",
"1",
"]",
"[",
"0",
"]",
"|=",
"128",
"for",
"code",
",",
"datum",
"in",
"codes",
":",
"byte",
"=",
"chr_",
"(",
"code",
")",
"if",
"len",
"(",
"datum",
")",
">",
"2",
"**",
"24",
":",
"raise",
"error",
"(",
"\"block is too long to write\"",
")",
"length",
"=",
"struct",
".",
"pack",
"(",
"\">I\"",
",",
"len",
"(",
"datum",
")",
")",
"[",
"-",
"3",
":",
"]",
"data",
".",
"append",
"(",
"byte",
"+",
"length",
"+",
"datum",
")",
"return",
"b\"\"",
".",
"join",
"(",
"data",
")"
] | 38e62c8dc35c72b16554f5dbe7c0fde91acc3411 |
test | MetadataBlock.group_padding | Consolidate FLAC padding metadata blocks.
The overall size of the rendered blocks does not change, so
this adds several bytes of padding for each merged block. | mutagen/flac.py | def group_padding(blocks):
"""Consolidate FLAC padding metadata blocks.
The overall size of the rendered blocks does not change, so
this adds several bytes of padding for each merged block.
"""
paddings = [b for b in blocks if isinstance(b, Padding)]
for p in paddings:
blocks.remove(p)
# total padding size is the sum of padding sizes plus 4 bytes
# per removed header.
size = sum(padding.length for padding in paddings)
padding = Padding()
padding.length = size + 4 * (len(paddings) - 1)
blocks.append(padding) | def group_padding(blocks):
"""Consolidate FLAC padding metadata blocks.
The overall size of the rendered blocks does not change, so
this adds several bytes of padding for each merged block.
"""
paddings = [b for b in blocks if isinstance(b, Padding)]
for p in paddings:
blocks.remove(p)
# total padding size is the sum of padding sizes plus 4 bytes
# per removed header.
size = sum(padding.length for padding in paddings)
padding = Padding()
padding.length = size + 4 * (len(paddings) - 1)
blocks.append(padding) | [
"Consolidate",
"FLAC",
"padding",
"metadata",
"blocks",
"."
] | LordSputnik/mutagen | python | https://github.com/LordSputnik/mutagen/blob/38e62c8dc35c72b16554f5dbe7c0fde91acc3411/mutagen/flac.py#L123-L138 | [
"def",
"group_padding",
"(",
"blocks",
")",
":",
"paddings",
"=",
"[",
"b",
"for",
"b",
"in",
"blocks",
"if",
"isinstance",
"(",
"b",
",",
"Padding",
")",
"]",
"for",
"p",
"in",
"paddings",
":",
"blocks",
".",
"remove",
"(",
"p",
")",
"# total padding size is the sum of padding sizes plus 4 bytes",
"# per removed header.",
"size",
"=",
"sum",
"(",
"padding",
".",
"length",
"for",
"padding",
"in",
"paddings",
")",
"padding",
"=",
"Padding",
"(",
")",
"padding",
".",
"length",
"=",
"size",
"+",
"4",
"*",
"(",
"len",
"(",
"paddings",
")",
"-",
"1",
")",
"blocks",
".",
"append",
"(",
"padding",
")"
] | 38e62c8dc35c72b16554f5dbe7c0fde91acc3411 |
test | FLAC.delete | Remove Vorbis comments from a file.
If no filename is given, the one most recently loaded is used. | mutagen/flac.py | def delete(self, filename=None):
"""Remove Vorbis comments from a file.
If no filename is given, the one most recently loaded is used.
"""
if filename is None:
filename = self.filename
for s in list(self.metadata_blocks):
if isinstance(s, VCFLACDict):
self.metadata_blocks.remove(s)
self.tags = None
self.save()
break | def delete(self, filename=None):
"""Remove Vorbis comments from a file.
If no filename is given, the one most recently loaded is used.
"""
if filename is None:
filename = self.filename
for s in list(self.metadata_blocks):
if isinstance(s, VCFLACDict):
self.metadata_blocks.remove(s)
self.tags = None
self.save()
break | [
"Remove",
"Vorbis",
"comments",
"from",
"a",
"file",
"."
] | LordSputnik/mutagen | python | https://github.com/LordSputnik/mutagen/blob/38e62c8dc35c72b16554f5dbe7c0fde91acc3411/mutagen/flac.py#L686-L698 | [
"def",
"delete",
"(",
"self",
",",
"filename",
"=",
"None",
")",
":",
"if",
"filename",
"is",
"None",
":",
"filename",
"=",
"self",
".",
"filename",
"for",
"s",
"in",
"list",
"(",
"self",
".",
"metadata_blocks",
")",
":",
"if",
"isinstance",
"(",
"s",
",",
"VCFLACDict",
")",
":",
"self",
".",
"metadata_blocks",
".",
"remove",
"(",
"s",
")",
"self",
".",
"tags",
"=",
"None",
"self",
".",
"save",
"(",
")",
"break"
] | 38e62c8dc35c72b16554f5dbe7c0fde91acc3411 |
test | FLAC.load | Load file information from a filename. | mutagen/flac.py | def load(self, filename):
"""Load file information from a filename."""
self.metadata_blocks = []
self.tags = None
self.cuesheet = None
self.seektable = None
self.filename = filename
fileobj = StrictFileObject(open(filename, "rb"))
try:
self.__check_header(fileobj)
while self.__read_metadata_block(fileobj):
pass
finally:
fileobj.close()
try:
self.metadata_blocks[0].length
except (AttributeError, IndexError):
raise FLACNoHeaderError("Stream info block not found") | def load(self, filename):
"""Load file information from a filename."""
self.metadata_blocks = []
self.tags = None
self.cuesheet = None
self.seektable = None
self.filename = filename
fileobj = StrictFileObject(open(filename, "rb"))
try:
self.__check_header(fileobj)
while self.__read_metadata_block(fileobj):
pass
finally:
fileobj.close()
try:
self.metadata_blocks[0].length
except (AttributeError, IndexError):
raise FLACNoHeaderError("Stream info block not found") | [
"Load",
"file",
"information",
"from",
"a",
"filename",
"."
] | LordSputnik/mutagen | python | https://github.com/LordSputnik/mutagen/blob/38e62c8dc35c72b16554f5dbe7c0fde91acc3411/mutagen/flac.py#L702-L721 | [
"def",
"load",
"(",
"self",
",",
"filename",
")",
":",
"self",
".",
"metadata_blocks",
"=",
"[",
"]",
"self",
".",
"tags",
"=",
"None",
"self",
".",
"cuesheet",
"=",
"None",
"self",
".",
"seektable",
"=",
"None",
"self",
".",
"filename",
"=",
"filename",
"fileobj",
"=",
"StrictFileObject",
"(",
"open",
"(",
"filename",
",",
"\"rb\"",
")",
")",
"try",
":",
"self",
".",
"__check_header",
"(",
"fileobj",
")",
"while",
"self",
".",
"__read_metadata_block",
"(",
"fileobj",
")",
":",
"pass",
"finally",
":",
"fileobj",
".",
"close",
"(",
")",
"try",
":",
"self",
".",
"metadata_blocks",
"[",
"0",
"]",
".",
"length",
"except",
"(",
"AttributeError",
",",
"IndexError",
")",
":",
"raise",
"FLACNoHeaderError",
"(",
"\"Stream info block not found\"",
")"
] | 38e62c8dc35c72b16554f5dbe7c0fde91acc3411 |
test | FLAC.save | Save metadata blocks to a file.
If no filename is given, the one most recently loaded is used. | mutagen/flac.py | def save(self, filename=None, deleteid3=False):
"""Save metadata blocks to a file.
If no filename is given, the one most recently loaded is used.
"""
if filename is None:
filename = self.filename
f = open(filename, 'rb+')
try:
# Ensure we've got padding at the end, and only at the end.
# If adding makes it too large, we'll scale it down later.
self.metadata_blocks.append(Padding(b'\x00' * 1020))
MetadataBlock.group_padding(self.metadata_blocks)
header = self.__check_header(f)
# "fLaC" and maybe ID3
available = self.__find_audio_offset(f) - header
data = MetadataBlock.writeblocks(self.metadata_blocks)
# Delete ID3v2
if deleteid3 and header > 4:
available += header - 4
header = 4
if len(data) > available:
# If we have too much data, see if we can reduce padding.
padding = self.metadata_blocks[-1]
newlength = padding.length - (len(data) - available)
if newlength > 0:
padding.length = newlength
data = MetadataBlock.writeblocks(self.metadata_blocks)
assert len(data) == available
elif len(data) < available:
# If we have too little data, increase padding.
self.metadata_blocks[-1].length += (available - len(data))
data = MetadataBlock.writeblocks(self.metadata_blocks)
assert len(data) == available
if len(data) != available:
# We couldn't reduce the padding enough.
diff = (len(data) - available)
insert_bytes(f, diff, header)
f.seek(header - 4)
f.write(b"fLaC" + data)
# Delete ID3v1
if deleteid3:
try:
f.seek(-128, 2)
except IOError:
pass
else:
if f.read(3) == b"TAG":
f.seek(-128, 2)
f.truncate()
finally:
f.close() | def save(self, filename=None, deleteid3=False):
"""Save metadata blocks to a file.
If no filename is given, the one most recently loaded is used.
"""
if filename is None:
filename = self.filename
f = open(filename, 'rb+')
try:
# Ensure we've got padding at the end, and only at the end.
# If adding makes it too large, we'll scale it down later.
self.metadata_blocks.append(Padding(b'\x00' * 1020))
MetadataBlock.group_padding(self.metadata_blocks)
header = self.__check_header(f)
# "fLaC" and maybe ID3
available = self.__find_audio_offset(f) - header
data = MetadataBlock.writeblocks(self.metadata_blocks)
# Delete ID3v2
if deleteid3 and header > 4:
available += header - 4
header = 4
if len(data) > available:
# If we have too much data, see if we can reduce padding.
padding = self.metadata_blocks[-1]
newlength = padding.length - (len(data) - available)
if newlength > 0:
padding.length = newlength
data = MetadataBlock.writeblocks(self.metadata_blocks)
assert len(data) == available
elif len(data) < available:
# If we have too little data, increase padding.
self.metadata_blocks[-1].length += (available - len(data))
data = MetadataBlock.writeblocks(self.metadata_blocks)
assert len(data) == available
if len(data) != available:
# We couldn't reduce the padding enough.
diff = (len(data) - available)
insert_bytes(f, diff, header)
f.seek(header - 4)
f.write(b"fLaC" + data)
# Delete ID3v1
if deleteid3:
try:
f.seek(-128, 2)
except IOError:
pass
else:
if f.read(3) == b"TAG":
f.seek(-128, 2)
f.truncate()
finally:
f.close() | [
"Save",
"metadata",
"blocks",
"to",
"a",
"file",
"."
] | LordSputnik/mutagen | python | https://github.com/LordSputnik/mutagen/blob/38e62c8dc35c72b16554f5dbe7c0fde91acc3411/mutagen/flac.py#L743-L803 | [
"def",
"save",
"(",
"self",
",",
"filename",
"=",
"None",
",",
"deleteid3",
"=",
"False",
")",
":",
"if",
"filename",
"is",
"None",
":",
"filename",
"=",
"self",
".",
"filename",
"f",
"=",
"open",
"(",
"filename",
",",
"'rb+'",
")",
"try",
":",
"# Ensure we've got padding at the end, and only at the end.",
"# If adding makes it too large, we'll scale it down later.",
"self",
".",
"metadata_blocks",
".",
"append",
"(",
"Padding",
"(",
"b'\\x00'",
"*",
"1020",
")",
")",
"MetadataBlock",
".",
"group_padding",
"(",
"self",
".",
"metadata_blocks",
")",
"header",
"=",
"self",
".",
"__check_header",
"(",
"f",
")",
"# \"fLaC\" and maybe ID3",
"available",
"=",
"self",
".",
"__find_audio_offset",
"(",
"f",
")",
"-",
"header",
"data",
"=",
"MetadataBlock",
".",
"writeblocks",
"(",
"self",
".",
"metadata_blocks",
")",
"# Delete ID3v2",
"if",
"deleteid3",
"and",
"header",
">",
"4",
":",
"available",
"+=",
"header",
"-",
"4",
"header",
"=",
"4",
"if",
"len",
"(",
"data",
")",
">",
"available",
":",
"# If we have too much data, see if we can reduce padding.",
"padding",
"=",
"self",
".",
"metadata_blocks",
"[",
"-",
"1",
"]",
"newlength",
"=",
"padding",
".",
"length",
"-",
"(",
"len",
"(",
"data",
")",
"-",
"available",
")",
"if",
"newlength",
">",
"0",
":",
"padding",
".",
"length",
"=",
"newlength",
"data",
"=",
"MetadataBlock",
".",
"writeblocks",
"(",
"self",
".",
"metadata_blocks",
")",
"assert",
"len",
"(",
"data",
")",
"==",
"available",
"elif",
"len",
"(",
"data",
")",
"<",
"available",
":",
"# If we have too little data, increase padding.",
"self",
".",
"metadata_blocks",
"[",
"-",
"1",
"]",
".",
"length",
"+=",
"(",
"available",
"-",
"len",
"(",
"data",
")",
")",
"data",
"=",
"MetadataBlock",
".",
"writeblocks",
"(",
"self",
".",
"metadata_blocks",
")",
"assert",
"len",
"(",
"data",
")",
"==",
"available",
"if",
"len",
"(",
"data",
")",
"!=",
"available",
":",
"# We couldn't reduce the padding enough.",
"diff",
"=",
"(",
"len",
"(",
"data",
")",
"-",
"available",
")",
"insert_bytes",
"(",
"f",
",",
"diff",
",",
"header",
")",
"f",
".",
"seek",
"(",
"header",
"-",
"4",
")",
"f",
".",
"write",
"(",
"b\"fLaC\"",
"+",
"data",
")",
"# Delete ID3v1",
"if",
"deleteid3",
":",
"try",
":",
"f",
".",
"seek",
"(",
"-",
"128",
",",
"2",
")",
"except",
"IOError",
":",
"pass",
"else",
":",
"if",
"f",
".",
"read",
"(",
"3",
")",
"==",
"b\"TAG\"",
":",
"f",
".",
"seek",
"(",
"-",
"128",
",",
"2",
")",
"f",
".",
"truncate",
"(",
")",
"finally",
":",
"f",
".",
"close",
"(",
")"
] | 38e62c8dc35c72b16554f5dbe7c0fde91acc3411 |
test | parse_rrset_alias | Parses an Alias tag beneath a ResourceRecordSet, spitting out the two values
found within. This is specific to A records that are set to Alias.
:param lxml.etree._Element e_alias: An Alias tag beneath a ResourceRecordSet.
:rtype: tuple
:returns: A tuple in the form of ``(alias_hosted_zone_id, alias_dns_name)``. | route53/xml_parsers/list_resource_record_sets_by_zone_id.py | def parse_rrset_alias(e_alias):
"""
Parses an Alias tag beneath a ResourceRecordSet, spitting out the two values
found within. This is specific to A records that are set to Alias.
:param lxml.etree._Element e_alias: An Alias tag beneath a ResourceRecordSet.
:rtype: tuple
:returns: A tuple in the form of ``(alias_hosted_zone_id, alias_dns_name)``.
"""
alias_hosted_zone_id = e_alias.find('./{*}HostedZoneId').text
alias_dns_name = e_alias.find('./{*}DNSName').text
return alias_hosted_zone_id, alias_dns_name | def parse_rrset_alias(e_alias):
"""
Parses an Alias tag beneath a ResourceRecordSet, spitting out the two values
found within. This is specific to A records that are set to Alias.
:param lxml.etree._Element e_alias: An Alias tag beneath a ResourceRecordSet.
:rtype: tuple
:returns: A tuple in the form of ``(alias_hosted_zone_id, alias_dns_name)``.
"""
alias_hosted_zone_id = e_alias.find('./{*}HostedZoneId').text
alias_dns_name = e_alias.find('./{*}DNSName').text
return alias_hosted_zone_id, alias_dns_name | [
"Parses",
"an",
"Alias",
"tag",
"beneath",
"a",
"ResourceRecordSet",
"spitting",
"out",
"the",
"two",
"values",
"found",
"within",
".",
"This",
"is",
"specific",
"to",
"A",
"records",
"that",
"are",
"set",
"to",
"Alias",
"."
] | gtaylor/python-route53 | python | https://github.com/gtaylor/python-route53/blob/b9fc7e258a79551c9ed61e4a71668b7f06f9e774/route53/xml_parsers/list_resource_record_sets_by_zone_id.py#L27-L39 | [
"def",
"parse_rrset_alias",
"(",
"e_alias",
")",
":",
"alias_hosted_zone_id",
"=",
"e_alias",
".",
"find",
"(",
"'./{*}HostedZoneId'",
")",
".",
"text",
"alias_dns_name",
"=",
"e_alias",
".",
"find",
"(",
"'./{*}DNSName'",
")",
".",
"text",
"return",
"alias_hosted_zone_id",
",",
"alias_dns_name"
] | b9fc7e258a79551c9ed61e4a71668b7f06f9e774 |
test | parse_rrset_record_values | Used to parse the various Values from the ResourceRecords tags on
most rrset types.
:param lxml.etree._Element e_resource_records: A ResourceRecords tag
beneath a ResourceRecordSet.
:rtype: list
:returns: A list of resource record strings. | route53/xml_parsers/list_resource_record_sets_by_zone_id.py | def parse_rrset_record_values(e_resource_records):
"""
Used to parse the various Values from the ResourceRecords tags on
most rrset types.
:param lxml.etree._Element e_resource_records: A ResourceRecords tag
beneath a ResourceRecordSet.
:rtype: list
:returns: A list of resource record strings.
"""
records = []
for e_record in e_resource_records:
for e_value in e_record:
records.append(e_value.text)
return records | def parse_rrset_record_values(e_resource_records):
"""
Used to parse the various Values from the ResourceRecords tags on
most rrset types.
:param lxml.etree._Element e_resource_records: A ResourceRecords tag
beneath a ResourceRecordSet.
:rtype: list
:returns: A list of resource record strings.
"""
records = []
for e_record in e_resource_records:
for e_value in e_record:
records.append(e_value.text)
return records | [
"Used",
"to",
"parse",
"the",
"various",
"Values",
"from",
"the",
"ResourceRecords",
"tags",
"on",
"most",
"rrset",
"types",
"."
] | gtaylor/python-route53 | python | https://github.com/gtaylor/python-route53/blob/b9fc7e258a79551c9ed61e4a71668b7f06f9e774/route53/xml_parsers/list_resource_record_sets_by_zone_id.py#L41-L58 | [
"def",
"parse_rrset_record_values",
"(",
"e_resource_records",
")",
":",
"records",
"=",
"[",
"]",
"for",
"e_record",
"in",
"e_resource_records",
":",
"for",
"e_value",
"in",
"e_record",
":",
"records",
".",
"append",
"(",
"e_value",
".",
"text",
")",
"return",
"records"
] | b9fc7e258a79551c9ed61e4a71668b7f06f9e774 |
test | parse_rrset | This a parser that allows the passing of any valid ResourceRecordSet
tag. It will spit out the appropriate ResourceRecordSet object for the tag.
:param lxml.etree._Element e_rrset: The root node of the etree parsed
response from the API.
:param Route53Connection connection: The connection instance used to
query the API.
:param str zone_id: The zone ID of the HostedZone these rrsets belong to.
:rtype: ResourceRecordSet
:returns: An instantiated ResourceRecordSet object. | route53/xml_parsers/list_resource_record_sets_by_zone_id.py | def parse_rrset(e_rrset, connection, zone_id):
"""
This a parser that allows the passing of any valid ResourceRecordSet
tag. It will spit out the appropriate ResourceRecordSet object for the tag.
:param lxml.etree._Element e_rrset: The root node of the etree parsed
response from the API.
:param Route53Connection connection: The connection instance used to
query the API.
:param str zone_id: The zone ID of the HostedZone these rrsets belong to.
:rtype: ResourceRecordSet
:returns: An instantiated ResourceRecordSet object.
"""
# This dict will be used to instantiate a ResourceRecordSet instance to yield.
kwargs = {
'connection': connection,
'zone_id': zone_id,
}
rrset_type = None
for e_field in e_rrset:
# Cheesy way to strip off the namespace.
tag_name = e_field.tag.split('}')[1]
field_text = e_field.text
if tag_name == 'Type':
# Need to store this to determine which ResourceRecordSet
# subclass to instantiate.
rrset_type = field_text
continue
elif tag_name == 'AliasTarget':
# A records have some special field values we need.
alias_hosted_zone_id, alias_dns_name = parse_rrset_alias(e_field)
kwargs['alias_hosted_zone_id'] = alias_hosted_zone_id
kwargs['alias_dns_name'] = alias_dns_name
# Alias A entries have no TTL.
kwargs['ttl'] = None
continue
elif tag_name == 'ResourceRecords':
kwargs['records'] = parse_rrset_record_values(e_field)
continue
# Map the XML tag name to a kwarg name.
kw_name = RRSET_TAG_TO_KWARG_MAP[tag_name]
# This will be the key/val pair used to instantiate the
# ResourceRecordSet instance.
kwargs[kw_name] = field_text
if not rrset_type:
raise Route53Error("No Type tag found in ListResourceRecordSetsResponse.")
if 'records' not in kwargs:
# Not all rrsets have records.
kwargs['records'] = []
RRSetSubclass = RRSET_TYPE_TO_RSET_SUBCLASS_MAP[rrset_type]
return RRSetSubclass(**kwargs) | def parse_rrset(e_rrset, connection, zone_id):
"""
This a parser that allows the passing of any valid ResourceRecordSet
tag. It will spit out the appropriate ResourceRecordSet object for the tag.
:param lxml.etree._Element e_rrset: The root node of the etree parsed
response from the API.
:param Route53Connection connection: The connection instance used to
query the API.
:param str zone_id: The zone ID of the HostedZone these rrsets belong to.
:rtype: ResourceRecordSet
:returns: An instantiated ResourceRecordSet object.
"""
# This dict will be used to instantiate a ResourceRecordSet instance to yield.
kwargs = {
'connection': connection,
'zone_id': zone_id,
}
rrset_type = None
for e_field in e_rrset:
# Cheesy way to strip off the namespace.
tag_name = e_field.tag.split('}')[1]
field_text = e_field.text
if tag_name == 'Type':
# Need to store this to determine which ResourceRecordSet
# subclass to instantiate.
rrset_type = field_text
continue
elif tag_name == 'AliasTarget':
# A records have some special field values we need.
alias_hosted_zone_id, alias_dns_name = parse_rrset_alias(e_field)
kwargs['alias_hosted_zone_id'] = alias_hosted_zone_id
kwargs['alias_dns_name'] = alias_dns_name
# Alias A entries have no TTL.
kwargs['ttl'] = None
continue
elif tag_name == 'ResourceRecords':
kwargs['records'] = parse_rrset_record_values(e_field)
continue
# Map the XML tag name to a kwarg name.
kw_name = RRSET_TAG_TO_KWARG_MAP[tag_name]
# This will be the key/val pair used to instantiate the
# ResourceRecordSet instance.
kwargs[kw_name] = field_text
if not rrset_type:
raise Route53Error("No Type tag found in ListResourceRecordSetsResponse.")
if 'records' not in kwargs:
# Not all rrsets have records.
kwargs['records'] = []
RRSetSubclass = RRSET_TYPE_TO_RSET_SUBCLASS_MAP[rrset_type]
return RRSetSubclass(**kwargs) | [
"This",
"a",
"parser",
"that",
"allows",
"the",
"passing",
"of",
"any",
"valid",
"ResourceRecordSet",
"tag",
".",
"It",
"will",
"spit",
"out",
"the",
"appropriate",
"ResourceRecordSet",
"object",
"for",
"the",
"tag",
"."
] | gtaylor/python-route53 | python | https://github.com/gtaylor/python-route53/blob/b9fc7e258a79551c9ed61e4a71668b7f06f9e774/route53/xml_parsers/list_resource_record_sets_by_zone_id.py#L60-L117 | [
"def",
"parse_rrset",
"(",
"e_rrset",
",",
"connection",
",",
"zone_id",
")",
":",
"# This dict will be used to instantiate a ResourceRecordSet instance to yield.",
"kwargs",
"=",
"{",
"'connection'",
":",
"connection",
",",
"'zone_id'",
":",
"zone_id",
",",
"}",
"rrset_type",
"=",
"None",
"for",
"e_field",
"in",
"e_rrset",
":",
"# Cheesy way to strip off the namespace.",
"tag_name",
"=",
"e_field",
".",
"tag",
".",
"split",
"(",
"'}'",
")",
"[",
"1",
"]",
"field_text",
"=",
"e_field",
".",
"text",
"if",
"tag_name",
"==",
"'Type'",
":",
"# Need to store this to determine which ResourceRecordSet",
"# subclass to instantiate.",
"rrset_type",
"=",
"field_text",
"continue",
"elif",
"tag_name",
"==",
"'AliasTarget'",
":",
"# A records have some special field values we need.",
"alias_hosted_zone_id",
",",
"alias_dns_name",
"=",
"parse_rrset_alias",
"(",
"e_field",
")",
"kwargs",
"[",
"'alias_hosted_zone_id'",
"]",
"=",
"alias_hosted_zone_id",
"kwargs",
"[",
"'alias_dns_name'",
"]",
"=",
"alias_dns_name",
"# Alias A entries have no TTL.",
"kwargs",
"[",
"'ttl'",
"]",
"=",
"None",
"continue",
"elif",
"tag_name",
"==",
"'ResourceRecords'",
":",
"kwargs",
"[",
"'records'",
"]",
"=",
"parse_rrset_record_values",
"(",
"e_field",
")",
"continue",
"# Map the XML tag name to a kwarg name.",
"kw_name",
"=",
"RRSET_TAG_TO_KWARG_MAP",
"[",
"tag_name",
"]",
"# This will be the key/val pair used to instantiate the",
"# ResourceRecordSet instance.",
"kwargs",
"[",
"kw_name",
"]",
"=",
"field_text",
"if",
"not",
"rrset_type",
":",
"raise",
"Route53Error",
"(",
"\"No Type tag found in ListResourceRecordSetsResponse.\"",
")",
"if",
"'records'",
"not",
"in",
"kwargs",
":",
"# Not all rrsets have records.",
"kwargs",
"[",
"'records'",
"]",
"=",
"[",
"]",
"RRSetSubclass",
"=",
"RRSET_TYPE_TO_RSET_SUBCLASS_MAP",
"[",
"rrset_type",
"]",
"return",
"RRSetSubclass",
"(",
"*",
"*",
"kwargs",
")"
] | b9fc7e258a79551c9ed61e4a71668b7f06f9e774 |
test | list_resource_record_sets_by_zone_id_parser | Parses the API responses for the
:py:meth:`route53.connection.Route53Connection.list_resource_record_sets_by_zone_id`
method.
:param lxml.etree._Element e_root: The root node of the etree parsed
response from the API.
:param Route53Connection connection: The connection instance used to
query the API.
:param str zone_id: The zone ID of the HostedZone these rrsets belong to.
:rtype: ResourceRecordSet
:returns: A generator of fully formed ResourceRecordSet instances. | route53/xml_parsers/list_resource_record_sets_by_zone_id.py | def list_resource_record_sets_by_zone_id_parser(e_root, connection, zone_id):
"""
Parses the API responses for the
:py:meth:`route53.connection.Route53Connection.list_resource_record_sets_by_zone_id`
method.
:param lxml.etree._Element e_root: The root node of the etree parsed
response from the API.
:param Route53Connection connection: The connection instance used to
query the API.
:param str zone_id: The zone ID of the HostedZone these rrsets belong to.
:rtype: ResourceRecordSet
:returns: A generator of fully formed ResourceRecordSet instances.
"""
# The rest of the list pagination tags are handled higher up in the stack.
# We'll just worry about the ResourceRecordSets tag, which has
# ResourceRecordSet tags nested beneath it.
e_rrsets = e_root.find('./{*}ResourceRecordSets')
for e_rrset in e_rrsets:
yield parse_rrset(e_rrset, connection, zone_id) | def list_resource_record_sets_by_zone_id_parser(e_root, connection, zone_id):
"""
Parses the API responses for the
:py:meth:`route53.connection.Route53Connection.list_resource_record_sets_by_zone_id`
method.
:param lxml.etree._Element e_root: The root node of the etree parsed
response from the API.
:param Route53Connection connection: The connection instance used to
query the API.
:param str zone_id: The zone ID of the HostedZone these rrsets belong to.
:rtype: ResourceRecordSet
:returns: A generator of fully formed ResourceRecordSet instances.
"""
# The rest of the list pagination tags are handled higher up in the stack.
# We'll just worry about the ResourceRecordSets tag, which has
# ResourceRecordSet tags nested beneath it.
e_rrsets = e_root.find('./{*}ResourceRecordSets')
for e_rrset in e_rrsets:
yield parse_rrset(e_rrset, connection, zone_id) | [
"Parses",
"the",
"API",
"responses",
"for",
"the",
":",
"py",
":",
"meth",
":",
"route53",
".",
"connection",
".",
"Route53Connection",
".",
"list_resource_record_sets_by_zone_id",
"method",
"."
] | gtaylor/python-route53 | python | https://github.com/gtaylor/python-route53/blob/b9fc7e258a79551c9ed61e4a71668b7f06f9e774/route53/xml_parsers/list_resource_record_sets_by_zone_id.py#L119-L140 | [
"def",
"list_resource_record_sets_by_zone_id_parser",
"(",
"e_root",
",",
"connection",
",",
"zone_id",
")",
":",
"# The rest of the list pagination tags are handled higher up in the stack.",
"# We'll just worry about the ResourceRecordSets tag, which has",
"# ResourceRecordSet tags nested beneath it.",
"e_rrsets",
"=",
"e_root",
".",
"find",
"(",
"'./{*}ResourceRecordSets'",
")",
"for",
"e_rrset",
"in",
"e_rrsets",
":",
"yield",
"parse_rrset",
"(",
"e_rrset",
",",
"connection",
",",
"zone_id",
")"
] | b9fc7e258a79551c9ed61e4a71668b7f06f9e774 |
test | HostedZone.nameservers | :rtype: list
:returns: A list of nameserver strings for this hosted zone. | route53/hosted_zone.py | def nameservers(self):
"""
:rtype: list
:returns: A list of nameserver strings for this hosted zone.
"""
# If this HostedZone was instantiated by ListHostedZones, the nameservers
# attribute didn't get populated. If the user requests it, we'll
# lazy load by querying it in after the fact. It's safe to cache like
# this since these nameserver values won't change.
if not self._nameservers:
# We'll just snatch the nameserver values from a fresh copy
# via GetHostedZone.
hosted_zone = self.connection.get_hosted_zone_by_id(self.id)
self._nameservers = hosted_zone._nameservers
return self._nameservers | def nameservers(self):
"""
:rtype: list
:returns: A list of nameserver strings for this hosted zone.
"""
# If this HostedZone was instantiated by ListHostedZones, the nameservers
# attribute didn't get populated. If the user requests it, we'll
# lazy load by querying it in after the fact. It's safe to cache like
# this since these nameserver values won't change.
if not self._nameservers:
# We'll just snatch the nameserver values from a fresh copy
# via GetHostedZone.
hosted_zone = self.connection.get_hosted_zone_by_id(self.id)
self._nameservers = hosted_zone._nameservers
return self._nameservers | [
":",
"rtype",
":",
"list",
":",
"returns",
":",
"A",
"list",
"of",
"nameserver",
"strings",
"for",
"this",
"hosted",
"zone",
"."
] | gtaylor/python-route53 | python | https://github.com/gtaylor/python-route53/blob/b9fc7e258a79551c9ed61e4a71668b7f06f9e774/route53/hosted_zone.py#L46-L62 | [
"def",
"nameservers",
"(",
"self",
")",
":",
"# If this HostedZone was instantiated by ListHostedZones, the nameservers",
"# attribute didn't get populated. If the user requests it, we'll",
"# lazy load by querying it in after the fact. It's safe to cache like",
"# this since these nameserver values won't change.",
"if",
"not",
"self",
".",
"_nameservers",
":",
"# We'll just snatch the nameserver values from a fresh copy",
"# via GetHostedZone.",
"hosted_zone",
"=",
"self",
".",
"connection",
".",
"get_hosted_zone_by_id",
"(",
"self",
".",
"id",
")",
"self",
".",
"_nameservers",
"=",
"hosted_zone",
".",
"_nameservers",
"return",
"self",
".",
"_nameservers"
] | b9fc7e258a79551c9ed61e4a71668b7f06f9e774 |
test | HostedZone.delete | Deletes this hosted zone. After this method is ran, you won't be able
to add records, or do anything else with the zone. You'd need to
re-create it, as zones are read-only after creation.
:keyword bool force: If ``True``, delete the
:py:class:`HostedZone <route53.hosted_zone.HostedZone>`, even if it
means nuking all associated record sets. If ``False``, an
exception is raised if this
:py:class:`HostedZone <route53.hosted_zone.HostedZone>`
has record sets.
:rtype: dict
:returns: A dict of change info, which contains some details about
the request. | route53/hosted_zone.py | def delete(self, force=False):
"""
Deletes this hosted zone. After this method is ran, you won't be able
to add records, or do anything else with the zone. You'd need to
re-create it, as zones are read-only after creation.
:keyword bool force: If ``True``, delete the
:py:class:`HostedZone <route53.hosted_zone.HostedZone>`, even if it
means nuking all associated record sets. If ``False``, an
exception is raised if this
:py:class:`HostedZone <route53.hosted_zone.HostedZone>`
has record sets.
:rtype: dict
:returns: A dict of change info, which contains some details about
the request.
"""
self._halt_if_already_deleted()
if force:
# Forcing deletion by cleaning up all record sets first. We'll
# do it all in one change set.
cset = ChangeSet(connection=self.connection, hosted_zone_id=self.id)
for rrset in self.record_sets:
# You can delete a HostedZone if there are only SOA and NS
# entries left. So delete everything but SOA/NS entries.
if rrset.rrset_type not in ['SOA', 'NS']:
cset.add_change('DELETE', rrset)
if cset.deletions or cset.creations:
# Bombs away.
self.connection._change_resource_record_sets(cset)
# Now delete the HostedZone.
retval = self.connection.delete_hosted_zone_by_id(self.id)
# Used to protect against modifying a deleted HostedZone.
self._is_deleted = True
return retval | def delete(self, force=False):
"""
Deletes this hosted zone. After this method is ran, you won't be able
to add records, or do anything else with the zone. You'd need to
re-create it, as zones are read-only after creation.
:keyword bool force: If ``True``, delete the
:py:class:`HostedZone <route53.hosted_zone.HostedZone>`, even if it
means nuking all associated record sets. If ``False``, an
exception is raised if this
:py:class:`HostedZone <route53.hosted_zone.HostedZone>`
has record sets.
:rtype: dict
:returns: A dict of change info, which contains some details about
the request.
"""
self._halt_if_already_deleted()
if force:
# Forcing deletion by cleaning up all record sets first. We'll
# do it all in one change set.
cset = ChangeSet(connection=self.connection, hosted_zone_id=self.id)
for rrset in self.record_sets:
# You can delete a HostedZone if there are only SOA and NS
# entries left. So delete everything but SOA/NS entries.
if rrset.rrset_type not in ['SOA', 'NS']:
cset.add_change('DELETE', rrset)
if cset.deletions or cset.creations:
# Bombs away.
self.connection._change_resource_record_sets(cset)
# Now delete the HostedZone.
retval = self.connection.delete_hosted_zone_by_id(self.id)
# Used to protect against modifying a deleted HostedZone.
self._is_deleted = True
return retval | [
"Deletes",
"this",
"hosted",
"zone",
".",
"After",
"this",
"method",
"is",
"ran",
"you",
"won",
"t",
"be",
"able",
"to",
"add",
"records",
"or",
"do",
"anything",
"else",
"with",
"the",
"zone",
".",
"You",
"d",
"need",
"to",
"re",
"-",
"create",
"it",
"as",
"zones",
"are",
"read",
"-",
"only",
"after",
"creation",
"."
] | gtaylor/python-route53 | python | https://github.com/gtaylor/python-route53/blob/b9fc7e258a79551c9ed61e4a71668b7f06f9e774/route53/hosted_zone.py#L87-L127 | [
"def",
"delete",
"(",
"self",
",",
"force",
"=",
"False",
")",
":",
"self",
".",
"_halt_if_already_deleted",
"(",
")",
"if",
"force",
":",
"# Forcing deletion by cleaning up all record sets first. We'll",
"# do it all in one change set.",
"cset",
"=",
"ChangeSet",
"(",
"connection",
"=",
"self",
".",
"connection",
",",
"hosted_zone_id",
"=",
"self",
".",
"id",
")",
"for",
"rrset",
"in",
"self",
".",
"record_sets",
":",
"# You can delete a HostedZone if there are only SOA and NS",
"# entries left. So delete everything but SOA/NS entries.",
"if",
"rrset",
".",
"rrset_type",
"not",
"in",
"[",
"'SOA'",
",",
"'NS'",
"]",
":",
"cset",
".",
"add_change",
"(",
"'DELETE'",
",",
"rrset",
")",
"if",
"cset",
".",
"deletions",
"or",
"cset",
".",
"creations",
":",
"# Bombs away.",
"self",
".",
"connection",
".",
"_change_resource_record_sets",
"(",
"cset",
")",
"# Now delete the HostedZone.",
"retval",
"=",
"self",
".",
"connection",
".",
"delete_hosted_zone_by_id",
"(",
"self",
".",
"id",
")",
"# Used to protect against modifying a deleted HostedZone.",
"self",
".",
"_is_deleted",
"=",
"True",
"return",
"retval"
] | b9fc7e258a79551c9ed61e4a71668b7f06f9e774 |
test | HostedZone._add_record | Convenience method for creating ResourceRecordSets. Most of the calls
are basically the same, this saves on repetition.
:rtype: tuple
:returns: A tuple in the form of ``(rrset, change_info)``, where
``rrset`` is the newly created ResourceRecordSet sub-class
instance. | route53/hosted_zone.py | def _add_record(self, record_set_class, name, values, ttl=60, weight=None,
region=None,set_identifier=None, alias_hosted_zone_id=None,
alias_dns_name=None):
"""
Convenience method for creating ResourceRecordSets. Most of the calls
are basically the same, this saves on repetition.
:rtype: tuple
:returns: A tuple in the form of ``(rrset, change_info)``, where
``rrset`` is the newly created ResourceRecordSet sub-class
instance.
"""
self._halt_if_already_deleted()
rrset_kwargs = dict(
connection=self.connection,
zone_id=self.id,
name=name,
ttl=ttl,
records=values,
weight=weight,
region=region,
set_identifier=set_identifier,
)
if alias_hosted_zone_id or alias_dns_name:
rrset_kwargs.update(dict(
alias_hosted_zone_id=alias_hosted_zone_id,
alias_dns_name=alias_dns_name
))
rrset = record_set_class(**rrset_kwargs)
cset = ChangeSet(connection=self.connection, hosted_zone_id=self.id)
cset.add_change('CREATE', rrset)
change_info = self.connection._change_resource_record_sets(cset)
return rrset, change_info | def _add_record(self, record_set_class, name, values, ttl=60, weight=None,
region=None,set_identifier=None, alias_hosted_zone_id=None,
alias_dns_name=None):
"""
Convenience method for creating ResourceRecordSets. Most of the calls
are basically the same, this saves on repetition.
:rtype: tuple
:returns: A tuple in the form of ``(rrset, change_info)``, where
``rrset`` is the newly created ResourceRecordSet sub-class
instance.
"""
self._halt_if_already_deleted()
rrset_kwargs = dict(
connection=self.connection,
zone_id=self.id,
name=name,
ttl=ttl,
records=values,
weight=weight,
region=region,
set_identifier=set_identifier,
)
if alias_hosted_zone_id or alias_dns_name:
rrset_kwargs.update(dict(
alias_hosted_zone_id=alias_hosted_zone_id,
alias_dns_name=alias_dns_name
))
rrset = record_set_class(**rrset_kwargs)
cset = ChangeSet(connection=self.connection, hosted_zone_id=self.id)
cset.add_change('CREATE', rrset)
change_info = self.connection._change_resource_record_sets(cset)
return rrset, change_info | [
"Convenience",
"method",
"for",
"creating",
"ResourceRecordSets",
".",
"Most",
"of",
"the",
"calls",
"are",
"basically",
"the",
"same",
"this",
"saves",
"on",
"repetition",
"."
] | gtaylor/python-route53 | python | https://github.com/gtaylor/python-route53/blob/b9fc7e258a79551c9ed61e4a71668b7f06f9e774/route53/hosted_zone.py#L140-L179 | [
"def",
"_add_record",
"(",
"self",
",",
"record_set_class",
",",
"name",
",",
"values",
",",
"ttl",
"=",
"60",
",",
"weight",
"=",
"None",
",",
"region",
"=",
"None",
",",
"set_identifier",
"=",
"None",
",",
"alias_hosted_zone_id",
"=",
"None",
",",
"alias_dns_name",
"=",
"None",
")",
":",
"self",
".",
"_halt_if_already_deleted",
"(",
")",
"rrset_kwargs",
"=",
"dict",
"(",
"connection",
"=",
"self",
".",
"connection",
",",
"zone_id",
"=",
"self",
".",
"id",
",",
"name",
"=",
"name",
",",
"ttl",
"=",
"ttl",
",",
"records",
"=",
"values",
",",
"weight",
"=",
"weight",
",",
"region",
"=",
"region",
",",
"set_identifier",
"=",
"set_identifier",
",",
")",
"if",
"alias_hosted_zone_id",
"or",
"alias_dns_name",
":",
"rrset_kwargs",
".",
"update",
"(",
"dict",
"(",
"alias_hosted_zone_id",
"=",
"alias_hosted_zone_id",
",",
"alias_dns_name",
"=",
"alias_dns_name",
")",
")",
"rrset",
"=",
"record_set_class",
"(",
"*",
"*",
"rrset_kwargs",
")",
"cset",
"=",
"ChangeSet",
"(",
"connection",
"=",
"self",
".",
"connection",
",",
"hosted_zone_id",
"=",
"self",
".",
"id",
")",
"cset",
".",
"add_change",
"(",
"'CREATE'",
",",
"rrset",
")",
"change_info",
"=",
"self",
".",
"connection",
".",
"_change_resource_record_sets",
"(",
"cset",
")",
"return",
"rrset",
",",
"change_info"
] | b9fc7e258a79551c9ed61e4a71668b7f06f9e774 |
test | HostedZone.create_a_record | Creates and returns an A record attached to this hosted zone.
:param str name: The fully qualified name of the record to add.
:param list values: A list of value strings for the record.
:keyword int ttl: The time-to-live of the record (in seconds).
:keyword int weight: *For weighted record sets only*. Among resource record
sets that have the same combination of DNS name and type, a value
that determines what portion of traffic for the current resource
record set is routed to the associated location. Ranges from 0-255.
:keyword str region: *For latency-based record sets*. The Amazon EC2 region
where the resource that is specified in this resource record set
resides.
:keyword str set_identifier: *For weighted and latency resource record
sets only*. An identifier that differentiates among multiple
resource record sets that have the same combination of DNS name
and type. 1-128 chars.
:keyword str alias_hosted_zone_id: Alias A records have this specified.
It appears to be the hosted zone ID for the ELB the Alias points at.
:keyword str alias_dns_name: Alias A records have this specified. It is
the DNS name for the ELB that the Alias points to.
:rtype: tuple
:returns: A tuple in the form of ``(rrset, change_info)``, where
``rrset`` is the newly created
:py:class:`AResourceRecordSet <route53.resource_record_set.AResourceRecordSet>`
instance. | route53/hosted_zone.py | def create_a_record(self, name, values, ttl=60, weight=None, region=None,
set_identifier=None, alias_hosted_zone_id=None,
alias_dns_name=None):
"""
Creates and returns an A record attached to this hosted zone.
:param str name: The fully qualified name of the record to add.
:param list values: A list of value strings for the record.
:keyword int ttl: The time-to-live of the record (in seconds).
:keyword int weight: *For weighted record sets only*. Among resource record
sets that have the same combination of DNS name and type, a value
that determines what portion of traffic for the current resource
record set is routed to the associated location. Ranges from 0-255.
:keyword str region: *For latency-based record sets*. The Amazon EC2 region
where the resource that is specified in this resource record set
resides.
:keyword str set_identifier: *For weighted and latency resource record
sets only*. An identifier that differentiates among multiple
resource record sets that have the same combination of DNS name
and type. 1-128 chars.
:keyword str alias_hosted_zone_id: Alias A records have this specified.
It appears to be the hosted zone ID for the ELB the Alias points at.
:keyword str alias_dns_name: Alias A records have this specified. It is
the DNS name for the ELB that the Alias points to.
:rtype: tuple
:returns: A tuple in the form of ``(rrset, change_info)``, where
``rrset`` is the newly created
:py:class:`AResourceRecordSet <route53.resource_record_set.AResourceRecordSet>`
instance.
"""
self._halt_if_already_deleted()
# Grab the params/kwargs here for brevity's sake.
values = locals()
del values['self']
return self._add_record(AResourceRecordSet, **values) | def create_a_record(self, name, values, ttl=60, weight=None, region=None,
set_identifier=None, alias_hosted_zone_id=None,
alias_dns_name=None):
"""
Creates and returns an A record attached to this hosted zone.
:param str name: The fully qualified name of the record to add.
:param list values: A list of value strings for the record.
:keyword int ttl: The time-to-live of the record (in seconds).
:keyword int weight: *For weighted record sets only*. Among resource record
sets that have the same combination of DNS name and type, a value
that determines what portion of traffic for the current resource
record set is routed to the associated location. Ranges from 0-255.
:keyword str region: *For latency-based record sets*. The Amazon EC2 region
where the resource that is specified in this resource record set
resides.
:keyword str set_identifier: *For weighted and latency resource record
sets only*. An identifier that differentiates among multiple
resource record sets that have the same combination of DNS name
and type. 1-128 chars.
:keyword str alias_hosted_zone_id: Alias A records have this specified.
It appears to be the hosted zone ID for the ELB the Alias points at.
:keyword str alias_dns_name: Alias A records have this specified. It is
the DNS name for the ELB that the Alias points to.
:rtype: tuple
:returns: A tuple in the form of ``(rrset, change_info)``, where
``rrset`` is the newly created
:py:class:`AResourceRecordSet <route53.resource_record_set.AResourceRecordSet>`
instance.
"""
self._halt_if_already_deleted()
# Grab the params/kwargs here for brevity's sake.
values = locals()
del values['self']
return self._add_record(AResourceRecordSet, **values) | [
"Creates",
"and",
"returns",
"an",
"A",
"record",
"attached",
"to",
"this",
"hosted",
"zone",
"."
] | gtaylor/python-route53 | python | https://github.com/gtaylor/python-route53/blob/b9fc7e258a79551c9ed61e4a71668b7f06f9e774/route53/hosted_zone.py#L181-L218 | [
"def",
"create_a_record",
"(",
"self",
",",
"name",
",",
"values",
",",
"ttl",
"=",
"60",
",",
"weight",
"=",
"None",
",",
"region",
"=",
"None",
",",
"set_identifier",
"=",
"None",
",",
"alias_hosted_zone_id",
"=",
"None",
",",
"alias_dns_name",
"=",
"None",
")",
":",
"self",
".",
"_halt_if_already_deleted",
"(",
")",
"# Grab the params/kwargs here for brevity's sake.",
"values",
"=",
"locals",
"(",
")",
"del",
"values",
"[",
"'self'",
"]",
"return",
"self",
".",
"_add_record",
"(",
"AResourceRecordSet",
",",
"*",
"*",
"values",
")"
] | b9fc7e258a79551c9ed61e4a71668b7f06f9e774 |
test | HostedZone.create_aaaa_record | Creates an AAAA record attached to this hosted zone.
:param str name: The fully qualified name of the record to add.
:param list values: A list of value strings for the record.
:keyword int ttl: The time-to-live of the record (in seconds).
:keyword int weight: *For weighted record sets only*. Among resource record
sets that have the same combination of DNS name and type, a value
that determines what portion of traffic for the current resource
record set is routed to the associated location. Ranges from 0-255.
:keyword str region: *For latency-based record sets*. The Amazon EC2 region
where the resource that is specified in this resource record set
resides.
:keyword str set_identifier: *For weighted and latency resource record
sets only*. An identifier that differentiates among multiple
resource record sets that have the same combination of DNS name
and type. 1-128 chars.
:rtype: tuple
:returns: A tuple in the form of ``(rrset, change_info)``, where
``rrset`` is the newly created AAAAResourceRecordSet instance. | route53/hosted_zone.py | def create_aaaa_record(self, name, values, ttl=60, weight=None, region=None,
set_identifier=None):
"""
Creates an AAAA record attached to this hosted zone.
:param str name: The fully qualified name of the record to add.
:param list values: A list of value strings for the record.
:keyword int ttl: The time-to-live of the record (in seconds).
:keyword int weight: *For weighted record sets only*. Among resource record
sets that have the same combination of DNS name and type, a value
that determines what portion of traffic for the current resource
record set is routed to the associated location. Ranges from 0-255.
:keyword str region: *For latency-based record sets*. The Amazon EC2 region
where the resource that is specified in this resource record set
resides.
:keyword str set_identifier: *For weighted and latency resource record
sets only*. An identifier that differentiates among multiple
resource record sets that have the same combination of DNS name
and type. 1-128 chars.
:rtype: tuple
:returns: A tuple in the form of ``(rrset, change_info)``, where
``rrset`` is the newly created AAAAResourceRecordSet instance.
"""
self._halt_if_already_deleted()
# Grab the params/kwargs here for brevity's sake.
values = locals()
del values['self']
return self._add_record(AAAAResourceRecordSet, **values) | def create_aaaa_record(self, name, values, ttl=60, weight=None, region=None,
set_identifier=None):
"""
Creates an AAAA record attached to this hosted zone.
:param str name: The fully qualified name of the record to add.
:param list values: A list of value strings for the record.
:keyword int ttl: The time-to-live of the record (in seconds).
:keyword int weight: *For weighted record sets only*. Among resource record
sets that have the same combination of DNS name and type, a value
that determines what portion of traffic for the current resource
record set is routed to the associated location. Ranges from 0-255.
:keyword str region: *For latency-based record sets*. The Amazon EC2 region
where the resource that is specified in this resource record set
resides.
:keyword str set_identifier: *For weighted and latency resource record
sets only*. An identifier that differentiates among multiple
resource record sets that have the same combination of DNS name
and type. 1-128 chars.
:rtype: tuple
:returns: A tuple in the form of ``(rrset, change_info)``, where
``rrset`` is the newly created AAAAResourceRecordSet instance.
"""
self._halt_if_already_deleted()
# Grab the params/kwargs here for brevity's sake.
values = locals()
del values['self']
return self._add_record(AAAAResourceRecordSet, **values) | [
"Creates",
"an",
"AAAA",
"record",
"attached",
"to",
"this",
"hosted",
"zone",
"."
] | gtaylor/python-route53 | python | https://github.com/gtaylor/python-route53/blob/b9fc7e258a79551c9ed61e4a71668b7f06f9e774/route53/hosted_zone.py#L220-L250 | [
"def",
"create_aaaa_record",
"(",
"self",
",",
"name",
",",
"values",
",",
"ttl",
"=",
"60",
",",
"weight",
"=",
"None",
",",
"region",
"=",
"None",
",",
"set_identifier",
"=",
"None",
")",
":",
"self",
".",
"_halt_if_already_deleted",
"(",
")",
"# Grab the params/kwargs here for brevity's sake.",
"values",
"=",
"locals",
"(",
")",
"del",
"values",
"[",
"'self'",
"]",
"return",
"self",
".",
"_add_record",
"(",
"AAAAResourceRecordSet",
",",
"*",
"*",
"values",
")"
] | b9fc7e258a79551c9ed61e4a71668b7f06f9e774 |
test | HostedZone.create_cname_record | Creates a CNAME record attached to this hosted zone.
:param str name: The fully qualified name of the record to add.
:param list values: A list of value strings for the record.
:keyword int ttl: The time-to-live of the record (in seconds).
:keyword int weight: *For weighted record sets only*. Among resource record
sets that have the same combination of DNS name and type, a value
that determines what portion of traffic for the current resource
record set is routed to the associated location. Ranges from 0-255.
:keyword str region: *For latency-based record sets*. The Amazon EC2 region
where the resource that is specified in this resource record set
resides.
:keyword str set_identifier: *For weighted and latency resource record
sets only*. An identifier that differentiates among multiple
resource record sets that have the same combination of DNS name
and type. 1-128 chars.
:rtype: tuple
:returns: A tuple in the form of ``(rrset, change_info)``, where
``rrset`` is the newly created CNAMEResourceRecordSet instance. | route53/hosted_zone.py | def create_cname_record(self, name, values, ttl=60, weight=None, region=None,
set_identifier=None):
"""
Creates a CNAME record attached to this hosted zone.
:param str name: The fully qualified name of the record to add.
:param list values: A list of value strings for the record.
:keyword int ttl: The time-to-live of the record (in seconds).
:keyword int weight: *For weighted record sets only*. Among resource record
sets that have the same combination of DNS name and type, a value
that determines what portion of traffic for the current resource
record set is routed to the associated location. Ranges from 0-255.
:keyword str region: *For latency-based record sets*. The Amazon EC2 region
where the resource that is specified in this resource record set
resides.
:keyword str set_identifier: *For weighted and latency resource record
sets only*. An identifier that differentiates among multiple
resource record sets that have the same combination of DNS name
and type. 1-128 chars.
:rtype: tuple
:returns: A tuple in the form of ``(rrset, change_info)``, where
``rrset`` is the newly created CNAMEResourceRecordSet instance.
"""
self._halt_if_already_deleted()
# Grab the params/kwargs here for brevity's sake.
values = locals()
del values['self']
return self._add_record(CNAMEResourceRecordSet, **values) | def create_cname_record(self, name, values, ttl=60, weight=None, region=None,
set_identifier=None):
"""
Creates a CNAME record attached to this hosted zone.
:param str name: The fully qualified name of the record to add.
:param list values: A list of value strings for the record.
:keyword int ttl: The time-to-live of the record (in seconds).
:keyword int weight: *For weighted record sets only*. Among resource record
sets that have the same combination of DNS name and type, a value
that determines what portion of traffic for the current resource
record set is routed to the associated location. Ranges from 0-255.
:keyword str region: *For latency-based record sets*. The Amazon EC2 region
where the resource that is specified in this resource record set
resides.
:keyword str set_identifier: *For weighted and latency resource record
sets only*. An identifier that differentiates among multiple
resource record sets that have the same combination of DNS name
and type. 1-128 chars.
:rtype: tuple
:returns: A tuple in the form of ``(rrset, change_info)``, where
``rrset`` is the newly created CNAMEResourceRecordSet instance.
"""
self._halt_if_already_deleted()
# Grab the params/kwargs here for brevity's sake.
values = locals()
del values['self']
return self._add_record(CNAMEResourceRecordSet, **values) | [
"Creates",
"a",
"CNAME",
"record",
"attached",
"to",
"this",
"hosted",
"zone",
"."
] | gtaylor/python-route53 | python | https://github.com/gtaylor/python-route53/blob/b9fc7e258a79551c9ed61e4a71668b7f06f9e774/route53/hosted_zone.py#L252-L282 | [
"def",
"create_cname_record",
"(",
"self",
",",
"name",
",",
"values",
",",
"ttl",
"=",
"60",
",",
"weight",
"=",
"None",
",",
"region",
"=",
"None",
",",
"set_identifier",
"=",
"None",
")",
":",
"self",
".",
"_halt_if_already_deleted",
"(",
")",
"# Grab the params/kwargs here for brevity's sake.",
"values",
"=",
"locals",
"(",
")",
"del",
"values",
"[",
"'self'",
"]",
"return",
"self",
".",
"_add_record",
"(",
"CNAMEResourceRecordSet",
",",
"*",
"*",
"values",
")"
] | b9fc7e258a79551c9ed61e4a71668b7f06f9e774 |
test | HostedZone.create_mx_record | Creates a MX record attached to this hosted zone.
:param str name: The fully qualified name of the record to add.
:param list values: A list of value strings for the record.
:keyword int ttl: The time-to-live of the record (in seconds).
:rtype: tuple
:returns: A tuple in the form of ``(rrset, change_info)``, where
``rrset`` is the newly created MXResourceRecordSet instance. | route53/hosted_zone.py | def create_mx_record(self, name, values, ttl=60):
"""
Creates a MX record attached to this hosted zone.
:param str name: The fully qualified name of the record to add.
:param list values: A list of value strings for the record.
:keyword int ttl: The time-to-live of the record (in seconds).
:rtype: tuple
:returns: A tuple in the form of ``(rrset, change_info)``, where
``rrset`` is the newly created MXResourceRecordSet instance.
"""
self._halt_if_already_deleted()
# Grab the params/kwargs here for brevity's sake.
values = locals()
del values['self']
return self._add_record(MXResourceRecordSet, **values) | def create_mx_record(self, name, values, ttl=60):
"""
Creates a MX record attached to this hosted zone.
:param str name: The fully qualified name of the record to add.
:param list values: A list of value strings for the record.
:keyword int ttl: The time-to-live of the record (in seconds).
:rtype: tuple
:returns: A tuple in the form of ``(rrset, change_info)``, where
``rrset`` is the newly created MXResourceRecordSet instance.
"""
self._halt_if_already_deleted()
# Grab the params/kwargs here for brevity's sake.
values = locals()
del values['self']
return self._add_record(MXResourceRecordSet, **values) | [
"Creates",
"a",
"MX",
"record",
"attached",
"to",
"this",
"hosted",
"zone",
"."
] | gtaylor/python-route53 | python | https://github.com/gtaylor/python-route53/blob/b9fc7e258a79551c9ed61e4a71668b7f06f9e774/route53/hosted_zone.py#L284-L302 | [
"def",
"create_mx_record",
"(",
"self",
",",
"name",
",",
"values",
",",
"ttl",
"=",
"60",
")",
":",
"self",
".",
"_halt_if_already_deleted",
"(",
")",
"# Grab the params/kwargs here for brevity's sake.",
"values",
"=",
"locals",
"(",
")",
"del",
"values",
"[",
"'self'",
"]",
"return",
"self",
".",
"_add_record",
"(",
"MXResourceRecordSet",
",",
"*",
"*",
"values",
")"
] | b9fc7e258a79551c9ed61e4a71668b7f06f9e774 |
test | HostedZone.create_ns_record | Creates a NS record attached to this hosted zone.
:param str name: The fully qualified name of the record to add.
:param list values: A list of value strings for the record.
:keyword int ttl: The time-to-live of the record (in seconds).
:rtype: tuple
:returns: A tuple in the form of ``(rrset, change_info)``, where
``rrset`` is the newly created NSResourceRecordSet instance. | route53/hosted_zone.py | def create_ns_record(self, name, values, ttl=60):
"""
Creates a NS record attached to this hosted zone.
:param str name: The fully qualified name of the record to add.
:param list values: A list of value strings for the record.
:keyword int ttl: The time-to-live of the record (in seconds).
:rtype: tuple
:returns: A tuple in the form of ``(rrset, change_info)``, where
``rrset`` is the newly created NSResourceRecordSet instance.
"""
self._halt_if_already_deleted()
# Grab the params/kwargs here for brevity's sake.
values = locals()
del values['self']
return self._add_record(NSResourceRecordSet, **values) | def create_ns_record(self, name, values, ttl=60):
"""
Creates a NS record attached to this hosted zone.
:param str name: The fully qualified name of the record to add.
:param list values: A list of value strings for the record.
:keyword int ttl: The time-to-live of the record (in seconds).
:rtype: tuple
:returns: A tuple in the form of ``(rrset, change_info)``, where
``rrset`` is the newly created NSResourceRecordSet instance.
"""
self._halt_if_already_deleted()
# Grab the params/kwargs here for brevity's sake.
values = locals()
del values['self']
return self._add_record(NSResourceRecordSet, **values) | [
"Creates",
"a",
"NS",
"record",
"attached",
"to",
"this",
"hosted",
"zone",
"."
] | gtaylor/python-route53 | python | https://github.com/gtaylor/python-route53/blob/b9fc7e258a79551c9ed61e4a71668b7f06f9e774/route53/hosted_zone.py#L304-L322 | [
"def",
"create_ns_record",
"(",
"self",
",",
"name",
",",
"values",
",",
"ttl",
"=",
"60",
")",
":",
"self",
".",
"_halt_if_already_deleted",
"(",
")",
"# Grab the params/kwargs here for brevity's sake.",
"values",
"=",
"locals",
"(",
")",
"del",
"values",
"[",
"'self'",
"]",
"return",
"self",
".",
"_add_record",
"(",
"NSResourceRecordSet",
",",
"*",
"*",
"values",
")"
] | b9fc7e258a79551c9ed61e4a71668b7f06f9e774 |
test | HostedZone.create_ptr_record | Creates a PTR record attached to this hosted zone.
:param str name: The fully qualified name of the record to add.
:param list values: A list of value strings for the record.
:keyword int ttl: The time-to-live of the record (in seconds).
:rtype: tuple
:returns: A tuple in the form of ``(rrset, change_info)``, where
``rrset`` is the newly created PTRResourceRecordSet instance. | route53/hosted_zone.py | def create_ptr_record(self, name, values, ttl=60):
"""
Creates a PTR record attached to this hosted zone.
:param str name: The fully qualified name of the record to add.
:param list values: A list of value strings for the record.
:keyword int ttl: The time-to-live of the record (in seconds).
:rtype: tuple
:returns: A tuple in the form of ``(rrset, change_info)``, where
``rrset`` is the newly created PTRResourceRecordSet instance.
"""
self._halt_if_already_deleted()
# Grab the params/kwargs here for brevity's sake.
values = locals()
del values['self']
return self._add_record(PTRResourceRecordSet, **values) | def create_ptr_record(self, name, values, ttl=60):
"""
Creates a PTR record attached to this hosted zone.
:param str name: The fully qualified name of the record to add.
:param list values: A list of value strings for the record.
:keyword int ttl: The time-to-live of the record (in seconds).
:rtype: tuple
:returns: A tuple in the form of ``(rrset, change_info)``, where
``rrset`` is the newly created PTRResourceRecordSet instance.
"""
self._halt_if_already_deleted()
# Grab the params/kwargs here for brevity's sake.
values = locals()
del values['self']
return self._add_record(PTRResourceRecordSet, **values) | [
"Creates",
"a",
"PTR",
"record",
"attached",
"to",
"this",
"hosted",
"zone",
"."
] | gtaylor/python-route53 | python | https://github.com/gtaylor/python-route53/blob/b9fc7e258a79551c9ed61e4a71668b7f06f9e774/route53/hosted_zone.py#L324-L342 | [
"def",
"create_ptr_record",
"(",
"self",
",",
"name",
",",
"values",
",",
"ttl",
"=",
"60",
")",
":",
"self",
".",
"_halt_if_already_deleted",
"(",
")",
"# Grab the params/kwargs here for brevity's sake.",
"values",
"=",
"locals",
"(",
")",
"del",
"values",
"[",
"'self'",
"]",
"return",
"self",
".",
"_add_record",
"(",
"PTRResourceRecordSet",
",",
"*",
"*",
"values",
")"
] | b9fc7e258a79551c9ed61e4a71668b7f06f9e774 |
test | HostedZone.create_spf_record | Creates a SPF record attached to this hosted zone.
:param str name: The fully qualified name of the record to add.
:param list values: A list of value strings for the record.
:keyword int ttl: The time-to-live of the record (in seconds).
:rtype: tuple
:returns: A tuple in the form of ``(rrset, change_info)``, where
``rrset`` is the newly created SPFResourceRecordSet instance. | route53/hosted_zone.py | def create_spf_record(self, name, values, ttl=60):
"""
Creates a SPF record attached to this hosted zone.
:param str name: The fully qualified name of the record to add.
:param list values: A list of value strings for the record.
:keyword int ttl: The time-to-live of the record (in seconds).
:rtype: tuple
:returns: A tuple in the form of ``(rrset, change_info)``, where
``rrset`` is the newly created SPFResourceRecordSet instance.
"""
self._halt_if_already_deleted()
# Grab the params/kwargs here for brevity's sake.
values = locals()
del values['self']
return self._add_record(SPFResourceRecordSet, **values) | def create_spf_record(self, name, values, ttl=60):
"""
Creates a SPF record attached to this hosted zone.
:param str name: The fully qualified name of the record to add.
:param list values: A list of value strings for the record.
:keyword int ttl: The time-to-live of the record (in seconds).
:rtype: tuple
:returns: A tuple in the form of ``(rrset, change_info)``, where
``rrset`` is the newly created SPFResourceRecordSet instance.
"""
self._halt_if_already_deleted()
# Grab the params/kwargs here for brevity's sake.
values = locals()
del values['self']
return self._add_record(SPFResourceRecordSet, **values) | [
"Creates",
"a",
"SPF",
"record",
"attached",
"to",
"this",
"hosted",
"zone",
"."
] | gtaylor/python-route53 | python | https://github.com/gtaylor/python-route53/blob/b9fc7e258a79551c9ed61e4a71668b7f06f9e774/route53/hosted_zone.py#L344-L362 | [
"def",
"create_spf_record",
"(",
"self",
",",
"name",
",",
"values",
",",
"ttl",
"=",
"60",
")",
":",
"self",
".",
"_halt_if_already_deleted",
"(",
")",
"# Grab the params/kwargs here for brevity's sake.",
"values",
"=",
"locals",
"(",
")",
"del",
"values",
"[",
"'self'",
"]",
"return",
"self",
".",
"_add_record",
"(",
"SPFResourceRecordSet",
",",
"*",
"*",
"values",
")"
] | b9fc7e258a79551c9ed61e4a71668b7f06f9e774 |
test | HostedZone.create_srv_record | Creates a SRV record attached to this hosted zone.
:param str name: The fully qualified name of the record to add.
:param list values: A list of value strings for the record.
:keyword int ttl: The time-to-live of the record (in seconds).
:rtype: tuple
:returns: A tuple in the form of ``(rrset, change_info)``, where
``rrset`` is the newly created SRVResourceRecordSet instance. | route53/hosted_zone.py | def create_srv_record(self, name, values, ttl=60):
"""
Creates a SRV record attached to this hosted zone.
:param str name: The fully qualified name of the record to add.
:param list values: A list of value strings for the record.
:keyword int ttl: The time-to-live of the record (in seconds).
:rtype: tuple
:returns: A tuple in the form of ``(rrset, change_info)``, where
``rrset`` is the newly created SRVResourceRecordSet instance.
"""
self._halt_if_already_deleted()
# Grab the params/kwargs here for brevity's sake.
values = locals()
del values['self']
return self._add_record(SRVResourceRecordSet, **values) | def create_srv_record(self, name, values, ttl=60):
"""
Creates a SRV record attached to this hosted zone.
:param str name: The fully qualified name of the record to add.
:param list values: A list of value strings for the record.
:keyword int ttl: The time-to-live of the record (in seconds).
:rtype: tuple
:returns: A tuple in the form of ``(rrset, change_info)``, where
``rrset`` is the newly created SRVResourceRecordSet instance.
"""
self._halt_if_already_deleted()
# Grab the params/kwargs here for brevity's sake.
values = locals()
del values['self']
return self._add_record(SRVResourceRecordSet, **values) | [
"Creates",
"a",
"SRV",
"record",
"attached",
"to",
"this",
"hosted",
"zone",
"."
] | gtaylor/python-route53 | python | https://github.com/gtaylor/python-route53/blob/b9fc7e258a79551c9ed61e4a71668b7f06f9e774/route53/hosted_zone.py#L364-L382 | [
"def",
"create_srv_record",
"(",
"self",
",",
"name",
",",
"values",
",",
"ttl",
"=",
"60",
")",
":",
"self",
".",
"_halt_if_already_deleted",
"(",
")",
"# Grab the params/kwargs here for brevity's sake.",
"values",
"=",
"locals",
"(",
")",
"del",
"values",
"[",
"'self'",
"]",
"return",
"self",
".",
"_add_record",
"(",
"SRVResourceRecordSet",
",",
"*",
"*",
"values",
")"
] | b9fc7e258a79551c9ed61e4a71668b7f06f9e774 |
test | HostedZone.create_txt_record | Creates a TXT record attached to this hosted zone.
:param str name: The fully qualified name of the record to add.
:param list values: A list of value strings for the record.
:keyword int ttl: The time-to-live of the record (in seconds).
:keyword int weight: *For weighted record sets only*. Among resource record
sets that have the same combination of DNS name and type, a value
that determines what portion of traffic for the current resource
record set is routed to the associated location. Ranges from 0-255.
:keyword str region: *For latency-based record sets*. The Amazon EC2 region
where the resource that is specified in this resource record set
resides.
:keyword str set_identifier: *For weighted and latency resource record
sets only*. An identifier that differentiates among multiple
resource record sets that have the same combination of DNS name
and type. 1-128 chars.
:rtype: tuple
:returns: A tuple in the form of ``(rrset, change_info)``, where
``rrset`` is the newly created TXTResourceRecordSet instance. | route53/hosted_zone.py | def create_txt_record(self, name, values, ttl=60, weight=None, region=None,
set_identifier=None):
"""
Creates a TXT record attached to this hosted zone.
:param str name: The fully qualified name of the record to add.
:param list values: A list of value strings for the record.
:keyword int ttl: The time-to-live of the record (in seconds).
:keyword int weight: *For weighted record sets only*. Among resource record
sets that have the same combination of DNS name and type, a value
that determines what portion of traffic for the current resource
record set is routed to the associated location. Ranges from 0-255.
:keyword str region: *For latency-based record sets*. The Amazon EC2 region
where the resource that is specified in this resource record set
resides.
:keyword str set_identifier: *For weighted and latency resource record
sets only*. An identifier that differentiates among multiple
resource record sets that have the same combination of DNS name
and type. 1-128 chars.
:rtype: tuple
:returns: A tuple in the form of ``(rrset, change_info)``, where
``rrset`` is the newly created TXTResourceRecordSet instance.
"""
self._halt_if_already_deleted()
# Grab the params/kwargs here for brevity's sake.
values = locals()
del values['self']
return self._add_record(TXTResourceRecordSet, **values) | def create_txt_record(self, name, values, ttl=60, weight=None, region=None,
set_identifier=None):
"""
Creates a TXT record attached to this hosted zone.
:param str name: The fully qualified name of the record to add.
:param list values: A list of value strings for the record.
:keyword int ttl: The time-to-live of the record (in seconds).
:keyword int weight: *For weighted record sets only*. Among resource record
sets that have the same combination of DNS name and type, a value
that determines what portion of traffic for the current resource
record set is routed to the associated location. Ranges from 0-255.
:keyword str region: *For latency-based record sets*. The Amazon EC2 region
where the resource that is specified in this resource record set
resides.
:keyword str set_identifier: *For weighted and latency resource record
sets only*. An identifier that differentiates among multiple
resource record sets that have the same combination of DNS name
and type. 1-128 chars.
:rtype: tuple
:returns: A tuple in the form of ``(rrset, change_info)``, where
``rrset`` is the newly created TXTResourceRecordSet instance.
"""
self._halt_if_already_deleted()
# Grab the params/kwargs here for brevity's sake.
values = locals()
del values['self']
return self._add_record(TXTResourceRecordSet, **values) | [
"Creates",
"a",
"TXT",
"record",
"attached",
"to",
"this",
"hosted",
"zone",
"."
] | gtaylor/python-route53 | python | https://github.com/gtaylor/python-route53/blob/b9fc7e258a79551c9ed61e4a71668b7f06f9e774/route53/hosted_zone.py#L384-L414 | [
"def",
"create_txt_record",
"(",
"self",
",",
"name",
",",
"values",
",",
"ttl",
"=",
"60",
",",
"weight",
"=",
"None",
",",
"region",
"=",
"None",
",",
"set_identifier",
"=",
"None",
")",
":",
"self",
".",
"_halt_if_already_deleted",
"(",
")",
"# Grab the params/kwargs here for brevity's sake.",
"values",
"=",
"locals",
"(",
")",
"del",
"values",
"[",
"'self'",
"]",
"return",
"self",
".",
"_add_record",
"(",
"TXTResourceRecordSet",
",",
"*",
"*",
"values",
")"
] | b9fc7e258a79551c9ed61e4a71668b7f06f9e774 |
test | EasyID3.RegisterTXXXKey | Register a user-defined text frame key.
Some ID3 tags are stored in TXXX frames, which allow a
freeform 'description' which acts as a subkey,
e.g. TXXX:BARCODE.::
EasyID3.RegisterTXXXKey('barcode', 'BARCODE'). | mutagen/easyid3.py | def RegisterTXXXKey(cls, key, desc):
"""Register a user-defined text frame key.
Some ID3 tags are stored in TXXX frames, which allow a
freeform 'description' which acts as a subkey,
e.g. TXXX:BARCODE.::
EasyID3.RegisterTXXXKey('barcode', 'BARCODE').
"""
frameid = "TXXX:" + desc
def getter(id3, key):
return list(id3[frameid])
def setter(id3, key, value):
try:
frame = id3[frameid]
except KeyError:
enc = 0
# Store 8859-1 if we can, per MusicBrainz spec.
try:
for v in value:
v.encode('latin_1')
except UnicodeError:
enc = 3
id3.add(mutagen.id3.TXXX(encoding=enc, text=value, desc=desc))
else:
frame.text = value
def deleter(id3, key):
del(id3[frameid])
cls.RegisterKey(key, getter, setter, deleter) | def RegisterTXXXKey(cls, key, desc):
"""Register a user-defined text frame key.
Some ID3 tags are stored in TXXX frames, which allow a
freeform 'description' which acts as a subkey,
e.g. TXXX:BARCODE.::
EasyID3.RegisterTXXXKey('barcode', 'BARCODE').
"""
frameid = "TXXX:" + desc
def getter(id3, key):
return list(id3[frameid])
def setter(id3, key, value):
try:
frame = id3[frameid]
except KeyError:
enc = 0
# Store 8859-1 if we can, per MusicBrainz spec.
try:
for v in value:
v.encode('latin_1')
except UnicodeError:
enc = 3
id3.add(mutagen.id3.TXXX(encoding=enc, text=value, desc=desc))
else:
frame.text = value
def deleter(id3, key):
del(id3[frameid])
cls.RegisterKey(key, getter, setter, deleter) | [
"Register",
"a",
"user",
"-",
"defined",
"text",
"frame",
"key",
"."
] | LordSputnik/mutagen | python | https://github.com/LordSputnik/mutagen/blob/38e62c8dc35c72b16554f5dbe7c0fde91acc3411/mutagen/easyid3.py#L141-L174 | [
"def",
"RegisterTXXXKey",
"(",
"cls",
",",
"key",
",",
"desc",
")",
":",
"frameid",
"=",
"\"TXXX:\"",
"+",
"desc",
"def",
"getter",
"(",
"id3",
",",
"key",
")",
":",
"return",
"list",
"(",
"id3",
"[",
"frameid",
"]",
")",
"def",
"setter",
"(",
"id3",
",",
"key",
",",
"value",
")",
":",
"try",
":",
"frame",
"=",
"id3",
"[",
"frameid",
"]",
"except",
"KeyError",
":",
"enc",
"=",
"0",
"# Store 8859-1 if we can, per MusicBrainz spec.",
"try",
":",
"for",
"v",
"in",
"value",
":",
"v",
".",
"encode",
"(",
"'latin_1'",
")",
"except",
"UnicodeError",
":",
"enc",
"=",
"3",
"id3",
".",
"add",
"(",
"mutagen",
".",
"id3",
".",
"TXXX",
"(",
"encoding",
"=",
"enc",
",",
"text",
"=",
"value",
",",
"desc",
"=",
"desc",
")",
")",
"else",
":",
"frame",
".",
"text",
"=",
"value",
"def",
"deleter",
"(",
"id3",
",",
"key",
")",
":",
"del",
"(",
"id3",
"[",
"frameid",
"]",
")",
"cls",
".",
"RegisterKey",
"(",
"key",
",",
"getter",
",",
"setter",
",",
"deleter",
")"
] | 38e62c8dc35c72b16554f5dbe7c0fde91acc3411 |
test | get_change_values | In the case of deletions, we pull the change values for the XML request
from the ResourceRecordSet._initial_vals dict, since we want the original
values. For creations, we pull from the attributes on ResourceRecordSet.
Since we're dealing with attributes vs. dict key/vals, we'll abstract
this part away here and just always pass a dict to write_change.
:rtype: dict
:returns: A dict of change data, used by :py:func:`write_change` to
write the change request XML. | route53/xml_generators/change_resource_record_set.py | def get_change_values(change):
"""
In the case of deletions, we pull the change values for the XML request
from the ResourceRecordSet._initial_vals dict, since we want the original
values. For creations, we pull from the attributes on ResourceRecordSet.
Since we're dealing with attributes vs. dict key/vals, we'll abstract
this part away here and just always pass a dict to write_change.
:rtype: dict
:returns: A dict of change data, used by :py:func:`write_change` to
write the change request XML.
"""
action, rrset = change
if action == 'CREATE':
# For creations, we want the current values, since they don't need to
# match an existing record set.
values = dict()
for key, val in rrset._initial_vals.items():
# Pull from the record set's attributes, which are the current
# values.
values[key] = getattr(rrset, key)
return values
else:
# We can look at the initial values dict for deletions, since we
# have to match against the values currently in Route53.
return rrset._initial_vals | def get_change_values(change):
"""
In the case of deletions, we pull the change values for the XML request
from the ResourceRecordSet._initial_vals dict, since we want the original
values. For creations, we pull from the attributes on ResourceRecordSet.
Since we're dealing with attributes vs. dict key/vals, we'll abstract
this part away here and just always pass a dict to write_change.
:rtype: dict
:returns: A dict of change data, used by :py:func:`write_change` to
write the change request XML.
"""
action, rrset = change
if action == 'CREATE':
# For creations, we want the current values, since they don't need to
# match an existing record set.
values = dict()
for key, val in rrset._initial_vals.items():
# Pull from the record set's attributes, which are the current
# values.
values[key] = getattr(rrset, key)
return values
else:
# We can look at the initial values dict for deletions, since we
# have to match against the values currently in Route53.
return rrset._initial_vals | [
"In",
"the",
"case",
"of",
"deletions",
"we",
"pull",
"the",
"change",
"values",
"for",
"the",
"XML",
"request",
"from",
"the",
"ResourceRecordSet",
".",
"_initial_vals",
"dict",
"since",
"we",
"want",
"the",
"original",
"values",
".",
"For",
"creations",
"we",
"pull",
"from",
"the",
"attributes",
"on",
"ResourceRecordSet",
"."
] | gtaylor/python-route53 | python | https://github.com/gtaylor/python-route53/blob/b9fc7e258a79551c9ed61e4a71668b7f06f9e774/route53/xml_generators/change_resource_record_set.py#L5-L33 | [
"def",
"get_change_values",
"(",
"change",
")",
":",
"action",
",",
"rrset",
"=",
"change",
"if",
"action",
"==",
"'CREATE'",
":",
"# For creations, we want the current values, since they don't need to",
"# match an existing record set.",
"values",
"=",
"dict",
"(",
")",
"for",
"key",
",",
"val",
"in",
"rrset",
".",
"_initial_vals",
".",
"items",
"(",
")",
":",
"# Pull from the record set's attributes, which are the current",
"# values.",
"values",
"[",
"key",
"]",
"=",
"getattr",
"(",
"rrset",
",",
"key",
")",
"return",
"values",
"else",
":",
"# We can look at the initial values dict for deletions, since we",
"# have to match against the values currently in Route53.",
"return",
"rrset",
".",
"_initial_vals"
] | b9fc7e258a79551c9ed61e4a71668b7f06f9e774 |
test | write_change | Creates an XML element for the change.
:param tuple change: A change tuple from a ChangeSet. Comes in the form
of ``(action, rrset)``.
:rtype: lxml.etree._Element
:returns: A fully baked Change tag. | route53/xml_generators/change_resource_record_set.py | def write_change(change):
"""
Creates an XML element for the change.
:param tuple change: A change tuple from a ChangeSet. Comes in the form
of ``(action, rrset)``.
:rtype: lxml.etree._Element
:returns: A fully baked Change tag.
"""
action, rrset = change
change_vals = get_change_values(change)
e_change = etree.Element("Change")
e_action = etree.SubElement(e_change, "Action")
e_action.text = action
e_rrset = etree.SubElement(e_change, "ResourceRecordSet")
e_name = etree.SubElement(e_rrset, "Name")
e_name.text = change_vals['name']
e_type = etree.SubElement(e_rrset, "Type")
e_type.text = rrset.rrset_type
if change_vals.get('set_identifier'):
e_set_id = etree.SubElement(e_rrset, "SetIdentifier")
e_set_id.text = change_vals['set_identifier']
if change_vals.get('weight'):
e_weight = etree.SubElement(e_rrset, "Weight")
e_weight.text = change_vals['weight']
if change_vals.get('alias_hosted_zone_id') or change_vals.get('alias_dns_name'):
e_alias_target = etree.SubElement(e_rrset, "AliasTarget")
e_hosted_zone_id = etree.SubElement(e_alias_target, "HostedZoneId")
e_hosted_zone_id.text = change_vals['alias_hosted_zone_id']
e_dns_name = etree.SubElement(e_alias_target, "DNSName")
e_dns_name.text = change_vals['alias_dns_name']
if change_vals.get('region'):
e_weight = etree.SubElement(e_rrset, "Region")
e_weight.text = change_vals['region']
e_ttl = etree.SubElement(e_rrset, "TTL")
e_ttl.text = str(change_vals['ttl'])
if rrset.is_alias_record_set():
# A record sets in Alias mode don't have any resource records.
return e_change
e_resource_records = etree.SubElement(e_rrset, "ResourceRecords")
for value in change_vals['records']:
e_resource_record = etree.SubElement(e_resource_records, "ResourceRecord")
e_value = etree.SubElement(e_resource_record, "Value")
e_value.text = value
return e_change | def write_change(change):
"""
Creates an XML element for the change.
:param tuple change: A change tuple from a ChangeSet. Comes in the form
of ``(action, rrset)``.
:rtype: lxml.etree._Element
:returns: A fully baked Change tag.
"""
action, rrset = change
change_vals = get_change_values(change)
e_change = etree.Element("Change")
e_action = etree.SubElement(e_change, "Action")
e_action.text = action
e_rrset = etree.SubElement(e_change, "ResourceRecordSet")
e_name = etree.SubElement(e_rrset, "Name")
e_name.text = change_vals['name']
e_type = etree.SubElement(e_rrset, "Type")
e_type.text = rrset.rrset_type
if change_vals.get('set_identifier'):
e_set_id = etree.SubElement(e_rrset, "SetIdentifier")
e_set_id.text = change_vals['set_identifier']
if change_vals.get('weight'):
e_weight = etree.SubElement(e_rrset, "Weight")
e_weight.text = change_vals['weight']
if change_vals.get('alias_hosted_zone_id') or change_vals.get('alias_dns_name'):
e_alias_target = etree.SubElement(e_rrset, "AliasTarget")
e_hosted_zone_id = etree.SubElement(e_alias_target, "HostedZoneId")
e_hosted_zone_id.text = change_vals['alias_hosted_zone_id']
e_dns_name = etree.SubElement(e_alias_target, "DNSName")
e_dns_name.text = change_vals['alias_dns_name']
if change_vals.get('region'):
e_weight = etree.SubElement(e_rrset, "Region")
e_weight.text = change_vals['region']
e_ttl = etree.SubElement(e_rrset, "TTL")
e_ttl.text = str(change_vals['ttl'])
if rrset.is_alias_record_set():
# A record sets in Alias mode don't have any resource records.
return e_change
e_resource_records = etree.SubElement(e_rrset, "ResourceRecords")
for value in change_vals['records']:
e_resource_record = etree.SubElement(e_resource_records, "ResourceRecord")
e_value = etree.SubElement(e_resource_record, "Value")
e_value.text = value
return e_change | [
"Creates",
"an",
"XML",
"element",
"for",
"the",
"change",
"."
] | gtaylor/python-route53 | python | https://github.com/gtaylor/python-route53/blob/b9fc7e258a79551c9ed61e4a71668b7f06f9e774/route53/xml_generators/change_resource_record_set.py#L35-L96 | [
"def",
"write_change",
"(",
"change",
")",
":",
"action",
",",
"rrset",
"=",
"change",
"change_vals",
"=",
"get_change_values",
"(",
"change",
")",
"e_change",
"=",
"etree",
".",
"Element",
"(",
"\"Change\"",
")",
"e_action",
"=",
"etree",
".",
"SubElement",
"(",
"e_change",
",",
"\"Action\"",
")",
"e_action",
".",
"text",
"=",
"action",
"e_rrset",
"=",
"etree",
".",
"SubElement",
"(",
"e_change",
",",
"\"ResourceRecordSet\"",
")",
"e_name",
"=",
"etree",
".",
"SubElement",
"(",
"e_rrset",
",",
"\"Name\"",
")",
"e_name",
".",
"text",
"=",
"change_vals",
"[",
"'name'",
"]",
"e_type",
"=",
"etree",
".",
"SubElement",
"(",
"e_rrset",
",",
"\"Type\"",
")",
"e_type",
".",
"text",
"=",
"rrset",
".",
"rrset_type",
"if",
"change_vals",
".",
"get",
"(",
"'set_identifier'",
")",
":",
"e_set_id",
"=",
"etree",
".",
"SubElement",
"(",
"e_rrset",
",",
"\"SetIdentifier\"",
")",
"e_set_id",
".",
"text",
"=",
"change_vals",
"[",
"'set_identifier'",
"]",
"if",
"change_vals",
".",
"get",
"(",
"'weight'",
")",
":",
"e_weight",
"=",
"etree",
".",
"SubElement",
"(",
"e_rrset",
",",
"\"Weight\"",
")",
"e_weight",
".",
"text",
"=",
"change_vals",
"[",
"'weight'",
"]",
"if",
"change_vals",
".",
"get",
"(",
"'alias_hosted_zone_id'",
")",
"or",
"change_vals",
".",
"get",
"(",
"'alias_dns_name'",
")",
":",
"e_alias_target",
"=",
"etree",
".",
"SubElement",
"(",
"e_rrset",
",",
"\"AliasTarget\"",
")",
"e_hosted_zone_id",
"=",
"etree",
".",
"SubElement",
"(",
"e_alias_target",
",",
"\"HostedZoneId\"",
")",
"e_hosted_zone_id",
".",
"text",
"=",
"change_vals",
"[",
"'alias_hosted_zone_id'",
"]",
"e_dns_name",
"=",
"etree",
".",
"SubElement",
"(",
"e_alias_target",
",",
"\"DNSName\"",
")",
"e_dns_name",
".",
"text",
"=",
"change_vals",
"[",
"'alias_dns_name'",
"]",
"if",
"change_vals",
".",
"get",
"(",
"'region'",
")",
":",
"e_weight",
"=",
"etree",
".",
"SubElement",
"(",
"e_rrset",
",",
"\"Region\"",
")",
"e_weight",
".",
"text",
"=",
"change_vals",
"[",
"'region'",
"]",
"e_ttl",
"=",
"etree",
".",
"SubElement",
"(",
"e_rrset",
",",
"\"TTL\"",
")",
"e_ttl",
".",
"text",
"=",
"str",
"(",
"change_vals",
"[",
"'ttl'",
"]",
")",
"if",
"rrset",
".",
"is_alias_record_set",
"(",
")",
":",
"# A record sets in Alias mode don't have any resource records.",
"return",
"e_change",
"e_resource_records",
"=",
"etree",
".",
"SubElement",
"(",
"e_rrset",
",",
"\"ResourceRecords\"",
")",
"for",
"value",
"in",
"change_vals",
"[",
"'records'",
"]",
":",
"e_resource_record",
"=",
"etree",
".",
"SubElement",
"(",
"e_resource_records",
",",
"\"ResourceRecord\"",
")",
"e_value",
"=",
"etree",
".",
"SubElement",
"(",
"e_resource_record",
",",
"\"Value\"",
")",
"e_value",
".",
"text",
"=",
"value",
"return",
"e_change"
] | b9fc7e258a79551c9ed61e4a71668b7f06f9e774 |
test | change_resource_record_set_writer | Forms an XML string that we'll send to Route53 in order to change
record sets.
:param Route53Connection connection: The connection instance used to
query the API.
:param change_set.ChangeSet change_set: The ChangeSet object to create the
XML doc from.
:keyword str comment: An optional comment to go along with the request. | route53/xml_generators/change_resource_record_set.py | def change_resource_record_set_writer(connection, change_set, comment=None):
"""
Forms an XML string that we'll send to Route53 in order to change
record sets.
:param Route53Connection connection: The connection instance used to
query the API.
:param change_set.ChangeSet change_set: The ChangeSet object to create the
XML doc from.
:keyword str comment: An optional comment to go along with the request.
"""
e_root = etree.Element(
"ChangeResourceRecordSetsRequest",
xmlns=connection._xml_namespace
)
e_change_batch = etree.SubElement(e_root, "ChangeBatch")
if comment:
e_comment = etree.SubElement(e_change_batch, "Comment")
e_comment.text = comment
e_changes = etree.SubElement(e_change_batch, "Changes")
# Deletions need to come first in the change sets.
for change in change_set.deletions + change_set.creations:
e_changes.append(write_change(change))
e_tree = etree.ElementTree(element=e_root)
#print(prettyprint_xml(e_root))
fobj = BytesIO()
# This writes bytes.
e_tree.write(fobj, xml_declaration=True, encoding='utf-8', method="xml")
return fobj.getvalue().decode('utf-8') | def change_resource_record_set_writer(connection, change_set, comment=None):
"""
Forms an XML string that we'll send to Route53 in order to change
record sets.
:param Route53Connection connection: The connection instance used to
query the API.
:param change_set.ChangeSet change_set: The ChangeSet object to create the
XML doc from.
:keyword str comment: An optional comment to go along with the request.
"""
e_root = etree.Element(
"ChangeResourceRecordSetsRequest",
xmlns=connection._xml_namespace
)
e_change_batch = etree.SubElement(e_root, "ChangeBatch")
if comment:
e_comment = etree.SubElement(e_change_batch, "Comment")
e_comment.text = comment
e_changes = etree.SubElement(e_change_batch, "Changes")
# Deletions need to come first in the change sets.
for change in change_set.deletions + change_set.creations:
e_changes.append(write_change(change))
e_tree = etree.ElementTree(element=e_root)
#print(prettyprint_xml(e_root))
fobj = BytesIO()
# This writes bytes.
e_tree.write(fobj, xml_declaration=True, encoding='utf-8', method="xml")
return fobj.getvalue().decode('utf-8') | [
"Forms",
"an",
"XML",
"string",
"that",
"we",
"ll",
"send",
"to",
"Route53",
"in",
"order",
"to",
"change",
"record",
"sets",
"."
] | gtaylor/python-route53 | python | https://github.com/gtaylor/python-route53/blob/b9fc7e258a79551c9ed61e4a71668b7f06f9e774/route53/xml_generators/change_resource_record_set.py#L98-L134 | [
"def",
"change_resource_record_set_writer",
"(",
"connection",
",",
"change_set",
",",
"comment",
"=",
"None",
")",
":",
"e_root",
"=",
"etree",
".",
"Element",
"(",
"\"ChangeResourceRecordSetsRequest\"",
",",
"xmlns",
"=",
"connection",
".",
"_xml_namespace",
")",
"e_change_batch",
"=",
"etree",
".",
"SubElement",
"(",
"e_root",
",",
"\"ChangeBatch\"",
")",
"if",
"comment",
":",
"e_comment",
"=",
"etree",
".",
"SubElement",
"(",
"e_change_batch",
",",
"\"Comment\"",
")",
"e_comment",
".",
"text",
"=",
"comment",
"e_changes",
"=",
"etree",
".",
"SubElement",
"(",
"e_change_batch",
",",
"\"Changes\"",
")",
"# Deletions need to come first in the change sets.",
"for",
"change",
"in",
"change_set",
".",
"deletions",
"+",
"change_set",
".",
"creations",
":",
"e_changes",
".",
"append",
"(",
"write_change",
"(",
"change",
")",
")",
"e_tree",
"=",
"etree",
".",
"ElementTree",
"(",
"element",
"=",
"e_root",
")",
"#print(prettyprint_xml(e_root))",
"fobj",
"=",
"BytesIO",
"(",
")",
"# This writes bytes.",
"e_tree",
".",
"write",
"(",
"fobj",
",",
"xml_declaration",
"=",
"True",
",",
"encoding",
"=",
"'utf-8'",
",",
"method",
"=",
"\"xml\"",
")",
"return",
"fobj",
".",
"getvalue",
"(",
")",
".",
"decode",
"(",
"'utf-8'",
")"
] | b9fc7e258a79551c9ed61e4a71668b7f06f9e774 |
test | init_logs | Initiate log file. | nanogui/nanogui.py | def init_logs():
"""Initiate log file."""
start_time = dt.fromtimestamp(time.time()).strftime('%Y%m%d_%H%M')
logname = os.path.join(os.path.expanduser("~") + "/nanoGUI_" + start_time + ".log")
handlers = [logging.FileHandler(logname)]
logging.basicConfig(
format='%(asctime)s %(message)s',
handlers=handlers,
level=logging.INFO)
logging.info('NanoGUI {} started with NanoPlot {}'.format(__version__, nanoplot.__version__))
logging.info('Python version is: {}'.format(sys.version.replace('\n', ' ')))
return logname | def init_logs():
"""Initiate log file."""
start_time = dt.fromtimestamp(time.time()).strftime('%Y%m%d_%H%M')
logname = os.path.join(os.path.expanduser("~") + "/nanoGUI_" + start_time + ".log")
handlers = [logging.FileHandler(logname)]
logging.basicConfig(
format='%(asctime)s %(message)s',
handlers=handlers,
level=logging.INFO)
logging.info('NanoGUI {} started with NanoPlot {}'.format(__version__, nanoplot.__version__))
logging.info('Python version is: {}'.format(sys.version.replace('\n', ' ')))
return logname | [
"Initiate",
"log",
"file",
"."
] | wdecoster/nanogui | python | https://github.com/wdecoster/nanogui/blob/78e4f8ca511c5ca9fd7ccd6ff03e8edd1a5db54d/nanogui/nanogui.py#L77-L88 | [
"def",
"init_logs",
"(",
")",
":",
"start_time",
"=",
"dt",
".",
"fromtimestamp",
"(",
"time",
".",
"time",
"(",
")",
")",
".",
"strftime",
"(",
"'%Y%m%d_%H%M'",
")",
"logname",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"expanduser",
"(",
"\"~\"",
")",
"+",
"\"/nanoGUI_\"",
"+",
"start_time",
"+",
"\".log\"",
")",
"handlers",
"=",
"[",
"logging",
".",
"FileHandler",
"(",
"logname",
")",
"]",
"logging",
".",
"basicConfig",
"(",
"format",
"=",
"'%(asctime)s %(message)s'",
",",
"handlers",
"=",
"handlers",
",",
"level",
"=",
"logging",
".",
"INFO",
")",
"logging",
".",
"info",
"(",
"'NanoGUI {} started with NanoPlot {}'",
".",
"format",
"(",
"__version__",
",",
"nanoplot",
".",
"__version__",
")",
")",
"logging",
".",
"info",
"(",
"'Python version is: {}'",
".",
"format",
"(",
"sys",
".",
"version",
".",
"replace",
"(",
"'\\n'",
",",
"' '",
")",
")",
")",
"return",
"logname"
] | 78e4f8ca511c5ca9fd7ccd6ff03e8edd1a5db54d |
test | nanoPlotGui.validate_integer | Check if text Entry is valid (number).
I have no idea what all these arguments are doing here but took this from
https://stackoverflow.com/questions/8959815/restricting-the-value-in-tkinter-entry-widget | nanogui/nanoguis.py | def validate_integer(self, action, index, value_if_allowed, prior_value,
text, validation_type, trigger_type, widget_name):
"""Check if text Entry is valid (number).
I have no idea what all these arguments are doing here but took this from
https://stackoverflow.com/questions/8959815/restricting-the-value-in-tkinter-entry-widget
"""
if(action == '1'):
if text in '0123456789.-+':
try:
int(value_if_allowed)
return True
except ValueError:
return False
else:
return False
else:
return True | def validate_integer(self, action, index, value_if_allowed, prior_value,
text, validation_type, trigger_type, widget_name):
"""Check if text Entry is valid (number).
I have no idea what all these arguments are doing here but took this from
https://stackoverflow.com/questions/8959815/restricting-the-value-in-tkinter-entry-widget
"""
if(action == '1'):
if text in '0123456789.-+':
try:
int(value_if_allowed)
return True
except ValueError:
return False
else:
return False
else:
return True | [
"Check",
"if",
"text",
"Entry",
"is",
"valid",
"(",
"number",
")",
"."
] | wdecoster/nanogui | python | https://github.com/wdecoster/nanogui/blob/78e4f8ca511c5ca9fd7ccd6ff03e8edd1a5db54d/nanogui/nanoguis.py#L454-L471 | [
"def",
"validate_integer",
"(",
"self",
",",
"action",
",",
"index",
",",
"value_if_allowed",
",",
"prior_value",
",",
"text",
",",
"validation_type",
",",
"trigger_type",
",",
"widget_name",
")",
":",
"if",
"(",
"action",
"==",
"'1'",
")",
":",
"if",
"text",
"in",
"'0123456789.-+'",
":",
"try",
":",
"int",
"(",
"value_if_allowed",
")",
"return",
"True",
"except",
"ValueError",
":",
"return",
"False",
"else",
":",
"return",
"False",
"else",
":",
"return",
"True"
] | 78e4f8ca511c5ca9fd7ccd6ff03e8edd1a5db54d |
test | NavigationBar.alias_item | Gets an item by its alias. | flask_navigation/navbar.py | def alias_item(self, alias):
"""Gets an item by its alias."""
ident = self.alias[alias]
return self.items[ident] | def alias_item(self, alias):
"""Gets an item by its alias."""
ident = self.alias[alias]
return self.items[ident] | [
"Gets",
"an",
"item",
"by",
"its",
"alias",
"."
] | tonyseek/flask-navigation | python | https://github.com/tonyseek/flask-navigation/blob/38fa83addcbe62f31516763fbe3c0bbdc793dc96/flask_navigation/navbar.py#L34-L37 | [
"def",
"alias_item",
"(",
"self",
",",
"alias",
")",
":",
"ident",
"=",
"self",
".",
"alias",
"[",
"alias",
"]",
"return",
"self",
".",
"items",
"[",
"ident",
"]"
] | 38fa83addcbe62f31516763fbe3c0bbdc793dc96 |
test | freeze_dict | Freezes ``dict`` into ``tuple``.
A typical usage is packing ``dict`` into hashable.
e.g.::
>>> freeze_dict({'a': 1, 'b': 2})
(('a', 1), ('b', 2)) | flask_navigation/utils.py | def freeze_dict(dict_):
"""Freezes ``dict`` into ``tuple``.
A typical usage is packing ``dict`` into hashable.
e.g.::
>>> freeze_dict({'a': 1, 'b': 2})
(('a', 1), ('b', 2))
"""
pairs = dict_.items()
key_getter = operator.itemgetter(0)
return tuple(sorted(pairs, key=key_getter)) | def freeze_dict(dict_):
"""Freezes ``dict`` into ``tuple``.
A typical usage is packing ``dict`` into hashable.
e.g.::
>>> freeze_dict({'a': 1, 'b': 2})
(('a', 1), ('b', 2))
"""
pairs = dict_.items()
key_getter = operator.itemgetter(0)
return tuple(sorted(pairs, key=key_getter)) | [
"Freezes",
"dict",
"into",
"tuple",
"."
] | tonyseek/flask-navigation | python | https://github.com/tonyseek/flask-navigation/blob/38fa83addcbe62f31516763fbe3c0bbdc793dc96/flask_navigation/utils.py#L5-L17 | [
"def",
"freeze_dict",
"(",
"dict_",
")",
":",
"pairs",
"=",
"dict_",
".",
"items",
"(",
")",
"key_getter",
"=",
"operator",
".",
"itemgetter",
"(",
"0",
")",
"return",
"tuple",
"(",
"sorted",
"(",
"pairs",
",",
"key",
"=",
"key_getter",
")",
")"
] | 38fa83addcbe62f31516763fbe3c0bbdc793dc96 |
test | join_html_attrs | Joins the map structure into HTML attributes.
The return value is a 2-tuple ``(template, ordered_values)``. It should be
passed into :class:`markupsafe.Markup` to prevent XSS attacked.
e.g.::
>>> join_html_attrs({'href': '/', 'data-active': 'true'})
('data-active="{0}" href="{1}"', ['true', '/']) | flask_navigation/utils.py | def join_html_attrs(attrs):
"""Joins the map structure into HTML attributes.
The return value is a 2-tuple ``(template, ordered_values)``. It should be
passed into :class:`markupsafe.Markup` to prevent XSS attacked.
e.g.::
>>> join_html_attrs({'href': '/', 'data-active': 'true'})
('data-active="{0}" href="{1}"', ['true', '/'])
"""
attrs = collections.OrderedDict(freeze_dict(attrs or {}))
template = ' '.join('%s="{%d}"' % (k, i) for i, k in enumerate(attrs))
return template, list(attrs.values()) | def join_html_attrs(attrs):
"""Joins the map structure into HTML attributes.
The return value is a 2-tuple ``(template, ordered_values)``. It should be
passed into :class:`markupsafe.Markup` to prevent XSS attacked.
e.g.::
>>> join_html_attrs({'href': '/', 'data-active': 'true'})
('data-active="{0}" href="{1}"', ['true', '/'])
"""
attrs = collections.OrderedDict(freeze_dict(attrs or {}))
template = ' '.join('%s="{%d}"' % (k, i) for i, k in enumerate(attrs))
return template, list(attrs.values()) | [
"Joins",
"the",
"map",
"structure",
"into",
"HTML",
"attributes",
"."
] | tonyseek/flask-navigation | python | https://github.com/tonyseek/flask-navigation/blob/38fa83addcbe62f31516763fbe3c0bbdc793dc96/flask_navigation/utils.py#L20-L33 | [
"def",
"join_html_attrs",
"(",
"attrs",
")",
":",
"attrs",
"=",
"collections",
".",
"OrderedDict",
"(",
"freeze_dict",
"(",
"attrs",
"or",
"{",
"}",
")",
")",
"template",
"=",
"' '",
".",
"join",
"(",
"'%s=\"{%d}\"'",
"%",
"(",
"k",
",",
"i",
")",
"for",
"i",
",",
"k",
"in",
"enumerate",
"(",
"attrs",
")",
")",
"return",
"template",
",",
"list",
"(",
"attrs",
".",
"values",
"(",
")",
")"
] | 38fa83addcbe62f31516763fbe3c0bbdc793dc96 |
test | Navigation.init_app | Initializes an app to work with this extension.
The app-context signals will be subscribed and the template context
will be initialized.
:param app: the :class:`flask.Flask` app instance. | flask_navigation/api.py | def init_app(self, app):
"""Initializes an app to work with this extension.
The app-context signals will be subscribed and the template context
will be initialized.
:param app: the :class:`flask.Flask` app instance.
"""
# connects app-level signals
appcontext_pushed.connect(self.initialize_bars, app)
# integrate with jinja template
app.add_template_global(self, 'nav') | def init_app(self, app):
"""Initializes an app to work with this extension.
The app-context signals will be subscribed and the template context
will be initialized.
:param app: the :class:`flask.Flask` app instance.
"""
# connects app-level signals
appcontext_pushed.connect(self.initialize_bars, app)
# integrate with jinja template
app.add_template_global(self, 'nav') | [
"Initializes",
"an",
"app",
"to",
"work",
"with",
"this",
"extension",
"."
] | tonyseek/flask-navigation | python | https://github.com/tonyseek/flask-navigation/blob/38fa83addcbe62f31516763fbe3c0bbdc793dc96/flask_navigation/api.py#L37-L48 | [
"def",
"init_app",
"(",
"self",
",",
"app",
")",
":",
"# connects app-level signals",
"appcontext_pushed",
".",
"connect",
"(",
"self",
".",
"initialize_bars",
",",
"app",
")",
"# integrate with jinja template",
"app",
".",
"add_template_global",
"(",
"self",
",",
"'nav'",
")"
] | 38fa83addcbe62f31516763fbe3c0bbdc793dc96 |
test | Navigation.initialize_bars | Calls the initializers of all bound navigation bars. | flask_navigation/api.py | def initialize_bars(self, sender=None, **kwargs):
"""Calls the initializers of all bound navigation bars."""
for bar in self.bars.values():
for initializer in bar.initializers:
initializer(self) | def initialize_bars(self, sender=None, **kwargs):
"""Calls the initializers of all bound navigation bars."""
for bar in self.bars.values():
for initializer in bar.initializers:
initializer(self) | [
"Calls",
"the",
"initializers",
"of",
"all",
"bound",
"navigation",
"bars",
"."
] | tonyseek/flask-navigation | python | https://github.com/tonyseek/flask-navigation/blob/38fa83addcbe62f31516763fbe3c0bbdc793dc96/flask_navigation/api.py#L50-L54 | [
"def",
"initialize_bars",
"(",
"self",
",",
"sender",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"bar",
"in",
"self",
".",
"bars",
".",
"values",
"(",
")",
":",
"for",
"initializer",
"in",
"bar",
".",
"initializers",
":",
"initializer",
"(",
"self",
")"
] | 38fa83addcbe62f31516763fbe3c0bbdc793dc96 |
test | Navigation.bind_bar | Binds a navigation bar into this extension instance. | flask_navigation/api.py | def bind_bar(self, sender=None, **kwargs):
"""Binds a navigation bar into this extension instance."""
bar = kwargs.pop('bar')
self.bars[bar.name] = bar | def bind_bar(self, sender=None, **kwargs):
"""Binds a navigation bar into this extension instance."""
bar = kwargs.pop('bar')
self.bars[bar.name] = bar | [
"Binds",
"a",
"navigation",
"bar",
"into",
"this",
"extension",
"instance",
"."
] | tonyseek/flask-navigation | python | https://github.com/tonyseek/flask-navigation/blob/38fa83addcbe62f31516763fbe3c0bbdc793dc96/flask_navigation/api.py#L56-L59 | [
"def",
"bind_bar",
"(",
"self",
",",
"sender",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"bar",
"=",
"kwargs",
".",
"pop",
"(",
"'bar'",
")",
"self",
".",
"bars",
"[",
"bar",
".",
"name",
"]",
"=",
"bar"
] | 38fa83addcbe62f31516763fbe3c0bbdc793dc96 |
test | Item.args | The arguments which will be passed to ``url_for``.
:type: :class:`dict` | flask_navigation/item.py | def args(self):
"""The arguments which will be passed to ``url_for``.
:type: :class:`dict`
"""
if self._args is None:
return {}
if callable(self._args):
return dict(self._args())
return dict(self._args) | def args(self):
"""The arguments which will be passed to ``url_for``.
:type: :class:`dict`
"""
if self._args is None:
return {}
if callable(self._args):
return dict(self._args())
return dict(self._args) | [
"The",
"arguments",
"which",
"will",
"be",
"passed",
"to",
"url_for",
"."
] | tonyseek/flask-navigation | python | https://github.com/tonyseek/flask-navigation/blob/38fa83addcbe62f31516763fbe3c0bbdc793dc96/flask_navigation/item.py#L68-L77 | [
"def",
"args",
"(",
"self",
")",
":",
"if",
"self",
".",
"_args",
"is",
"None",
":",
"return",
"{",
"}",
"if",
"callable",
"(",
"self",
".",
"_args",
")",
":",
"return",
"dict",
"(",
"self",
".",
"_args",
"(",
")",
")",
"return",
"dict",
"(",
"self",
".",
"_args",
")"
] | 38fa83addcbe62f31516763fbe3c0bbdc793dc96 |
test | Item.url | The final url of this navigation item.
By default, the value is generated by the :attr:`self.endpoint` and
:attr:`self.args`.
.. note::
The :attr:`url` property require the app context without a provided
config value :const:`SERVER_NAME`, because of :func:`flask.url_for`.
:type: :class:`str` | flask_navigation/item.py | def url(self):
"""The final url of this navigation item.
By default, the value is generated by the :attr:`self.endpoint` and
:attr:`self.args`.
.. note::
The :attr:`url` property require the app context without a provided
config value :const:`SERVER_NAME`, because of :func:`flask.url_for`.
:type: :class:`str`
"""
if self.is_internal:
return url_for(self.endpoint, **self.args)
return self._url | def url(self):
"""The final url of this navigation item.
By default, the value is generated by the :attr:`self.endpoint` and
:attr:`self.args`.
.. note::
The :attr:`url` property require the app context without a provided
config value :const:`SERVER_NAME`, because of :func:`flask.url_for`.
:type: :class:`str`
"""
if self.is_internal:
return url_for(self.endpoint, **self.args)
return self._url | [
"The",
"final",
"url",
"of",
"this",
"navigation",
"item",
"."
] | tonyseek/flask-navigation | python | https://github.com/tonyseek/flask-navigation/blob/38fa83addcbe62f31516763fbe3c0bbdc793dc96/flask_navigation/item.py#L80-L95 | [
"def",
"url",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_internal",
":",
"return",
"url_for",
"(",
"self",
".",
"endpoint",
",",
"*",
"*",
"self",
".",
"args",
")",
"return",
"self",
".",
"_url"
] | 38fa83addcbe62f31516763fbe3c0bbdc793dc96 |
test | Item.is_current | ``True`` if current request has same endpoint with the item.
The property should be used in a bound request context, or the
:class:`RuntimeError` may be raised. | flask_navigation/item.py | def is_current(self):
"""``True`` if current request has same endpoint with the item.
The property should be used in a bound request context, or the
:class:`RuntimeError` may be raised.
"""
if not self.is_internal:
return False # always false for external url
has_same_endpoint = (request.endpoint == self.endpoint)
has_same_args = (request.view_args == self.args)
return has_same_endpoint and has_same_args | def is_current(self):
"""``True`` if current request has same endpoint with the item.
The property should be used in a bound request context, or the
:class:`RuntimeError` may be raised.
"""
if not self.is_internal:
return False # always false for external url
has_same_endpoint = (request.endpoint == self.endpoint)
has_same_args = (request.view_args == self.args)
return has_same_endpoint and has_same_args | [
"True",
"if",
"current",
"request",
"has",
"same",
"endpoint",
"with",
"the",
"item",
"."
] | tonyseek/flask-navigation | python | https://github.com/tonyseek/flask-navigation/blob/38fa83addcbe62f31516763fbe3c0bbdc793dc96/flask_navigation/item.py#L110-L120 | [
"def",
"is_current",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_internal",
":",
"return",
"False",
"# always false for external url",
"has_same_endpoint",
"=",
"(",
"request",
".",
"endpoint",
"==",
"self",
".",
"endpoint",
")",
"has_same_args",
"=",
"(",
"request",
".",
"view_args",
"==",
"self",
".",
"args",
")",
"return",
"has_same_endpoint",
"and",
"has_same_args"
] | 38fa83addcbe62f31516763fbe3c0bbdc793dc96 |
test | YandexSpeller.lang | Set lang | pyaspeller/speller.py | def lang(self, language):
"""Set lang"""
if isinstance(language, str):
self._lang = [language]
elif isinstance(language, collections.Iterable):
self._lang = list(language)
if any(lang not in self._supported_langs for lang in self._lang):
raise BadArgumentError("Unsupported language") | def lang(self, language):
"""Set lang"""
if isinstance(language, str):
self._lang = [language]
elif isinstance(language, collections.Iterable):
self._lang = list(language)
if any(lang not in self._supported_langs for lang in self._lang):
raise BadArgumentError("Unsupported language") | [
"Set",
"lang"
] | oriontvv/pyaspeller | python | https://github.com/oriontvv/pyaspeller/blob/9a76d1f1fb00c7eabfa006f8e0f145f764c7a8d6/pyaspeller/speller.py#L136-L144 | [
"def",
"lang",
"(",
"self",
",",
"language",
")",
":",
"if",
"isinstance",
"(",
"language",
",",
"str",
")",
":",
"self",
".",
"_lang",
"=",
"[",
"language",
"]",
"elif",
"isinstance",
"(",
"language",
",",
"collections",
".",
"Iterable",
")",
":",
"self",
".",
"_lang",
"=",
"list",
"(",
"language",
")",
"if",
"any",
"(",
"lang",
"not",
"in",
"self",
".",
"_supported_langs",
"for",
"lang",
"in",
"self",
".",
"_lang",
")",
":",
"raise",
"BadArgumentError",
"(",
"\"Unsupported language\"",
")"
] | 9a76d1f1fb00c7eabfa006f8e0f145f764c7a8d6 |
test | YandexSpeller.config_path | Set config_path | pyaspeller/speller.py | def config_path(self, value):
"""Set config_path"""
self._config_path = value or ''
if not isinstance(self._config_path, str):
raise BadArgumentError("config_path must be string: {}".format(
self._config_path)) | def config_path(self, value):
"""Set config_path"""
self._config_path = value or ''
if not isinstance(self._config_path, str):
raise BadArgumentError("config_path must be string: {}".format(
self._config_path)) | [
"Set",
"config_path"
] | oriontvv/pyaspeller | python | https://github.com/oriontvv/pyaspeller/blob/9a76d1f1fb00c7eabfa006f8e0f145f764c7a8d6/pyaspeller/speller.py#L152-L157 | [
"def",
"config_path",
"(",
"self",
",",
"value",
")",
":",
"self",
".",
"_config_path",
"=",
"value",
"or",
"''",
"if",
"not",
"isinstance",
"(",
"self",
".",
"_config_path",
",",
"str",
")",
":",
"raise",
"BadArgumentError",
"(",
"\"config_path must be string: {}\"",
".",
"format",
"(",
"self",
".",
"_config_path",
")",
")"
] | 9a76d1f1fb00c7eabfa006f8e0f145f764c7a8d6 |
test | YandexSpeller.dictionary | Set dictionary | pyaspeller/speller.py | def dictionary(self, value):
"""Set dictionary"""
self._dictionary = value or {}
if not isinstance(self._dictionary, dict):
raise BadArgumentError("dictionary must be dict: {}".format(
self._dictionary)) | def dictionary(self, value):
"""Set dictionary"""
self._dictionary = value or {}
if not isinstance(self._dictionary, dict):
raise BadArgumentError("dictionary must be dict: {}".format(
self._dictionary)) | [
"Set",
"dictionary"
] | oriontvv/pyaspeller | python | https://github.com/oriontvv/pyaspeller/blob/9a76d1f1fb00c7eabfa006f8e0f145f764c7a8d6/pyaspeller/speller.py#L165-L170 | [
"def",
"dictionary",
"(",
"self",
",",
"value",
")",
":",
"self",
".",
"_dictionary",
"=",
"value",
"or",
"{",
"}",
"if",
"not",
"isinstance",
"(",
"self",
".",
"_dictionary",
",",
"dict",
")",
":",
"raise",
"BadArgumentError",
"(",
"\"dictionary must be dict: {}\"",
".",
"format",
"(",
"self",
".",
"_dictionary",
")",
")"
] | 9a76d1f1fb00c7eabfa006f8e0f145f764c7a8d6 |
test | YandexSpeller.api_options | current spelling settings
:return: api options as number | pyaspeller/speller.py | def api_options(self):
"""
current spelling settings
:return: api options as number
"""
options = 0
if self._ignore_uppercase:
options |= 1
if self._ignore_digits:
options |= 2
if self._ignore_urls:
options |= 4
if self._find_repeat_words:
options |= 8
if self._ignore_latin:
options |= 16
if self._flag_latin:
options |= 128
if self._by_words:
options |= 256
if self._ignore_capitalization:
options |= 512
if self._ignore_roman_numerals:
options |= 2048
return options | def api_options(self):
"""
current spelling settings
:return: api options as number
"""
options = 0
if self._ignore_uppercase:
options |= 1
if self._ignore_digits:
options |= 2
if self._ignore_urls:
options |= 4
if self._find_repeat_words:
options |= 8
if self._ignore_latin:
options |= 16
if self._flag_latin:
options |= 128
if self._by_words:
options |= 256
if self._ignore_capitalization:
options |= 512
if self._ignore_roman_numerals:
options |= 2048
return options | [
"current",
"spelling",
"settings",
":",
"return",
":",
"api",
"options",
"as",
"number"
] | oriontvv/pyaspeller | python | https://github.com/oriontvv/pyaspeller/blob/9a76d1f1fb00c7eabfa006f8e0f145f764c7a8d6/pyaspeller/speller.py#L328-L352 | [
"def",
"api_options",
"(",
"self",
")",
":",
"options",
"=",
"0",
"if",
"self",
".",
"_ignore_uppercase",
":",
"options",
"|=",
"1",
"if",
"self",
".",
"_ignore_digits",
":",
"options",
"|=",
"2",
"if",
"self",
".",
"_ignore_urls",
":",
"options",
"|=",
"4",
"if",
"self",
".",
"_find_repeat_words",
":",
"options",
"|=",
"8",
"if",
"self",
".",
"_ignore_latin",
":",
"options",
"|=",
"16",
"if",
"self",
".",
"_flag_latin",
":",
"options",
"|=",
"128",
"if",
"self",
".",
"_by_words",
":",
"options",
"|=",
"256",
"if",
"self",
".",
"_ignore_capitalization",
":",
"options",
"|=",
"512",
"if",
"self",
".",
"_ignore_roman_numerals",
":",
"options",
"|=",
"2048",
"return",
"options"
] | 9a76d1f1fb00c7eabfa006f8e0f145f764c7a8d6 |
test | validate | Does basic Metric option validation. | analytics/validation.py | def validate(metric_class):
"""
Does basic Metric option validation.
"""
if not hasattr(metric_class, 'label'):
raise ImproperlyConfigured("No 'label' attribute found for metric %s." % metric_class.__name__)
if not hasattr(metric_class, 'widget'):
raise ImproperlyConfigured("No 'widget' attribute found for metric %s." % metric_class.__name__) | def validate(metric_class):
"""
Does basic Metric option validation.
"""
if not hasattr(metric_class, 'label'):
raise ImproperlyConfigured("No 'label' attribute found for metric %s." % metric_class.__name__)
if not hasattr(metric_class, 'widget'):
raise ImproperlyConfigured("No 'widget' attribute found for metric %s." % metric_class.__name__) | [
"Does",
"basic",
"Metric",
"option",
"validation",
"."
] | praekelt/django-analytics | python | https://github.com/praekelt/django-analytics/blob/29c22d03374ccc0ec451650e2c2886d324f6e5c6/analytics/validation.py#L3-L11 | [
"def",
"validate",
"(",
"metric_class",
")",
":",
"if",
"not",
"hasattr",
"(",
"metric_class",
",",
"'label'",
")",
":",
"raise",
"ImproperlyConfigured",
"(",
"\"No 'label' attribute found for metric %s.\"",
"%",
"metric_class",
".",
"__name__",
")",
"if",
"not",
"hasattr",
"(",
"metric_class",
",",
"'widget'",
")",
":",
"raise",
"ImproperlyConfigured",
"(",
"\"No 'widget' attribute found for metric %s.\"",
"%",
"metric_class",
".",
"__name__",
")"
] | 29c22d03374ccc0ec451650e2c2886d324f6e5c6 |
test | get_statistic_by_name | Fetches a statistics based on the given class name. Does a look-up
in the gadgets' registered statistics to find the specified one. | analytics/maintenance.py | def get_statistic_by_name(stat_name):
"""
Fetches a statistics based on the given class name. Does a look-up
in the gadgets' registered statistics to find the specified one.
"""
if stat_name == 'ALL':
return get_statistic_models()
for stat in get_statistic_models():
if stat.__name__ == stat_name:
return stat
raise Exception, _("%(stat)s cannot be found.") % {'stat': stat_name} | def get_statistic_by_name(stat_name):
"""
Fetches a statistics based on the given class name. Does a look-up
in the gadgets' registered statistics to find the specified one.
"""
if stat_name == 'ALL':
return get_statistic_models()
for stat in get_statistic_models():
if stat.__name__ == stat_name:
return stat
raise Exception, _("%(stat)s cannot be found.") % {'stat': stat_name} | [
"Fetches",
"a",
"statistics",
"based",
"on",
"the",
"given",
"class",
"name",
".",
"Does",
"a",
"look",
"-",
"up",
"in",
"the",
"gadgets",
"registered",
"statistics",
"to",
"find",
"the",
"specified",
"one",
"."
] | praekelt/django-analytics | python | https://github.com/praekelt/django-analytics/blob/29c22d03374ccc0ec451650e2c2886d324f6e5c6/analytics/maintenance.py#L24-L37 | [
"def",
"get_statistic_by_name",
"(",
"stat_name",
")",
":",
"if",
"stat_name",
"==",
"'ALL'",
":",
"return",
"get_statistic_models",
"(",
")",
"for",
"stat",
"in",
"get_statistic_models",
"(",
")",
":",
"if",
"stat",
".",
"__name__",
"==",
"stat_name",
":",
"return",
"stat",
"raise",
"Exception",
",",
"_",
"(",
"\"%(stat)s cannot be found.\"",
")",
"%",
"{",
"'stat'",
":",
"stat_name",
"}"
] | 29c22d03374ccc0ec451650e2c2886d324f6e5c6 |
test | calculate_statistics | Calculates all of the metrics associated with the registered gadgets. | analytics/maintenance.py | def calculate_statistics(stat, frequencies):
"""
Calculates all of the metrics associated with the registered gadgets.
"""
stats = ensure_list(stat)
frequencies = ensure_list(frequencies)
for stat in stats:
for f in frequencies:
print "Calculating %s (%s)..." % (stat.__name__, settings.STATISTIC_FREQUENCY_DICT[f])
stat.calculate(f) | def calculate_statistics(stat, frequencies):
"""
Calculates all of the metrics associated with the registered gadgets.
"""
stats = ensure_list(stat)
frequencies = ensure_list(frequencies)
for stat in stats:
for f in frequencies:
print "Calculating %s (%s)..." % (stat.__name__, settings.STATISTIC_FREQUENCY_DICT[f])
stat.calculate(f) | [
"Calculates",
"all",
"of",
"the",
"metrics",
"associated",
"with",
"the",
"registered",
"gadgets",
"."
] | praekelt/django-analytics | python | https://github.com/praekelt/django-analytics/blob/29c22d03374ccc0ec451650e2c2886d324f6e5c6/analytics/maintenance.py#L52-L62 | [
"def",
"calculate_statistics",
"(",
"stat",
",",
"frequencies",
")",
":",
"stats",
"=",
"ensure_list",
"(",
"stat",
")",
"frequencies",
"=",
"ensure_list",
"(",
"frequencies",
")",
"for",
"stat",
"in",
"stats",
":",
"for",
"f",
"in",
"frequencies",
":",
"print",
"\"Calculating %s (%s)...\"",
"%",
"(",
"stat",
".",
"__name__",
",",
"settings",
".",
"STATISTIC_FREQUENCY_DICT",
"[",
"f",
"]",
")",
"stat",
".",
"calculate",
"(",
"f",
")"
] | 29c22d03374ccc0ec451650e2c2886d324f6e5c6 |
test | reset_statistics | Resets the specified statistic's data (deletes it) for the given
frequency/ies. | analytics/maintenance.py | def reset_statistics(stat, frequencies, reset_cumulative, recalculate=False):
"""
Resets the specified statistic's data (deletes it) for the given
frequency/ies.
"""
stats = ensure_list(stat)
frequencies = ensure_list(frequencies)
for s in stats:
for f in frequencies:
if not s.cumulative or reset_cumulative:
print "Resetting %s (%s)..." % (s.__name__, settings.STATISTIC_FREQUENCY_DICT[f])
s.objects.filter(frequency=f).delete()
elif s.cumulative and not reset_cumulative:
print "Skipping %s because it is cumulative." % s.__name__
if recalculate:
print "Recalculating statistics..."
calculate_statistics(stats, frequencies) | def reset_statistics(stat, frequencies, reset_cumulative, recalculate=False):
"""
Resets the specified statistic's data (deletes it) for the given
frequency/ies.
"""
stats = ensure_list(stat)
frequencies = ensure_list(frequencies)
for s in stats:
for f in frequencies:
if not s.cumulative or reset_cumulative:
print "Resetting %s (%s)..." % (s.__name__, settings.STATISTIC_FREQUENCY_DICT[f])
s.objects.filter(frequency=f).delete()
elif s.cumulative and not reset_cumulative:
print "Skipping %s because it is cumulative." % s.__name__
if recalculate:
print "Recalculating statistics..."
calculate_statistics(stats, frequencies) | [
"Resets",
"the",
"specified",
"statistic",
"s",
"data",
"(",
"deletes",
"it",
")",
"for",
"the",
"given",
"frequency",
"/",
"ies",
"."
] | praekelt/django-analytics | python | https://github.com/praekelt/django-analytics/blob/29c22d03374ccc0ec451650e2c2886d324f6e5c6/analytics/maintenance.py#L65-L84 | [
"def",
"reset_statistics",
"(",
"stat",
",",
"frequencies",
",",
"reset_cumulative",
",",
"recalculate",
"=",
"False",
")",
":",
"stats",
"=",
"ensure_list",
"(",
"stat",
")",
"frequencies",
"=",
"ensure_list",
"(",
"frequencies",
")",
"for",
"s",
"in",
"stats",
":",
"for",
"f",
"in",
"frequencies",
":",
"if",
"not",
"s",
".",
"cumulative",
"or",
"reset_cumulative",
":",
"print",
"\"Resetting %s (%s)...\"",
"%",
"(",
"s",
".",
"__name__",
",",
"settings",
".",
"STATISTIC_FREQUENCY_DICT",
"[",
"f",
"]",
")",
"s",
".",
"objects",
".",
"filter",
"(",
"frequency",
"=",
"f",
")",
".",
"delete",
"(",
")",
"elif",
"s",
".",
"cumulative",
"and",
"not",
"reset_cumulative",
":",
"print",
"\"Skipping %s because it is cumulative.\"",
"%",
"s",
".",
"__name__",
"if",
"recalculate",
":",
"print",
"\"Recalculating statistics...\"",
"calculate_statistics",
"(",
"stats",
",",
"frequencies",
")"
] | 29c22d03374ccc0ec451650e2c2886d324f6e5c6 |
test | autodiscover | Auto-discover INSTALLED_APPS gadgets.py modules and fail silently when
not present. This forces an import on them to register any gadgets they
may want. | analytics/__init__.py | def autodiscover():
"""
Auto-discover INSTALLED_APPS gadgets.py modules and fail silently when
not present. This forces an import on them to register any gadgets they
may want.
"""
from django.conf import settings
from django.utils.importlib import import_module
from django.utils.module_loading import module_has_submodule
for app in settings.INSTALLED_APPS:
mod = import_module(app)
# Attempt to import the app's gadgets module.
try:
import_module('%s.gadgets' % app)
except:
# Decide whether to bubble up this error. If the app just
# doesn't have a gadgets module, we can ignore the error
# attempting to import it, otherwise we want it to bubble up.
if module_has_submodule(mod, 'gadgets'):
raise | def autodiscover():
"""
Auto-discover INSTALLED_APPS gadgets.py modules and fail silently when
not present. This forces an import on them to register any gadgets they
may want.
"""
from django.conf import settings
from django.utils.importlib import import_module
from django.utils.module_loading import module_has_submodule
for app in settings.INSTALLED_APPS:
mod = import_module(app)
# Attempt to import the app's gadgets module.
try:
import_module('%s.gadgets' % app)
except:
# Decide whether to bubble up this error. If the app just
# doesn't have a gadgets module, we can ignore the error
# attempting to import it, otherwise we want it to bubble up.
if module_has_submodule(mod, 'gadgets'):
raise | [
"Auto",
"-",
"discover",
"INSTALLED_APPS",
"gadgets",
".",
"py",
"modules",
"and",
"fail",
"silently",
"when",
"not",
"present",
".",
"This",
"forces",
"an",
"import",
"on",
"them",
"to",
"register",
"any",
"gadgets",
"they",
"may",
"want",
"."
] | praekelt/django-analytics | python | https://github.com/praekelt/django-analytics/blob/29c22d03374ccc0ec451650e2c2886d324f6e5c6/analytics/__init__.py#L1-L21 | [
"def",
"autodiscover",
"(",
")",
":",
"from",
"django",
".",
"conf",
"import",
"settings",
"from",
"django",
".",
"utils",
".",
"importlib",
"import",
"import_module",
"from",
"django",
".",
"utils",
".",
"module_loading",
"import",
"module_has_submodule",
"for",
"app",
"in",
"settings",
".",
"INSTALLED_APPS",
":",
"mod",
"=",
"import_module",
"(",
"app",
")",
"# Attempt to import the app's gadgets module.",
"try",
":",
"import_module",
"(",
"'%s.gadgets'",
"%",
"app",
")",
"except",
":",
"# Decide whether to bubble up this error. If the app just",
"# doesn't have a gadgets module, we can ignore the error",
"# attempting to import it, otherwise we want it to bubble up.",
"if",
"module_has_submodule",
"(",
"mod",
",",
"'gadgets'",
")",
":",
"raise"
] | 29c22d03374ccc0ec451650e2c2886d324f6e5c6 |
test | csv_dump | Returns a CSV dump of all of the specified metric's counts
and cumulative counts. | analytics/csv_views.py | def csv_dump(request, uid):
"""
Returns a CSV dump of all of the specified metric's counts
and cumulative counts.
"""
metric = Metric.objects.get(uid=uid)
frequency = request.GET.get('frequency', settings.STATISTIC_FREQUENCY_DAILY)
response = HttpResponse(mimetype='text/csv')
response['Content-Disposition'] = 'attachment; filename=%s%s.csv' % (uid, datetime.datetime.now().strftime("%Y%m%d-%H%M"))
writer = csv.writer(response)
writer.writerow([_('Date/time'), _('Count'), _('Cumulative count')])
for stat in metric.statistics.filter(frequency=frequency).order_by('date_time'):
writer.writerow([stat.date_time.strftime(settings.CSV_DATETIME_FORMAT), stat.count, stat.cumulative_count])
return response | def csv_dump(request, uid):
"""
Returns a CSV dump of all of the specified metric's counts
and cumulative counts.
"""
metric = Metric.objects.get(uid=uid)
frequency = request.GET.get('frequency', settings.STATISTIC_FREQUENCY_DAILY)
response = HttpResponse(mimetype='text/csv')
response['Content-Disposition'] = 'attachment; filename=%s%s.csv' % (uid, datetime.datetime.now().strftime("%Y%m%d-%H%M"))
writer = csv.writer(response)
writer.writerow([_('Date/time'), _('Count'), _('Cumulative count')])
for stat in metric.statistics.filter(frequency=frequency).order_by('date_time'):
writer.writerow([stat.date_time.strftime(settings.CSV_DATETIME_FORMAT), stat.count, stat.cumulative_count])
return response | [
"Returns",
"a",
"CSV",
"dump",
"of",
"all",
"of",
"the",
"specified",
"metric",
"s",
"counts",
"and",
"cumulative",
"counts",
"."
] | praekelt/django-analytics | python | https://github.com/praekelt/django-analytics/blob/29c22d03374ccc0ec451650e2c2886d324f6e5c6/analytics/csv_views.py#L7-L24 | [
"def",
"csv_dump",
"(",
"request",
",",
"uid",
")",
":",
"metric",
"=",
"Metric",
".",
"objects",
".",
"get",
"(",
"uid",
"=",
"uid",
")",
"frequency",
"=",
"request",
".",
"GET",
".",
"get",
"(",
"'frequency'",
",",
"settings",
".",
"STATISTIC_FREQUENCY_DAILY",
")",
"response",
"=",
"HttpResponse",
"(",
"mimetype",
"=",
"'text/csv'",
")",
"response",
"[",
"'Content-Disposition'",
"]",
"=",
"'attachment; filename=%s%s.csv'",
"%",
"(",
"uid",
",",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
".",
"strftime",
"(",
"\"%Y%m%d-%H%M\"",
")",
")",
"writer",
"=",
"csv",
".",
"writer",
"(",
"response",
")",
"writer",
".",
"writerow",
"(",
"[",
"_",
"(",
"'Date/time'",
")",
",",
"_",
"(",
"'Count'",
")",
",",
"_",
"(",
"'Cumulative count'",
")",
"]",
")",
"for",
"stat",
"in",
"metric",
".",
"statistics",
".",
"filter",
"(",
"frequency",
"=",
"frequency",
")",
".",
"order_by",
"(",
"'date_time'",
")",
":",
"writer",
".",
"writerow",
"(",
"[",
"stat",
".",
"date_time",
".",
"strftime",
"(",
"settings",
".",
"CSV_DATETIME_FORMAT",
")",
",",
"stat",
".",
"count",
",",
"stat",
".",
"cumulative_count",
"]",
")",
"return",
"response"
] | 29c22d03374ccc0ec451650e2c2886d324f6e5c6 |
test | Statistic.calculate | Runs the calculator for this type of statistic. | analytics/options.py | def calculate(cls, frequency=settings.STATISTIC_FREQUENCY_DAILY, verbose=settings.STATISTIC_CALCULATION_VERBOSE):
"""
Runs the calculator for this type of statistic.
"""
if verbose:
print _("Calculating statistics for %(class)s...") % {'class': cls.get_label()}
start_datetime = None
end_datetime = None
# get the latest statistic
latest_stat = cls.get_latest(frequency)
# work out today's date, truncated to midnight
today = datetime.strptime(datetime.now().strftime("%Y %m %d"), "%Y %m %d")
now = datetime.now()
# if this statistic only has cumulative stats available
if cls.cumulative:
if frequency == settings.STATISTIC_FREQUENCY_HOURLY:
# truncate to the nearest hour
start_datetime = datetime.strptime(now.strftime("%Y %m %d %H:00:00"), "%Y %m %d %H:%M:%S")
elif frequency == settings.STATISTIC_FREQUENCY_DAILY:
start_datetime = today
elif frequency == settings.STATISTIC_FREQUENCY_WEEKLY:
# truncate today to the start of this week
start_datetime = datetime.strptime(today.strftime("%Y %W 0"), "%Y %W %w")
elif frequency == settings.STATISTIC_FREQUENCY_MONTHLY:
# truncate today to the start of this month
start_datetime = datetime.strptime(today.strftime("%Y %m 1"), "%Y %m %d")
stat, created = cls.objects.get_or_create(date_time=start_datetime, frequency=frequency)
stat.cumulative_count = cls.get_cumulative()
stat.count = (stat.cumulative_count-latest_stat.cumulative_count) if latest_stat else stat.cumulative_count
else:
# get the date/time at which we should start calculating
start_datetime = cls.get_start_datetime() if latest_stat is None else latest_stat.date_time
# truncate the start date/time to the appropriate frequency
if frequency == settings.STATISTIC_FREQUENCY_HOURLY:
start_datetime = datetime.strptime(start_datetime.strftime("%Y %m %d %H:00:00"), "%Y %m %d %H:%M:%S")
end_datetime = start_datetime+timedelta(hours=1)
elif frequency == settings.STATISTIC_FREQUENCY_DAILY:
start_datetime = datetime.strptime(start_datetime.strftime("%Y %m %d"), "%Y %m %d")
end_datetime = start_datetime+timedelta(days=1)
elif frequency == settings.STATISTIC_FREQUENCY_WEEKLY:
# start at the beginning of the week of the latest stat
start_datetime = datetime.strptime(start_datetime.strftime("%Y %W 0"), "%Y %W %w")-timedelta(days=7)
end_datetime = start_datetime+timedelta(days=7)
elif frequency == settings.STATISTIC_FREQUENCY_MONTHLY:
# start at the beginning of the month of the latest stat
start_datetime = datetime.strptime(start_datetime.strftime("%Y %m 1"), "%Y %m %d")
end_datetime = datetime.strptime((start_datetime+timedelta(days=33)).strftime("%Y %m 1"), "%Y %m %d")
# if we're doing the normal count
while start_datetime < now:
count = cls.get_count(start_datetime, end_datetime)
cumulative_count = 0
if isinstance(count, tuple):
cumulative_count = count[1]
count = count[0]
else:
cumulative_count = (latest_stat.cumulative_count+count) if latest_stat else count
stat, created = cls.objects.get_or_create(date_time=start_datetime, frequency=frequency)
stat.count = count
stat.cumulative_count = cumulative_count
stat.save()
latest_stat = stat
# update the dates/time window
start_datetime = end_datetime
if frequency == settings.STATISTIC_FREQUENCY_HOURLY:
end_datetime += timedelta(hours=1)
elif frequency == settings.STATISTIC_FREQUENCY_DAILY:
end_datetime += timedelta(days=1)
elif frequency == settings.STATISTIC_FREQUENCY_WEEKLY:
end_datetime += timedelta(days=7)
elif frequency == settings.STATISTIC_FREQUENCY_MONTHLY:
end_datetime = datetime.strptime((start_datetime+timedelta(days=33)).strftime("%Y %m 1"), "%Y %m %d") | def calculate(cls, frequency=settings.STATISTIC_FREQUENCY_DAILY, verbose=settings.STATISTIC_CALCULATION_VERBOSE):
"""
Runs the calculator for this type of statistic.
"""
if verbose:
print _("Calculating statistics for %(class)s...") % {'class': cls.get_label()}
start_datetime = None
end_datetime = None
# get the latest statistic
latest_stat = cls.get_latest(frequency)
# work out today's date, truncated to midnight
today = datetime.strptime(datetime.now().strftime("%Y %m %d"), "%Y %m %d")
now = datetime.now()
# if this statistic only has cumulative stats available
if cls.cumulative:
if frequency == settings.STATISTIC_FREQUENCY_HOURLY:
# truncate to the nearest hour
start_datetime = datetime.strptime(now.strftime("%Y %m %d %H:00:00"), "%Y %m %d %H:%M:%S")
elif frequency == settings.STATISTIC_FREQUENCY_DAILY:
start_datetime = today
elif frequency == settings.STATISTIC_FREQUENCY_WEEKLY:
# truncate today to the start of this week
start_datetime = datetime.strptime(today.strftime("%Y %W 0"), "%Y %W %w")
elif frequency == settings.STATISTIC_FREQUENCY_MONTHLY:
# truncate today to the start of this month
start_datetime = datetime.strptime(today.strftime("%Y %m 1"), "%Y %m %d")
stat, created = cls.objects.get_or_create(date_time=start_datetime, frequency=frequency)
stat.cumulative_count = cls.get_cumulative()
stat.count = (stat.cumulative_count-latest_stat.cumulative_count) if latest_stat else stat.cumulative_count
else:
# get the date/time at which we should start calculating
start_datetime = cls.get_start_datetime() if latest_stat is None else latest_stat.date_time
# truncate the start date/time to the appropriate frequency
if frequency == settings.STATISTIC_FREQUENCY_HOURLY:
start_datetime = datetime.strptime(start_datetime.strftime("%Y %m %d %H:00:00"), "%Y %m %d %H:%M:%S")
end_datetime = start_datetime+timedelta(hours=1)
elif frequency == settings.STATISTIC_FREQUENCY_DAILY:
start_datetime = datetime.strptime(start_datetime.strftime("%Y %m %d"), "%Y %m %d")
end_datetime = start_datetime+timedelta(days=1)
elif frequency == settings.STATISTIC_FREQUENCY_WEEKLY:
# start at the beginning of the week of the latest stat
start_datetime = datetime.strptime(start_datetime.strftime("%Y %W 0"), "%Y %W %w")-timedelta(days=7)
end_datetime = start_datetime+timedelta(days=7)
elif frequency == settings.STATISTIC_FREQUENCY_MONTHLY:
# start at the beginning of the month of the latest stat
start_datetime = datetime.strptime(start_datetime.strftime("%Y %m 1"), "%Y %m %d")
end_datetime = datetime.strptime((start_datetime+timedelta(days=33)).strftime("%Y %m 1"), "%Y %m %d")
# if we're doing the normal count
while start_datetime < now:
count = cls.get_count(start_datetime, end_datetime)
cumulative_count = 0
if isinstance(count, tuple):
cumulative_count = count[1]
count = count[0]
else:
cumulative_count = (latest_stat.cumulative_count+count) if latest_stat else count
stat, created = cls.objects.get_or_create(date_time=start_datetime, frequency=frequency)
stat.count = count
stat.cumulative_count = cumulative_count
stat.save()
latest_stat = stat
# update the dates/time window
start_datetime = end_datetime
if frequency == settings.STATISTIC_FREQUENCY_HOURLY:
end_datetime += timedelta(hours=1)
elif frequency == settings.STATISTIC_FREQUENCY_DAILY:
end_datetime += timedelta(days=1)
elif frequency == settings.STATISTIC_FREQUENCY_WEEKLY:
end_datetime += timedelta(days=7)
elif frequency == settings.STATISTIC_FREQUENCY_MONTHLY:
end_datetime = datetime.strptime((start_datetime+timedelta(days=33)).strftime("%Y %m 1"), "%Y %m %d") | [
"Runs",
"the",
"calculator",
"for",
"this",
"type",
"of",
"statistic",
"."
] | praekelt/django-analytics | python | https://github.com/praekelt/django-analytics/blob/29c22d03374ccc0ec451650e2c2886d324f6e5c6/analytics/options.py#L54-L133 | [
"def",
"calculate",
"(",
"cls",
",",
"frequency",
"=",
"settings",
".",
"STATISTIC_FREQUENCY_DAILY",
",",
"verbose",
"=",
"settings",
".",
"STATISTIC_CALCULATION_VERBOSE",
")",
":",
"if",
"verbose",
":",
"print",
"_",
"(",
"\"Calculating statistics for %(class)s...\"",
")",
"%",
"{",
"'class'",
":",
"cls",
".",
"get_label",
"(",
")",
"}",
"start_datetime",
"=",
"None",
"end_datetime",
"=",
"None",
"# get the latest statistic",
"latest_stat",
"=",
"cls",
".",
"get_latest",
"(",
"frequency",
")",
"# work out today's date, truncated to midnight",
"today",
"=",
"datetime",
".",
"strptime",
"(",
"datetime",
".",
"now",
"(",
")",
".",
"strftime",
"(",
"\"%Y %m %d\"",
")",
",",
"\"%Y %m %d\"",
")",
"now",
"=",
"datetime",
".",
"now",
"(",
")",
"# if this statistic only has cumulative stats available",
"if",
"cls",
".",
"cumulative",
":",
"if",
"frequency",
"==",
"settings",
".",
"STATISTIC_FREQUENCY_HOURLY",
":",
"# truncate to the nearest hour",
"start_datetime",
"=",
"datetime",
".",
"strptime",
"(",
"now",
".",
"strftime",
"(",
"\"%Y %m %d %H:00:00\"",
")",
",",
"\"%Y %m %d %H:%M:%S\"",
")",
"elif",
"frequency",
"==",
"settings",
".",
"STATISTIC_FREQUENCY_DAILY",
":",
"start_datetime",
"=",
"today",
"elif",
"frequency",
"==",
"settings",
".",
"STATISTIC_FREQUENCY_WEEKLY",
":",
"# truncate today to the start of this week",
"start_datetime",
"=",
"datetime",
".",
"strptime",
"(",
"today",
".",
"strftime",
"(",
"\"%Y %W 0\"",
")",
",",
"\"%Y %W %w\"",
")",
"elif",
"frequency",
"==",
"settings",
".",
"STATISTIC_FREQUENCY_MONTHLY",
":",
"# truncate today to the start of this month",
"start_datetime",
"=",
"datetime",
".",
"strptime",
"(",
"today",
".",
"strftime",
"(",
"\"%Y %m 1\"",
")",
",",
"\"%Y %m %d\"",
")",
"stat",
",",
"created",
"=",
"cls",
".",
"objects",
".",
"get_or_create",
"(",
"date_time",
"=",
"start_datetime",
",",
"frequency",
"=",
"frequency",
")",
"stat",
".",
"cumulative_count",
"=",
"cls",
".",
"get_cumulative",
"(",
")",
"stat",
".",
"count",
"=",
"(",
"stat",
".",
"cumulative_count",
"-",
"latest_stat",
".",
"cumulative_count",
")",
"if",
"latest_stat",
"else",
"stat",
".",
"cumulative_count",
"else",
":",
"# get the date/time at which we should start calculating",
"start_datetime",
"=",
"cls",
".",
"get_start_datetime",
"(",
")",
"if",
"latest_stat",
"is",
"None",
"else",
"latest_stat",
".",
"date_time",
"# truncate the start date/time to the appropriate frequency",
"if",
"frequency",
"==",
"settings",
".",
"STATISTIC_FREQUENCY_HOURLY",
":",
"start_datetime",
"=",
"datetime",
".",
"strptime",
"(",
"start_datetime",
".",
"strftime",
"(",
"\"%Y %m %d %H:00:00\"",
")",
",",
"\"%Y %m %d %H:%M:%S\"",
")",
"end_datetime",
"=",
"start_datetime",
"+",
"timedelta",
"(",
"hours",
"=",
"1",
")",
"elif",
"frequency",
"==",
"settings",
".",
"STATISTIC_FREQUENCY_DAILY",
":",
"start_datetime",
"=",
"datetime",
".",
"strptime",
"(",
"start_datetime",
".",
"strftime",
"(",
"\"%Y %m %d\"",
")",
",",
"\"%Y %m %d\"",
")",
"end_datetime",
"=",
"start_datetime",
"+",
"timedelta",
"(",
"days",
"=",
"1",
")",
"elif",
"frequency",
"==",
"settings",
".",
"STATISTIC_FREQUENCY_WEEKLY",
":",
"# start at the beginning of the week of the latest stat",
"start_datetime",
"=",
"datetime",
".",
"strptime",
"(",
"start_datetime",
".",
"strftime",
"(",
"\"%Y %W 0\"",
")",
",",
"\"%Y %W %w\"",
")",
"-",
"timedelta",
"(",
"days",
"=",
"7",
")",
"end_datetime",
"=",
"start_datetime",
"+",
"timedelta",
"(",
"days",
"=",
"7",
")",
"elif",
"frequency",
"==",
"settings",
".",
"STATISTIC_FREQUENCY_MONTHLY",
":",
"# start at the beginning of the month of the latest stat",
"start_datetime",
"=",
"datetime",
".",
"strptime",
"(",
"start_datetime",
".",
"strftime",
"(",
"\"%Y %m 1\"",
")",
",",
"\"%Y %m %d\"",
")",
"end_datetime",
"=",
"datetime",
".",
"strptime",
"(",
"(",
"start_datetime",
"+",
"timedelta",
"(",
"days",
"=",
"33",
")",
")",
".",
"strftime",
"(",
"\"%Y %m 1\"",
")",
",",
"\"%Y %m %d\"",
")",
"# if we're doing the normal count",
"while",
"start_datetime",
"<",
"now",
":",
"count",
"=",
"cls",
".",
"get_count",
"(",
"start_datetime",
",",
"end_datetime",
")",
"cumulative_count",
"=",
"0",
"if",
"isinstance",
"(",
"count",
",",
"tuple",
")",
":",
"cumulative_count",
"=",
"count",
"[",
"1",
"]",
"count",
"=",
"count",
"[",
"0",
"]",
"else",
":",
"cumulative_count",
"=",
"(",
"latest_stat",
".",
"cumulative_count",
"+",
"count",
")",
"if",
"latest_stat",
"else",
"count",
"stat",
",",
"created",
"=",
"cls",
".",
"objects",
".",
"get_or_create",
"(",
"date_time",
"=",
"start_datetime",
",",
"frequency",
"=",
"frequency",
")",
"stat",
".",
"count",
"=",
"count",
"stat",
".",
"cumulative_count",
"=",
"cumulative_count",
"stat",
".",
"save",
"(",
")",
"latest_stat",
"=",
"stat",
"# update the dates/time window",
"start_datetime",
"=",
"end_datetime",
"if",
"frequency",
"==",
"settings",
".",
"STATISTIC_FREQUENCY_HOURLY",
":",
"end_datetime",
"+=",
"timedelta",
"(",
"hours",
"=",
"1",
")",
"elif",
"frequency",
"==",
"settings",
".",
"STATISTIC_FREQUENCY_DAILY",
":",
"end_datetime",
"+=",
"timedelta",
"(",
"days",
"=",
"1",
")",
"elif",
"frequency",
"==",
"settings",
".",
"STATISTIC_FREQUENCY_WEEKLY",
":",
"end_datetime",
"+=",
"timedelta",
"(",
"days",
"=",
"7",
")",
"elif",
"frequency",
"==",
"settings",
".",
"STATISTIC_FREQUENCY_MONTHLY",
":",
"end_datetime",
"=",
"datetime",
".",
"strptime",
"(",
"(",
"start_datetime",
"+",
"timedelta",
"(",
"days",
"=",
"33",
")",
")",
".",
"strftime",
"(",
"\"%Y %m 1\"",
")",
",",
"\"%Y %m %d\"",
")"
] | 29c22d03374ccc0ec451650e2c2886d324f6e5c6 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.