_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q36000
BaseIssue.search
train
def search(cls, *, limit=100, page=1, properties=None, return_query=False): """Search for issues based on the provided filters Args: limit (`int`): Number of results to return. Default: 100 page (`int`): Pagination offset for results. Default: 1 properties (`dict`): ...
python
{ "resource": "" }
q36001
RequiredTagsIssue.state_name
train
def state_name(self): """Get a human-readable value of the state Returns: str: Name of the current state """ if self.state == 1: return 'New Issue' elif self.state == 2: return 'Shutdown in 1 week' elif self.state == 3: r...
python
{ "resource": "" }
q36002
copy
train
def copy(src, dst, merge, write_v1=True, excluded_tags=None, verbose=False): """Returns 0 on success""" if excluded_tags is None: excluded_tags = [] try: id3 = mutagen.id3.ID3(src, translate=False) except mutagen.id3.ID3NoHeaderError: print_(u"No ID3 header found in ", src, fil...
python
{ "resource": "" }
q36003
ID3FileType.add_tags
train
def add_tags(self, ID3=None): """Add an empty ID3 tag to the file. Args: ID3 (ID3): An ID3 subclass to use or `None` to use the one that used when loading. A custom tag reader may be used in instead of the default `ID3` object, e.g. an `mutagen.easyid3.EasyI...
python
{ "resource": "" }
q36004
EasyMP4Tags.RegisterKey
train
def RegisterKey(cls, key, getter=None, setter=None, deleter=None, lister=None): """Register a new key mapping. A key mapping is four functions, a getter, setter, deleter, and lister. The key may be either a string or a glob pattern. The getter, deleted, and lister r...
python
{ "resource": "" }
q36005
EasyMP4Tags.RegisterIntKey
train
def RegisterIntKey(cls, key, atomid, min_value=0, max_value=(2 ** 16) - 1): """Register a scalar integer key. """ def getter(tags, key): return list(map(text_type, tags[atomid])) def setter(tags, key, value): clamp = lambda x: int(min(max(min_value, x), max_valu...
python
{ "resource": "" }
q36006
EasyMP4Tags.pprint
train
def pprint(self): """Print tag key=value pairs.""" strings = [] for key in sorted(self.keys()): values = self[key] for value in values: strings.append("%s=%s" % (key, value)) return "\n".join(strings)
python
{ "resource": "" }
q36007
_BitPaddedMixin.has_valid_padding
train
def has_valid_padding(value, bits=7): """Whether the padding bits are all zero""" assert bits <= 8 mask = (((1 << (8 - bits)) - 1) << bits) if isinstance(value, integer_types): while value: if value & mask: return False v...
python
{ "resource": "" }
q36008
_ADTSStream.find_stream
train
def find_stream(cls, fileobj, max_bytes): """Returns a possibly valid _ADTSStream or None. Args: max_bytes (int): maximum bytes to read """ r = BitReader(fileobj) stream = cls(r) if stream.sync(max_bytes): stream.offset = (r.get_position() - 12) ...
python
{ "resource": "" }
q36009
_ADTSStream.sync
train
def sync(self, max_bytes): """Find the next sync. Returns True if found.""" # at least 2 bytes for the sync max_bytes = max(max_bytes, 2) r = self._r r.align() while max_bytes > 0: try: b = r.bytes(1) if b == b"\xff": ...
python
{ "resource": "" }
q36010
_DSFID3.save
train
def save(self, filething=None, v2_version=4, v23_sep='/', padding=None): """Save ID3v2 data to the DSF file""" fileobj = filething.fileobj fileobj.seek(0) dsd_header = DSDChunk(fileobj) if dsd_header.offset_metdata_chunk == 0: # create a new ID3 chunk at the end of ...
python
{ "resource": "" }
q36011
Atom.read
train
def read(self, fileobj): """Return if all data could be read and the atom payload""" fileobj.seek(self._dataoffset, 0) data = fileobj.read(self.datalength) return len(data) == self.datalength, data
python
{ "resource": "" }
q36012
Atom.render
train
def render(name, data): """Render raw atom data.""" # this raises OverflowError if Py_ssize_t can't handle the atom data size = len(data) + 8 if size <= 0xFFFFFFFF: return struct.pack(">I4s", size, name) + data else: return struct.pack(">I4sQ", 1, name, si...
python
{ "resource": "" }
q36013
Atom.findall
train
def findall(self, name, recursive=False): """Recursively find all child atoms by specified name.""" if self.children is not None: for child in self.children: if child.name == name: yield child if recursive: for atom in c...
python
{ "resource": "" }
q36014
Atoms.path
train
def path(self, *names): """Look up and return the complete path of an atom. For example, atoms.path('moov', 'udta', 'meta') will return a list of three atoms, corresponding to the moov, udta, and meta atoms. """ path = [self] for name in names: path....
python
{ "resource": "" }
q36015
ASFValue
train
def ASFValue(value, kind, **kwargs): """Create a tag value of a specific kind. :: ASFValue(u"My Value", UNICODE) :rtype: ASFBaseAttribute :raises TypeError: in case a wrong type was passed :raises ValueError: in case the value can't be be represented as ASFValue. """ try: ...
python
{ "resource": "" }
q36016
iter_text_fixups
train
def iter_text_fixups(data, encoding): """Yields a series of repaired text values for decoding""" yield data if encoding == Encoding.UTF16BE: # wrong termination yield data + b"\x00" elif encoding == Encoding.UTF16: # wrong termination yield data + b"\x00" # utf-1...
python
{ "resource": "" }
q36017
verify_fileobj
train
def verify_fileobj(fileobj, writable=False): """Verifies that the passed fileobj is a file like object which we can use. Args: writable (bool): verify that the file object is writable as well Raises: ValueError: In case the object is not a file object that is readable (or w...
python
{ "resource": "" }
q36018
loadfile
train
def loadfile(method=True, writable=False, create=False): """A decorator for functions taking a `filething` as a first argument. Passes a FileThing instance as the first argument to the wrapped function. Args: method (bool): If the wrapped functions is a method writable (bool): If a filenam...
python
{ "resource": "" }
q36019
convert_error
train
def convert_error(exc_src, exc_dest): """A decorator for reraising exceptions with a different type. Mostly useful for IOError. Args: exc_src (type): The source exception type exc_dest (type): The target exception type. """ def wrap(func): @wraps(func) def wrapper(...
python
{ "resource": "" }
q36020
_openfile
train
def _openfile(instance, filething, filename, fileobj, writable, create): """yields a FileThing Args: filething: Either a file name, a file object or None filename: Either a file name or None fileobj: Either a file object or None writable (bool): if the file should be opened ...
python
{ "resource": "" }
q36021
hashable
train
def hashable(cls): """Makes sure the class is hashable. Needs a working __eq__ and __hash__ and will add a __ne__. """ # py2 assert "__hash__" in cls.__dict__ # py3 assert cls.__dict__["__hash__"] is not None assert "__eq__" in cls.__dict__ cls.__ne__ = lambda self, other: not sel...
python
{ "resource": "" }
q36022
enum
train
def enum(cls): """A decorator for creating an int enum class. Makes the values a subclass of the type and implements repr/str. The new class will be a subclass of int. Args: cls (type): The class to convert to an enum Returns: type: A new class :: @enum class...
python
{ "resource": "" }
q36023
flags
train
def flags(cls): """A decorator for creating an int flags class. Makes the values a subclass of the type and implements repr/str. The new class will be a subclass of int. Args: cls (type): The class to convert to an flags Returns: type: A new class :: @flags c...
python
{ "resource": "" }
q36024
get_size
train
def get_size(fileobj): """Returns the size of the file. The position when passed in will be preserved if no error occurs. Args: fileobj (fileobj) Returns: int: The size of the file Raises: IOError """ old_pos = fileobj.tell() try: fileobj.seek(0, 2) ...
python
{ "resource": "" }
q36025
read_full
train
def read_full(fileobj, size): """Like fileobj.read but raises IOError if not all requested data is returned. If you want to distinguish IOError and the EOS case, better handle the error yourself instead of using this. Args: fileobj (fileobj) size (int): amount of bytes to read ...
python
{ "resource": "" }
q36026
resize_file
train
def resize_file(fobj, diff, BUFFER_SIZE=2 ** 16): """Resize a file by `diff`. New space will be filled with zeros. Args: fobj (fileobj) diff (int): amount of size to change Raises: IOError """ fobj.seek(0, 2) filesize = fobj.tell() if diff < 0: if file...
python
{ "resource": "" }
q36027
insert_bytes
train
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. Args: fo...
python
{ "resource": "" }
q36028
resize_bytes
train
def resize_bytes(fobj, old_size, new_size, offset): """Resize an area in a file adding and deleting at the end of it. Does nothing if no resizing is needed. Args: fobj (fileobj) old_size (int): The area starting at offset new_size (int): The new size of the area offset (int)...
python
{ "resource": "" }
q36029
decode_terminated
train
def decode_terminated(data, encoding, strict=True): """Returns the decoded data until the first NULL terminator and all data after it. Args: data (bytes): data to decode encoding (str): The codec to use strict (bool): If True will raise ValueError in case no NULL is found ...
python
{ "resource": "" }
q36030
BitReader.bits
train
def bits(self, count): """Reads `count` bits and returns an uint, MSB read first. May raise BitReaderError if not enough data could be read or IOError by the underlying file object. """ if count < 0: raise ValueError if count > self._bits: n_byt...
python
{ "resource": "" }
q36031
BitReader.bytes
train
def bytes(self, count): """Returns a bytearray of length `count`. Works unaligned.""" if count < 0: raise ValueError # fast path if self._bits == 0: data = self._fileobj.read(count) if len(data) != count: raise BitReaderError("not eno...
python
{ "resource": "" }
q36032
BitReader.skip
train
def skip(self, count): """Skip `count` bits. Might raise BitReaderError if there wasn't enough data to skip, but might also fail on the next bits() instead. """ if count < 0: raise ValueError if count <= self._bits: self.bits(count) else...
python
{ "resource": "" }
q36033
BitReader.align
train
def align(self): """Align to the next byte, returns the amount of bits skipped""" bits = self._bits self._buffer = 0 self._bits = 0 return bits
python
{ "resource": "" }
q36034
_get_win_argv
train
def _get_win_argv(): """Returns a unicode argv under Windows and standard sys.argv otherwise Returns: List[`fsnative`] """ assert is_win argc = ctypes.c_int() try: argv = winapi.CommandLineToArgvW( winapi.GetCommandLineW(), ctypes.byref(argc)) except WindowsErr...
python
{ "resource": "" }
q36035
_get_userdir
train
def _get_userdir(user=None): """Returns the user dir or None""" if user is not None and not isinstance(user, fsnative): raise TypeError if is_win: if "HOME" in environ: path = environ["HOME"] elif "USERPROFILE" in environ: path = environ["USERPROFILE"] ...
python
{ "resource": "" }
q36036
OggPage.write
train
def write(self): """Return a string encoding of the page header and data. A ValueError is raised if the data is too big to fit in a single page. """ data = [ struct.pack("<4sBBqIIi", b"OggS", self.version, self.__type_flags, self.position, se...
python
{ "resource": "" }
q36037
OggPage.size
train
def size(self): """Total frame size.""" size = 27 # Initial header size for datum in self.packets: quot, rem = divmod(len(datum), 255) size += quot + 1 if not self.complete and rem == 0: # Packet contains a multiple of 255 bytes and is not ...
python
{ "resource": "" }
q36038
OggPage.renumber
train
def renumber(fileobj, serial, start): """Renumber pages belonging to a specified logical stream. fileobj must be opened with mode r+b or w+b. Starting at page number 'start', renumber all pages belonging to logical stream 'serial'. Other pages will be ignored. fileobj must poi...
python
{ "resource": "" }
q36039
OggPage.to_packets
train
def to_packets(pages, strict=False): """Construct a list of packet data from a list of Ogg pages. If strict is true, the first page must start a new packet, and the last page must end the last packet. """ serial = pages[0].serial sequence = pages[0].sequence pac...
python
{ "resource": "" }
q36040
OggPage.from_packets
train
def from_packets(packets, sequence=0, default_size=4096, wiggle_room=2048): """Construct a list of Ogg pages from a list of packet data. The algorithm will generate pages of approximately default_size in size (rounded down to the nearest multiple of 255). However, i...
python
{ "resource": "" }
q36041
OggPage.replace
train
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 ...
python
{ "resource": "" }
q36042
OggPage.find_last
train
def find_last(fileobj, serial, finishing=False): """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 (...
python
{ "resource": "" }
q36043
guid2bytes
train
def guid2bytes(s): """Converts a GUID to the serialized bytes representation""" assert isinstance(s, str) assert len(s) == 36 p = struct.pack return b"".join([ p("<IHH", int(s[:8], 16), int(s[9:13], 16), int(s[14:18], 16)), p(">H", int(s[19:23], 16)), p(">Q", int(s[24:], 16...
python
{ "resource": "" }
q36044
bytes2guid
train
def bytes2guid(s): """Converts a serialized GUID to a text GUID""" assert isinstance(s, bytes) u = struct.unpack v = [] v.extend(u("<IHH", s[:8])) v.extend(u(">HQ", s[8:10] + b"\x00\x00" + s[10:])) return "%08X-%04X-%04X-%04X-%012X" % tuple(v)
python
{ "resource": "" }
q36045
PaddingInfo.get_default_padding
train
def get_default_padding(self): """The default implementation which tries to select a reasonable amount of padding and which might change in future versions. Returns: int: Amount of padding after saving """ high = 1024 * 10 + self.size // 100 # 10 KiB + 1% of traili...
python
{ "resource": "" }
q36046
MP4Tags.__update_offset_table
train
def __update_offset_table(self, fileobj, fmt, atom, delta, offset): """Update offset table in the specified atom.""" if atom.offset > offset: atom.offset += delta fileobj.seek(atom.offset + 12) data = fileobj.read(atom.length - 12) fmt = fmt % cdata.uint_be(data[:4]) ...
python
{ "resource": "" }
q36047
MP4Tags.__update_offsets
train
def __update_offsets(self, fileobj, atoms, delta, offset): """Update offset tables in all 'stco' and 'co64' atoms.""" if delta == 0: return moov = atoms[b"moov"] for atom in moov.findall(b'stco', True): self.__update_offset_table(fileobj, ">%dI", atom, delta, offs...
python
{ "resource": "" }
q36048
MP4Tags.delete
train
def delete(self, filename): """Remove the metadata from the given filename.""" self._failed_atoms.clear() self.clear() self.save(filename, padding=lambda x: 0)
python
{ "resource": "" }
q36049
MP4Info._parse_stsd
train
def _parse_stsd(self, atom, fileobj): """Sets channels, bits_per_sample, sample_rate and optionally bitrate. Can raise MP4StreamInfoError. """ assert atom.name == b"stsd" ok, data = atom.read(fileobj) if not ok: raise MP4StreamInfoError("Invalid stsd") ...
python
{ "resource": "" }
q36050
BaseDescriptor._parse_desc_length_file
train
def _parse_desc_length_file(cls, fileobj): """May raise ValueError""" value = 0 for i in xrange(4): try: b = cdata.uint8(fileobj.read(1)) except cdata.error as e: raise ValueError(e) value = (value << 7) | (b & 0x7f) ...
python
{ "resource": "" }
q36051
BaseDescriptor.parse
train
def parse(cls, fileobj): """Returns a parsed instance of the called type. The file position is right after the descriptor after this returns. Raises DescriptorError """ try: length = cls._parse_desc_length_file(fileobj) except ValueError as e: ra...
python
{ "resource": "" }
q36052
DecoderConfigDescriptor.codec_desc
train
def codec_desc(self): """string or None""" info = self.decSpecificInfo desc = None if info is not None: desc = info.description return desc
python
{ "resource": "" }
q36053
DecoderSpecificInfo.description
train
def description(self): """string or None if unknown""" name = None try: name = self._TYPE_NAMES[self.audioObjectType] except IndexError: pass if name is None: return if self.sbrPresentFlag == 1: name += "+SBR" if se...
python
{ "resource": "" }
q36054
DecoderSpecificInfo.channels
train
def channels(self): """channel count or 0 for unknown""" # from ProgramConfigElement() if hasattr(self, "pce_channels"): return self.pce_channels conf = getattr( self, "extensionChannelConfiguration", self.channelConfiguration) if conf == 1: ...
python
{ "resource": "" }
q36055
_read_track
train
def _read_track(chunk): """Retuns a list of midi events and tempo change events""" TEMPO, MIDI = range(2) # Deviations: The running status should be reset on non midi events, but # some files contain meta events inbetween. # TODO: Offset and time signature are not considered. tempos = [] ...
python
{ "resource": "" }
q36056
_read_midi_length
train
def _read_midi_length(fileobj): """Returns the duration in seconds. Can raise all kind of errors...""" TEMPO, MIDI = range(2) def read_chunk(fileobj): info = fileobj.read(8) if len(info) != 8: raise SMFError("truncated") chunklen = struct.unpack(">I", info[4:])[0] ...
python
{ "resource": "" }
q36057
_swap_bytes
train
def _swap_bytes(data): """swaps bytes for 16 bit, leaves remaining trailing bytes alone""" a, b = data[1::2], data[::2] data = bytearray().join(bytearray(x) for x in zip(a, b)) if len(b) > len(a): data += b[-1:] return bytes(data)
python
{ "resource": "" }
q36058
_codec_can_decode_with_surrogatepass
train
def _codec_can_decode_with_surrogatepass(codec, _cache={}): """Returns if a codec supports the surrogatepass error handler when decoding. Some codecs were broken in Python <3.4 """ try: return _cache[codec] except KeyError: try: u"\ud83d".encode( codec, _...
python
{ "resource": "" }
q36059
_winpath2bytes_py3
train
def _winpath2bytes_py3(text, codec): """Fallback implementation for text including surrogates""" # merge surrogate codepoints if _normalize_codec(codec).startswith("utf-16"): # fast path, utf-16 merges anyway return text.encode(codec, _surrogatepass) return _decode_surrogatepass( ...
python
{ "resource": "" }
q36060
_get_encoding
train
def _get_encoding(): """The encoding used for paths, argv, environ, stdout and stdin""" encoding = sys.getfilesystemencoding() if encoding is None: if is_darwin: encoding = "utf-8" elif is_win: encoding = "mbcs" else: encoding = "ascii" encodi...
python
{ "resource": "" }
q36061
MetadataBlock._writeblock
train
def _writeblock(cls, block, is_last=False): """Returns the block content + header. Raises error. """ data = bytearray() code = (block.code | 128) if is_last else block.code datum = block.write() size = len(datum) if size > cls._MAX_SIZE: if b...
python
{ "resource": "" }
q36062
MetadataBlock._writeblocks
train
def _writeblocks(cls, blocks, available, cont_size, padding_func): """Render metadata block as a byte string.""" # write everything except padding data = bytearray() for block in blocks: if isinstance(block, Padding): continue data += cls._writebl...
python
{ "resource": "" }
q36063
FLAC.add_tags
train
def add_tags(self): """Add a Vorbis comment block to the file.""" if self.tags is None: self.tags = VCFLACDict() self.metadata_blocks.append(self.tags) else: raise FLACVorbisError("a Vorbis comment already exists")
python
{ "resource": "" }
q36064
FLAC.delete
train
def delete(self, filething=None): """Remove Vorbis comments from a file. If no filename is given, the one most recently loaded is used. """ if self.tags is not None: temp_blocks = [ b for b in self.metadata_blocks if b.code != VCFLACDict.code] se...
python
{ "resource": "" }
q36065
FLAC.load
train
def load(self, filething): """Load file information from a filename.""" fileobj = filething.fileobj self.metadata_blocks = [] self.tags = None self.cuesheet = None self.seektable = None fileobj = StrictFileObject(fileobj) self.__check_header(fileobj, fi...
python
{ "resource": "" }
q36066
FLAC.clear_pictures
train
def clear_pictures(self): """Delete all pictures from the file.""" blocks = [b for b in self.metadata_blocks if b.code != Picture.code] self.metadata_blocks = blocks
python
{ "resource": "" }
q36067
FLAC.save
train
def save(self, filething=None, deleteid3=False, padding=None): """Save metadata blocks to a file. Args: filething (filething) deleteid3 (bool): delete id3 tags while at it padding (:obj:`mutagen.PaddingFunction`) If no filename is given, the one most recentl...
python
{ "resource": "" }
q36068
frame_from_fsnative
train
def frame_from_fsnative(arg): """Takes item from argv and returns ascii native str or raises ValueError. """ assert isinstance(arg, fsnative) text = fsn2text(arg, strict=True) if PY2: return text.encode("ascii") else: return text.encode("ascii").decode("ascii")
python
{ "resource": "" }
q36069
value_from_fsnative
train
def value_from_fsnative(arg, escape): """Takes an item from argv and returns a text_type value without surrogate escapes or raises ValueError. """ assert isinstance(arg, fsnative) if escape: bytes_ = fsn2bytes(arg) if PY2: bytes_ = bytes_.decode("string_escape") ...
python
{ "resource": "" }
q36070
skip_id3
train
def skip_id3(fileobj): """Might raise IOError""" # WMP writes multiple id3s, so skip as many as we find while True: idata = fileobj.read(10) try: id3, insize = struct.unpack('>3sxxx4s', idata) except struct.error: id3, insize = b'', 0 insize = BitPadd...
python
{ "resource": "" }
q36071
iter_sync
train
def iter_sync(fileobj, max_read): """Iterate over a fileobj and yields on each mpeg sync. When yielding the fileobj offset is right before the sync and can be changed between iterations without affecting the iteration process. Might raise IOError. """ read = 0 size = 2 last_byte = b""...
python
{ "resource": "" }
q36072
MPEGFrame._parse_vbr_header
train
def _parse_vbr_header(self, fileobj, frame_offset, frame_size, frame_length): """Does not raise""" # Xing xing_offset = XingHeader.get_offset(self) fileobj.seek(frame_offset + xing_offset, 0) try: xing = XingHeader(fileobj) except Xi...
python
{ "resource": "" }
q36073
EasyID3.RegisterTXXXKey
train
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'). """ fram...
python
{ "resource": "" }
q36074
_get_value_type
train
def _get_value_type(kind): """Returns a _APEValue subclass or raises ValueError""" if kind == TEXT: return APETextValue elif kind == BINARY: return APEBinaryValue elif kind == EXTERNAL: return APEExtValue raise ValueError("unknown kind %r" % kind)
python
{ "resource": "" }
q36075
APEValue
train
def APEValue(value, kind): """APEv2 tag value factory. Use this if you need to specify the value's type manually. Binary and text data are automatically detected by APEv2.__setitem__. """ try: type_ = _get_value_type(kind) except ValueError: raise ValueError("kind must be TEXT...
python
{ "resource": "" }
q36076
APEv2.pprint
train
def pprint(self): """Return tag key=value pairs in a human-readable format.""" items = sorted(self.items()) return u"\n".join(u"%s=%s" % (k, v.pprint()) for k, v in items)
python
{ "resource": "" }
q36077
APEv2.__parse_tag
train
def __parse_tag(self, tag, count): """Raises IOError and APEBadItemError""" fileobj = cBytesIO(tag) for i in xrange(count): tag_data = fileobj.read(8) # someone writes wrong item counts if not tag_data: break if len(tag_data) != 8...
python
{ "resource": "" }
q36078
APEv2.save
train
def save(self, filething=None): """Save changes to a file. If no filename is given, the one most recently loaded is used. Tags are always written at the end of the file, and include a header and a footer. """ fileobj = filething.fileobj data = _APEv2Data(fileo...
python
{ "resource": "" }
q36079
ASFTags.as_dict
train
def as_dict(self): """Return a copy of the comment data in a real dict.""" d = {} for key, value in self: d.setdefault(key, []).append(value) return d
python
{ "resource": "" }
q36080
Frame._get_v23_frame
train
def _get_v23_frame(self, **kwargs): """Returns a frame copy which is suitable for writing into a v2.3 tag. kwargs get passed to the specs. """ new_kwargs = {} for checker in self._framespec: name = checker.name value = getattr(self, name) new...
python
{ "resource": "" }
q36081
Frame._readData
train
def _readData(self, id3, data): """Raises ID3JunkFrameError; Returns leftover data""" for reader in self._framespec: if len(data) or reader.handle_nodata: try: value, data = reader.read(id3, self, data) except SpecError as e: ...
python
{ "resource": "" }
q36082
Frame._fromData
train
def _fromData(cls, header, tflags, data): """Construct this ID3 frame from raw string data. Raises: ID3JunkFrameError in case parsing failed NotImplementedError in case parsing isn't implemented ID3EncryptionUnsupportedError in case the frame is encrypted. """ ...
python
{ "resource": "" }
q36083
LAMEHeader.parse_version
train
def parse_version(cls, fileobj): """Returns a version string and True if a LAMEHeader follows. The passed file object will be positioned right before the lame header if True. Raises LAMEError if there is no lame version info. """ # http://wiki.hydrogenaud.io/index.php?t...
python
{ "resource": "" }
q36084
XingHeader.get_encoder_settings
train
def get_encoder_settings(self): """Returns the guessed encoder settings""" if self.lame_header is None: return u"" return self.lame_header.guess_settings(*self.lame_version)
python
{ "resource": "" }
q36085
XingHeader.get_offset
train
def get_offset(cls, info): """Calculate the offset to the Xing header from the start of the MPEG header including sync based on the MPEG header's content. """ assert info.layer == 3 if info.version == 1: if info.mode != 3: return 36 else:...
python
{ "resource": "" }
q36086
get_windows_env_var
train
def get_windows_env_var(key): """Get an env var. Raises: WindowsError """ if not isinstance(key, text_type): raise TypeError("%r not of type %r" % (key, text_type)) buf = ctypes.create_unicode_buffer(32767) stored = winapi.GetEnvironmentVariableW(key, buf, 32767) if store...
python
{ "resource": "" }
q36087
set_windows_env_var
train
def set_windows_env_var(key, value): """Set an env var. Raises: WindowsError """ if not isinstance(key, text_type): raise TypeError("%r not of type %r" % (key, text_type)) if not isinstance(value, text_type): raise TypeError("%r not of type %r" % (value, text_type)) s...
python
{ "resource": "" }
q36088
del_windows_env_var
train
def del_windows_env_var(key): """Delete an env var. Raises: WindowsError """ if not isinstance(key, text_type): raise TypeError("%r not of type %r" % (key, text_type)) status = winapi.SetEnvironmentVariableW(key, None) if status == 0: raise ctypes.WinError()
python
{ "resource": "" }
q36089
read_windows_environ
train
def read_windows_environ(): """Returns a unicode dict of the Windows environment. Raises: WindowsEnvironError """ res = winapi.GetEnvironmentStringsW() if not res: raise ctypes.WinError() res = ctypes.cast(res, ctypes.POINTER(ctypes.c_wchar)) done = [] current = u"" ...
python
{ "resource": "" }
q36090
getenv
train
def getenv(key, value=None): """Like `os.getenv` but returns unicode under Windows + Python 2 Args: key (pathlike): The env var to get value (object): The value to return if the env var does not exist Returns: `fsnative` or `object`: The env var or the passed value if it...
python
{ "resource": "" }
q36091
unsetenv
train
def unsetenv(key): """Like `os.unsetenv` but takes unicode under Windows + Python 2 Args: key (pathlike): The env var to unset """ key = path2fsn(key) if is_win: # python 3 has no unsetenv under Windows -> use our ctypes one as well try: del_windows_env_var(key)...
python
{ "resource": "" }
q36092
putenv
train
def putenv(key, value): """Like `os.putenv` but takes unicode under Windows + Python 2 Args: key (pathlike): The env var to get value (pathlike): The value to set Raises: ValueError """ key = path2fsn(key) value = path2fsn(value) if is_win and PY2: try: ...
python
{ "resource": "" }
q36093
_WavPackHeader.from_fileobj
train
def from_fileobj(cls, fileobj): """A new _WavPackHeader or raises WavPackHeaderError""" header = fileobj.read(32) if len(header) != 32 or not header.startswith(b"wvpk"): raise WavPackHeaderError("not a WavPack header: %r" % header) block_size = cdata.uint_le(header[4:8]) ...
python
{ "resource": "" }
q36094
determine_bpi
train
def determine_bpi(data, frames, EMPTY=b"\x00" * 10): """Takes id3v2.4 frame data and determines if ints or bitpaddedints should be used for parsing. Needed because iTunes used to write normal ints for frame sizes. """ # count number of tags found as BitPaddedInt and how far past o = 0 asbpi...
python
{ "resource": "" }
q36095
read_frames
train
def read_frames(id3, data, frames): """Does not error out""" assert id3.version >= ID3Header._V22 result = [] unsupported_frames = [] if id3.version < ID3Header._V24 and id3.f_unsynch: try: data = unsynch.decode(data) except ValueError: pass if id3.ver...
python
{ "resource": "" }
q36096
ID3Tags.setall
train
def setall(self, key, values): """Delete frames of the given type and add frames in 'values'. Args: key (text): key for frames to delete values (list[Frame]): frames to add """ self.delall(key) for tag in values: self[tag.HashKey] = tag
python
{ "resource": "" }
q36097
ID3Tags._add
train
def _add(self, frame, strict): """Add a frame. Args: frame (Frame): the frame to add strict (bool): if this should raise in case it can't be added and frames shouldn't be merged. """ if not isinstance(frame, Frame): raise TypeError("%...
python
{ "resource": "" }
q36098
ID3Tags.__update_common
train
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 mimes = {"PNG": "image/png", "JPG": "image/jpeg"} for pic in self.getall("APIC"): i...
python
{ "resource": "" }
q36099
ID3Tags.update_to_v24
train
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_...
python
{ "resource": "" }