desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Look up a metadata tag key.
If the file has no tags at all, a KeyError is raised.'
| def __getitem__(self, key):
| if (self.tags is None):
raise KeyError(key)
else:
return self.tags[key]
|
'Set a metadata tag.
If the file has no tags, an appropriate format is added (but
not written until save is called).'
| def __setitem__(self, key, value):
| if (self.tags is None):
self.add_tags()
self.tags[key] = value
|
'Delete a metadata tag key.
If the file has no tags at all, a KeyError is raised.'
| def __delitem__(self, key):
| if (self.tags is None):
raise KeyError(key)
else:
del self.tags[key]
|
'Return a list of keys in the metadata tag.
If the file has no tags at all, an empty list is returned.'
| def keys(self):
| if (self.tags is None):
return []
else:
return self.tags.keys()
|
'delete(filething=None)
Remove tags from a file.
In cases where the tagging format is independent of the file type
(for example `mutagen.id3.ID3`) all traces of the tagging format will
be removed.
In cases where the tag is part of the file type, all tags and
padding will be removed.
The tags attribute will be cleared a... | @loadfile(writable=True)
def delete(self, filething):
| if (self.tags is not None):
return self.tags.delete(filething)
|
'save(filething=None, **kwargs)
Save metadata tags.
Raises:
MutagenError: if saving wasn\'t possible'
| @loadfile(writable=True)
def save(self, filething, **kwargs):
| if (self.tags is not None):
return self.tags.save(filething, **kwargs)
|
'Returns:
text: stream information and comment key=value pairs.'
| def pprint(self):
| stream = ('%s (%s)' % (self.info.pprint(), self.mime[0]))
try:
tags = self.tags.pprint()
except AttributeError:
return stream
else:
return (stream + ((tags and ('\n' + tags)) or ''))
|
'Adds new tags to the file.
Raises:
MutagenError: if tags already exist or adding is not possible.'
| def add_tags(self):
| raise NotImplementedError
|
'A list of mime types (`text`)'
| @property
def mime(self):
| mimes = []
for Kind in type(self).__mro__:
for mime in getattr(Kind, '_mimes', []):
if (mime not in mimes):
mimes.append(mime)
return mimes
|
'Returns a score for how likely the file can be parsed by this type.
Args:
filename (path): a file path
fileobj (fileobj): a file object open in rb mode. Position is
undefined
header (bytes): data of undefined length, starts with the start of
the file.
Returns:
int: negative if definitely not a matching type, otherwise... | @staticmethod
def score(filename, fileobj, header):
| raise NotImplementedError
|
'Returns:
text: Print stream information'
| def pprint(self):
| raise NotImplementedError
|
'Read the chunks data'
| def read(self):
| self.__fileobj.seek(self.data_offset)
return self.__fileobj.read(self.data_size)
|
'Write the chunk data'
| def write(self, data):
| if (len(data) > self.data_size):
raise ValueError
self.__fileobj.seek(self.data_offset)
self.__fileobj.write(data)
|
'Removes the chunk from the file'
| def delete(self):
| delete_bytes(self.__fileobj, self.size, self.offset)
if (self.parent_chunk is not None):
self.parent_chunk._update_size((self.parent_chunk.data_size - self.size))
|
'Update the size of the chunk'
| def _update_size(self, data_size):
| self.__fileobj.seek((self.offset + 4))
self.__fileobj.write(pack('>I', data_size))
if (self.parent_chunk is not None):
size_diff = (self.data_size - data_size)
self.parent_chunk._update_size((self.parent_chunk.data_size - size_diff))
self.data_size = data_size
self.size = (data_size ... |
'Resize the file and update the chunk sizes'
| def resize(self, new_data_size):
| resize_bytes(self.__fileobj, self.data_size, new_data_size, self.data_offset)
self._update_size(new_data_size)
|
'Check if the IFF file contains a specific chunk'
| def __contains__(self, id_):
| assert isinstance(id_, text_type)
if (not is_valid_chunk_id(id_)):
raise KeyError('AIFF key must be four ASCII characters.')
return (id_ in self.__chunks)
|
'Get a chunk from the IFF file'
| def __getitem__(self, id_):
| assert isinstance(id_, text_type)
if (not is_valid_chunk_id(id_)):
raise KeyError('AIFF key must be four ASCII characters.')
try:
return self.__chunks[id_]
except KeyError:
raise KeyError(('%r has no %r chunk' % (self.__fileobj, id_)))
|
'Remove a chunk from the IFF file'
| def __delitem__(self, id_):
| assert isinstance(id_, text_type)
if (not is_valid_chunk_id(id_)):
raise KeyError('AIFF key must be four ASCII characters.')
self.__chunks.pop(id_).delete()
|
'Insert a new chunk at the end of the IFF file'
| def insert_chunk(self, id_):
| assert isinstance(id_, text_type)
if (not is_valid_chunk_id(id_)):
raise KeyError('AIFF key must be four ASCII characters.')
self.__fileobj.seek(self.__next_offset)
self.__fileobj.write(pack('>4si', id_.ljust(4).encode('ascii'), 0))
self.__fileobj.seek(self.__next_offset)
... |
'Raises error'
| @convert_error(IOError, error)
def __init__(self, fileobj):
| iff = IFFFile(fileobj)
try:
common_chunk = iff[u'COMM']
except KeyError as e:
raise error(str(e))
data = common_chunk.read()
if (len(data) < 18):
raise error
info = struct.unpack('>hLh10s', data[:18])
(channels, frame_count, sample_size, sample_rate) = info
self.s... |
'Save ID3v2 data to the AIFF file'
| @convert_error(IOError, error)
@loadfile(writable=True)
def save(self, filething, v2_version=4, v23_sep='/', padding=None):
| fileobj = filething.fileobj
iff_file = IFFFile(fileobj)
if (u'ID3' not in iff_file):
iff_file.insert_chunk(u'ID3')
chunk = iff_file[u'ID3']
try:
data = self._prepare_data(fileobj, chunk.data_offset, chunk.data_size, v2_version, v23_sep, padding)
except ID3Error as e:
rera... |
'Completely removes the ID3 chunk from the AIFF file'
| @loadfile(writable=True)
def delete(self, filething):
| delete(filething)
self.clear()
|
'Add an empty ID3 tag to the file.'
| def add_tags(self):
| if (self.tags is None):
self.tags = _IFFID3()
else:
raise error('an ID3 tag already exists')
|
'Load stream and tag information from a file.'
| @convert_error(IOError, error)
@loadfile()
def load(self, filething, **kwargs):
| fileobj = filething.fileobj
try:
self.tags = _IFFID3(fileobj, **kwargs)
except ID3NoHeaderError:
self.tags = None
except ID3Error as e:
raise error(e)
else:
self.tags.filename = self.filename
fileobj.seek(0, 0)
self.info = AIFFInfo(fileobj)
|
'Save ID3v2 data to the DSF file'
| @convert_error(IOError, error)
@loadfile(writable=True)
def save(self, filething, v2_version=4, v23_sep='/', padding=None):
| fileobj = filething.fileobj
fileobj.seek(0)
dsd_header = DSDChunk(fileobj)
if (dsd_header.offset_metdata_chunk == 0):
fileobj.seek(0, 2)
dsd_header.offset_metdata_chunk = fileobj.tell()
dsd_header.write()
try:
data = self._prepare_data(fileobj, dsd_header.offset_metda... |
'Add a DSF tag block to the file.'
| def add_tags(self):
| if (self.tags is None):
self.tags = _DSFID3()
else:
raise error('an ID3 tag already exists')
|
'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 receive an MP4Tags instance
and the requested key name. The setter also receives the
desired value, which will be a list of strings.
The ... | @classmethod
def RegisterKey(cls, key, getter=None, setter=None, deleter=None, lister=None):
| key = key.lower()
if (getter is not None):
cls.Get[key] = getter
if (setter is not None):
cls.Set[key] = setter
if (deleter is not None):
cls.Delete[key] = deleter
if (lister is not None):
cls.List[key] = lister
|
'Register a text key.
If the key you need to register is a simple one-to-one mapping
of MP4 atom name to EasyMP4Tags key, then you can use this
function::
EasyMP4Tags.RegisterTextKey("artist", "©ART")'
| @classmethod
def RegisterTextKey(cls, key, atomid):
| def getter(tags, key):
return tags[atomid]
def setter(tags, key, value):
tags[atomid] = value
def deleter(tags, key):
del tags[atomid]
cls.RegisterKey(key, getter, setter, deleter)
|
'Register a scalar integer key.'
| @classmethod
def RegisterIntKey(cls, key, atomid, min_value=0, max_value=((2 ** 16) - 1)):
| 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_value)))
tags[atomid] = [clamp(v) for v in map(int, value)]
def deleter(tags, key):
del tags[atomid]
cls.RegisterKey(key, gette... |
'Register a text key.
If the key you need to register is a simple one-to-one mapping
of MP4 freeform atom (----) and name to EasyMP4Tags key, then
you can use this function::
EasyMP4Tags.RegisterFreeformKey(
"musicbrainz_artistid", "MusicBrainz Artist Id")'
| @classmethod
def RegisterFreeformKey(cls, key, name, mean='com.apple.iTunes'):
| atomid = ((('----:' + mean) + ':') + name)
def getter(tags, key):
return [s.decode('utf-8', 'replace') for s in tags[atomid]]
def setter(tags, key, value):
encoded = []
for v in value:
if (not isinstance(v, text_type)):
if PY3:
raise Ty... |
'Print tag key=value pairs.'
| def pprint(self):
| strings = []
for key in sorted(self.keys()):
values = self[key]
for value in values:
strings.append(('%s=%s' % (key, value)))
return '\n'.join(strings)
|
'Parse the given data string or file-like as a metadata block.
The metadata header should not be included.'
| def __init__(self, data):
| if (data is not None):
if (not isinstance(data, StrictFileObject)):
if isinstance(data, bytes):
data = cBytesIO(data)
elif (not hasattr(data, 'read')):
raise TypeError('StreamInfo requires string data or a file-like')
data... |
'Returns the block content + header.
Raises error.'
| @classmethod
def _writeblock(cls, block, is_last=False):
| data = bytearray()
code = ((block.code | 128) if is_last else block.code)
datum = block.write()
size = len(datum)
if (size > cls._MAX_SIZE):
if (block._distrust_size and (block._invalid_overflow_size != (-1))):
size = block._invalid_overflow_size
else:
raise e... |
'Render metadata block as a byte string.'
| @classmethod
def _writeblocks(cls, blocks, available, cont_size, padding_func):
| data = bytearray()
for block in blocks:
if isinstance(block, Padding):
continue
data += cls._writeblock(block)
blockssize = len(data)
padding_block = Padding()
blockssize += len(cls._writeblock(padding_block))
info = PaddingInfo((available - blockssize), cont_size)
... |
'Add a Vorbis comment block to the file.'
| def add_tags(self):
| if (self.tags is None):
self.tags = VCFLACDict()
self.metadata_blocks.append(self.tags)
else:
raise FLACVorbisError('a Vorbis comment already exists')
|
'Remove Vorbis comments from a file.
If no filename is given, the one most recently loaded is used.'
| @loadfile(writable=True)
def delete(self, filething):
| if (self.tags is not None):
self.metadata_blocks.remove(self.tags)
try:
self.save(filething, padding=(lambda x: 0))
finally:
self.metadata_blocks.append(self.tags)
self.tags.clear()
|
'Load file information from a filename.'
| @convert_error(IOError, error)
@loadfile()
def load(self, filething):
| fileobj = filething.fileobj
self.metadata_blocks = []
self.tags = None
self.cuesheet = None
self.seektable = None
fileobj = StrictFileObject(fileobj)
self.__check_header(fileobj, filething.name)
while self.__read_metadata_block(fileobj):
pass
try:
self.metadata_blocks... |
'Add a new picture to the file.
Args:
picture (Picture)'
| def add_picture(self, picture):
| self.metadata_blocks.append(picture)
|
'Delete all pictures from the file.'
| def clear_pictures(self):
| blocks = [b for b in self.metadata_blocks if (b.code != Picture.code)]
self.metadata_blocks = blocks
|
'Returns:
List[`Picture`]: List of embedded pictures'
| @property
def pictures(self):
| return [b for b in self.metadata_blocks if (b.code == Picture.code)]
|
'Save metadata blocks to a file.
Args:
filething (filething)
deleteid3 (bool): delete id3 tags while at it
padding (PaddingFunction)
If no filename is given, the one most recently loaded is used.'
| @convert_error(IOError, error)
@loadfile(writable=True)
def save(self, filething, deleteid3=False, padding=None):
| f = StrictFileObject(filething.fileobj)
header = self.__check_header(f, filething.name)
audio_offset = self.__find_audio_offset(f)
available = (audio_offset - header)
if (deleteid3 and (header > 4)):
available += (header - 4)
header = 4
content_size = (get_size(f) - audio_offset)... |
'Returns the offset of the flac block start
(skipping id3 tags if found). The passed fileobj will be advanced to
that offset as well.'
| def __check_header(self, fileobj, name):
| size = 4
header = fileobj.read(4)
if (header != 'fLaC'):
size = None
if (header[:3] == 'ID3'):
size = (14 + BitPaddedInt(fileobj.read(6)[2:]))
fileobj.seek((size - 4))
if (fileobj.read(4) != 'fLaC'):
size = None
if (size is None):
... |
'Update all parent atoms with the new size.'
| def __update_parents(self, fileobj, path, delta):
| if (delta == 0):
return
for atom in path:
fileobj.seek(atom.offset)
size = cdata.uint_be(fileobj.read(4))
if (size == 1):
size = cdata.ulonglong_be(fileobj.read(12)[4:])
fileobj.seek((atom.offset + 8))
fileobj.write(cdata.to_ulonglong_be((size ... |
'Update offset table in the specified atom.'
| def __update_offset_table(self, fileobj, fmt, atom, delta, offset):
| 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]))
offsets = struct.unpack(fmt, data[4:])
offsets = [(o + (0, delta)[(offset < o)]) for o in offsets]
fileobj.seek((atom.offset ... |
'Update offset tables in all \'stco\' and \'co64\' atoms.'
| def __update_offsets(self, fileobj, atoms, delta, offset):
| if (delta == 0):
return
moov = atoms['moov']
for atom in moov.findall('stco', True):
self.__update_offset_table(fileobj, '>%dI', atom, delta, offset)
for atom in moov.findall('co64', True):
self.__update_offset_table(fileobj, '>%dQ', atom, delta, offset)
try:
for atom... |
'Remove the metadata from the given filename.'
| def delete(self, filename):
| self._failed_atoms.clear()
self.clear()
self.save(filename, padding=(lambda x: 0))
|
'Sets channels, bits_per_sample, sample_rate and optionally bitrate.
Can raise MP4StreamInfoError.'
| def _parse_stsd(self, atom, fileobj):
| assert (atom.name == 'stsd')
(ok, data) = atom.read(fileobj)
if (not ok):
raise MP4StreamInfoError('Invalid stsd')
try:
(version, flags, data) = parse_full_atom(data)
except ValueError as e:
raise MP4StreamInfoError(e)
if (version != 0):
raise MP4StreamInfoErro... |
'save(filething=None, padding=None)'
| def save(self, *args, **kwargs):
| super(MP4, self).save(*args, **kwargs)
|
'May raise AtomError'
| @convert_error(IOError, AtomError)
def __init__(self, fileobj, level=0):
| self.offset = fileobj.tell()
try:
(self.length, self.name) = struct.unpack('>I4s', fileobj.read(8))
except struct.error:
raise AtomError('truncated data')
self._dataoffset = (self.offset + 8)
if (self.length == 1):
try:
(self.length,) = struct.unpack('>Q', file... |
'Return if all data could be read and the atom payload'
| def read(self, fileobj):
| fileobj.seek(self._dataoffset, 0)
data = fileobj.read(self.datalength)
return ((len(data) == self.datalength), data)
|
'Render raw atom data.'
| @staticmethod
def render(name, data):
| size = (len(data) + 8)
if (size <= 4294967295):
return (struct.pack('>I4s', size, name) + data)
else:
return (struct.pack('>I4sQ', 1, name, (size + 8)) + data)
|
'Recursively find all child atoms by specified name.'
| def findall(self, name, recursive=False):
| if (self.children is not None):
for child in self.children:
if (child.name == name):
(yield child)
if recursive:
for atom in child.findall(name, True):
(yield atom)
|
'Look up a child atom, potentially recursively.
e.g. atom[\'udta\', \'meta\'] => <Atom name=\'meta\' ...>'
| def __getitem__(self, remaining):
| if (not remaining):
return self
elif (self.children is None):
raise KeyError(('%r is not a container' % self.name))
for child in self.children:
if (child.name == remaining[0]):
return child[remaining[1:]]
else:
raise KeyError(('%r not found' ... |
'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.'
| def path(self, *names):
| path = [self]
for name in names:
path.append(path[(-1)][(name,)])
return path[1:]
|
'Look up a child atom.
\'names\' may be a list of atoms ([\'moov\', \'udta\']) or a string
specifying the complete path (\'moov.udta\').'
| def __getitem__(self, names):
| if PY2:
if isinstance(names, basestring):
names = names.split('.')
elif isinstance(names, bytes):
names = names.split('.')
for child in self.atoms:
if (child.name == names[0]):
return child[names[1:]]
else:
raise KeyError(('%r not found' % na... |
'May raise ValueError'
| @classmethod
def _parse_desc_length_file(cls, fileobj):
| 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 & 127))
if (not (b >> 7)):
break
else:
raise ValueError('invalid descriptor length')
... |
'Returns a parsed instance of the called type.
The file position is right after the descriptor after this returns.
Raises DescriptorError'
| @classmethod
def parse(cls, fileobj):
| try:
length = cls._parse_desc_length_file(fileobj)
except ValueError as e:
raise DescriptorError(e)
pos = fileobj.tell()
instance = cls(fileobj, length)
left = (length - (fileobj.tell() - pos))
if (left < 0):
raise DescriptorError('descriptor parsing read too ... |
'Raises DescriptorError'
| def __init__(self, fileobj, length):
| r = BitReader(fileobj)
try:
self.ES_ID = r.bits(16)
self.streamDependenceFlag = r.bits(1)
self.URL_Flag = r.bits(1)
self.OCRstreamFlag = r.bits(1)
self.streamPriority = r.bits(5)
if self.streamDependenceFlag:
self.dependsOn_ES_ID = r.bits(16)
i... |
'Raises DescriptorError'
| def __init__(self, fileobj, length):
| r = BitReader(fileobj)
try:
self.objectTypeIndication = r.bits(8)
self.streamType = r.bits(6)
self.upStream = r.bits(1)
self.reserved = r.bits(1)
self.bufferSizeDB = r.bits(24)
self.maxBitrate = r.bits(32)
self.avgBitrate = r.bits(32)
if ((self.obj... |
'string'
| @property
def codec_param(self):
| param = (u'.%X' % self.objectTypeIndication)
info = self.decSpecificInfo
if (info is not None):
param += (u'.%d' % info.audioObjectType)
return param
|
'string or None'
| @property
def codec_desc(self):
| info = self.decSpecificInfo
desc = None
if (info is not None):
desc = info.description
return desc
|
'string or None if unknown'
| @property
def description(self):
| name = None
try:
name = self._TYPE_NAMES[self.audioObjectType]
except IndexError:
pass
if (name is None):
return
if (self.sbrPresentFlag == 1):
name += '+SBR'
if (self.psPresentFlag == 1):
name += '+PS'
return text_type(name)
|
'0 means unknown'
| @property
def sample_rate(self):
| if (self.sbrPresentFlag == 1):
return self.extensionSamplingFrequency
elif (self.sbrPresentFlag == 0):
return self.samplingFrequency
else:
aot_can_sbr = (1, 2, 3, 4, 6, 17, 19, 20, 22)
if (self.audioObjectType not in aot_can_sbr):
return self.samplingFrequency
... |
'channel count or 0 for unknown'
| @property
def channels(self):
| if hasattr(self, 'pce_channels'):
return self.pce_channels
conf = getattr(self, 'extensionChannelConfiguration', self.channelConfiguration)
if (conf == 1):
if (self.psPresentFlag == (-1)):
return 0
elif (self.psPresentFlag == 1):
return 2
else:
... |
'Raises BitReaderError'
| def _get_audio_object_type(self, r):
| audioObjectType = r.bits(5)
if (audioObjectType == 31):
audioObjectTypeExt = r.bits(6)
audioObjectType = (32 + audioObjectTypeExt)
return audioObjectType
|
'Raises BitReaderError'
| def _get_sampling_freq(self, r):
| samplingFrequencyIndex = r.bits(4)
if (samplingFrequencyIndex == 15):
samplingFrequency = r.bits(24)
else:
try:
samplingFrequency = self._FREQS[samplingFrequencyIndex]
except IndexError:
samplingFrequency = 0
return samplingFrequency
|
'Raises DescriptorError'
| def __init__(self, fileobj, length):
| r = BitReader(fileobj)
try:
self._parse(r, length)
except BitReaderError as e:
raise DescriptorError(e)
|
'Raises BitReaderError'
| def _parse(self, r, length):
| def bits_left():
return ((length * 8) - r.get_position())
self.audioObjectType = self._get_audio_object_type(r)
self.samplingFrequency = self._get_sampling_freq(r)
self.channelConfiguration = r.bits(4)
self.sbrPresentFlag = (-1)
self.psPresentFlag = (-1)
if (self.audioObjectType in (... |
'Create a new instance'
| def __init__(self):
| self.C = None
self.row_covered = []
self.col_covered = []
self.n = 0
self.Z0_r = 0
self.Z0_c = 0
self.marked = None
self.path = None
|
'**DEPRECATED**
Please use the module function ``make_cost_matrix()``.'
| def make_cost_matrix(profit_matrix, inversion_function):
| import munkres
return munkres.make_cost_matrix(profit_matrix, inversion_function)
|
'Pad a possibly non-square matrix to make it square.
:Parameters:
matrix : list of lists
matrix to pad
pad_value : int
value to use to pad the matrix
:rtype: list of lists
:return: a new, possibly padded, matrix'
| def pad_matrix(self, matrix, pad_value=0):
| max_columns = 0
total_rows = len(matrix)
for row in matrix:
max_columns = max(max_columns, len(row))
total_rows = max(max_columns, total_rows)
new_matrix = []
for row in matrix:
row_len = len(row)
new_row = row[:]
if (total_rows > row_len):
new_row += ... |
'Compute the indexes for the lowest-cost pairings between rows and
columns in the database. Returns a list of (row, column) tuples
that can be used to traverse the matrix.
:Parameters:
cost_matrix : list of lists
The cost matrix. If this cost matrix is not square, it
will be padded with zeros, via a call to ``pad_matri... | def compute(self, cost_matrix):
| self.C = self.pad_matrix(cost_matrix)
self.n = len(self.C)
self.original_length = len(cost_matrix)
self.original_width = len(cost_matrix[0])
self.row_covered = [False for i in range(self.n)]
self.col_covered = [False for i in range(self.n)]
self.Z0_r = 0
self.Z0_c = 0
self.path = sel... |
'Return an exact copy of the supplied matrix'
| def __copy_matrix(self, matrix):
| return copy.deepcopy(matrix)
|
'Create an *n*x*n* matrix, populating it with the specific value.'
| def __make_matrix(self, n, val):
| matrix = []
for i in range(n):
matrix += [[val for j in range(n)]]
return matrix
|
'For each row of the matrix, find the smallest element and
subtract it from every element in its row. Go to Step 2.'
| def __step1(self):
| C = self.C
n = self.n
for i in range(n):
minval = min(self.C[i])
for j in range(n):
self.C[i][j] -= minval
return 2
|
'Find a zero (Z) in the resulting matrix. If there is no starred
zero in its row or column, star Z. Repeat for each element in the
matrix. Go to Step 3.'
| def __step2(self):
| n = self.n
for i in range(n):
for j in range(n):
if ((self.C[i][j] == 0) and (not self.col_covered[j]) and (not self.row_covered[i])):
self.marked[i][j] = 1
self.col_covered[j] = True
self.row_covered[i] = True
self.__clear_covers()
ret... |
'Cover each column containing a starred zero. If K columns are
covered, the starred zeros describe a complete set of unique
assignments. In this case, Go to DONE, otherwise, Go to Step 4.'
| def __step3(self):
| n = self.n
count = 0
for i in range(n):
for j in range(n):
if (self.marked[i][j] == 1):
self.col_covered[j] = True
count += 1
if (count >= n):
step = 7
else:
step = 4
return step
|
'Find a noncovered zero and prime it. If there is no starred zero
in the row containing this primed zero, Go to Step 5. Otherwise,
cover this row and uncover the column containing the starred
zero. Continue in this manner until there are no uncovered zeros
left. Save the smallest uncovered value and Go to Step 6.'
| def __step4(self):
| step = 0
done = False
row = (-1)
col = (-1)
star_col = (-1)
while (not done):
(row, col) = self.__find_a_zero()
if (row < 0):
done = True
step = 6
else:
self.marked[row][col] = 2
star_col = self.__find_star_in_row(row)
... |
'Construct a series of alternating primed and starred zeros as
follows. Let Z0 represent the uncovered primed zero found in Step 4.
Let Z1 denote the starred zero in the column of Z0 (if any).
Let Z2 denote the primed zero in the row of Z1 (there will always
be one). Continue until the series terminates at a primed zer... | def __step5(self):
| count = 0
path = self.path
path[count][0] = self.Z0_r
path[count][1] = self.Z0_c
done = False
while (not done):
row = self.__find_star_in_col(path[count][1])
if (row >= 0):
count += 1
path[count][0] = row
path[count][1] = path[(count - 1)][1]
... |
'Add the value found in Step 4 to every element of each covered
row, and subtract it from every element of each uncovered column.
Return to Step 4 without altering any stars, primes, or covered
lines.'
| def __step6(self):
| minval = self.__find_smallest()
for i in range(self.n):
for j in range(self.n):
if self.row_covered[i]:
self.C[i][j] += minval
if (not self.col_covered[j]):
self.C[i][j] -= minval
return 4
|
'Find the smallest uncovered value in the matrix.'
| def __find_smallest(self):
| minval = sys.maxsize
for i in range(self.n):
for j in range(self.n):
if ((not self.row_covered[i]) and (not self.col_covered[j])):
if (minval > self.C[i][j]):
minval = self.C[i][j]
return minval
|
'Find the first uncovered element with value 0'
| def __find_a_zero(self):
| row = (-1)
col = (-1)
i = 0
n = self.n
done = False
while (not done):
j = 0
while True:
if ((self.C[i][j] == 0) and (not self.row_covered[i]) and (not self.col_covered[j])):
row = i
col = j
done = True
j += 1... |
'Find the first starred element in the specified row. Returns
the column index, or -1 if no starred element was found.'
| def __find_star_in_row(self, row):
| col = (-1)
for j in range(self.n):
if (self.marked[row][j] == 1):
col = j
break
return col
|
'Find the first starred element in the specified row. Returns
the row index, or -1 if no starred element was found.'
| def __find_star_in_col(self, col):
| row = (-1)
for i in range(self.n):
if (self.marked[i][col] == 1):
row = i
break
return row
|
'Find the first prime element in the specified row. Returns
the column index, or -1 if no starred element was found.'
| def __find_prime_in_row(self, row):
| col = (-1)
for j in range(self.n):
if (self.marked[row][j] == 2):
col = j
break
return col
|
'Clear all covered matrix cells'
| def __clear_covers(self):
| for i in range(self.n):
self.row_covered[i] = False
self.col_covered[i] = False
|
'Erase all prime markings'
| def __erase_primes(self):
| for i in range(self.n):
for j in range(self.n):
if (self.marked[i][j] == 2):
self.marked[i][j] = 0
|
'Return the function\'s docstring.'
| def __repr__(self):
| return self.func.__doc__
|
'Support instance methods.'
| def __get__(self, obj, objtype):
| return functools.partial(self.__call__, obj)
|
'(INTERNAL) ctypes parameter conversion method.'
| @staticmethod
def from_param(this):
| if (this is None):
return None
return this._as_parameter_
|
'Register an event notification.
@param eventtype: the desired event type to be notified about.
@param callback: the function to call when the event occurs.
@param args: optional positional arguments for the callback.
@param kwds: optional keyword arguments for the callback.
@return: 0 on success, ENOMEM on error.
@not... | def event_attach(self, eventtype, callback, *args, **kwds):
| if (not isinstance(eventtype, EventType)):
raise VLCException(('%s required: %r' % ('EventType', eventtype)))
if (not hasattr(callback, '__call__')):
raise VLCException(('%s required: %r' % ('callable', callback)))
if (not any(getargspec(callback)[:2])):
raise VLCExceptio... |
'Unregister an event notification.
@param eventtype: the event type notification to be removed.'
| def event_detach(self, eventtype):
| if (not isinstance(eventtype, EventType)):
raise VLCException(('%s required: %r' % ('EventType', eventtype)))
k = eventtype.value
if (k in self._callbacks):
del self._callbacks[k]
libvlc_event_detach(self, k, self._callback_handler, k)
|
'Create a new MediaPlayer instance.
@param uri: an optional URI to play in the player.'
| def media_player_new(self, uri=None):
| p = libvlc_media_player_new(self)
if uri:
p.set_media(self.media_new(uri))
p._instance = self
return p
|
'Create a new MediaListPlayer instance.'
| def media_list_player_new(self):
| p = libvlc_media_list_player_new(self)
p._instance = self
return p
|
'Create a new Media instance.
If mrl contains a colon (:) preceded by more than 1 letter, it
will be treated as a URL. Else, it will be considered as a
local path. If you need more control, directly use
media_new_location/media_new_path methods.
Options can be specified as supplementary string parameters,
but note that... | def media_new(self, mrl, *options):
| if ((':' in mrl) and (mrl.index(':') > 1)):
m = libvlc_media_new_location(self, str_to_bytes(mrl))
else:
m = libvlc_media_new_path(self, str_to_bytes(os.path.normpath(mrl)))
for o in options:
libvlc_media_add_option(m, str_to_bytes(o))
m._instance = self
return m
|
'Create a new MediaList instance.
@param mrls: optional list of MRL strings'
| def media_list_new(self, mrls=None):
| l = libvlc_media_list_new(self)
if mrls:
for m in mrls:
l.add_media(m)
l._instance = self
return l
|
'Enumerate the defined audio output devices.
@return: list of dicts {name:, description:, devices:}'
| def audio_output_enumerate_devices(self):
| r = []
head = libvlc_audio_output_list_get(self)
if head:
i = head
while i:
i = i.contents
d = [{'id': libvlc_audio_output_device_id(self, i.name, d), 'longname': libvlc_audio_output_device_longname(self, i.name, d)} for d in range(libvlc_audio_output_device_count(sel... |
'Returns a list of available audio filters.'
| def audio_filter_list_get(self):
| return module_description_list(libvlc_audio_filter_list_get(self))
|
'Returns a list of available video filters.'
| def video_filter_list_get(self):
| return module_description_list(libvlc_video_filter_list_get(self))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.