desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Make a subview of a parent view for a given subscript key.'
| def __init__(self, parent, key):
| self.parent = parent
self.key = key
if isinstance(self.parent, RootView):
self.name = ''
else:
self.name = self.parent.name
if (not isinstance(self.key, int)):
self.name += '.'
if isinstance(self.key, int):
self.name += u'#{0}'.format(self.key)
elif is... |
'If a list has less than 4 items, represent it in inline style
(i.e. comma separated, within square brackets).'
| def represent_list(self, data):
| node = super(Dumper, self).represent_list(data)
length = len(data)
if ((self.default_flow_style is None) and (length < 4)):
node.flow_style = True
elif (self.default_flow_style is None):
node.flow_style = False
return node
|
'Represent bool as \'yes\' or \'no\' instead of \'true\' or \'false\'.'
| def represent_bool(self, data):
| if data:
value = u'yes'
else:
value = u'no'
return self.represent_scalar('tag:yaml.org,2002:bool', value)
|
'Represent a None value with nothing instead of \'none\'.'
| def represent_none(self, data):
| return self.represent_scalar('tag:yaml.org,2002:null', '')
|
'Create a configuration object by reading the
automatically-discovered config files for the application for a
given name. If `modname` is specified, it should be the import
name of a module whose package will be searched for a default
config file. (Otherwise, no defaults are used.) Pass `False` for
`read` to disable au... | def __init__(self, appname, modname=None, read=True):
| super(Configuration, self).__init__([])
self.appname = appname
self.modname = modname
self._env_var = '{0}DIR'.format(self.appname.upper())
if read:
self.read()
|
'Points to the location of the user configuration.
The file may not exist.'
| def user_config_path(self):
| return os.path.join(self.config_dir(), CONFIG_FILENAME)
|
'Add the configuration options from the YAML file in the
user\'s configuration directory (given by `config_dir`) if it
exists.'
| def _add_user_source(self):
| filename = self.user_config_path()
if os.path.isfile(filename):
self.add(ConfigSource((load_yaml(filename) or {}), filename))
|
'Add the package\'s default configuration settings. This looks
for a YAML file located inside the package for the module
`modname` if it was given.'
| def _add_default_source(self):
| if self.modname:
pkg_path = _package_path(self.modname)
if pkg_path:
filename = os.path.join(pkg_path, DEFAULT_FILENAME)
if os.path.isfile(filename):
self.add(ConfigSource(load_yaml(filename), filename, True))
|
'Find and read the files for this configuration and set them
as the sources for this configuration. To disable either
discovered user configuration files or the in-package defaults,
set `user` or `defaults` to `False`.'
| def read(self, user=True, defaults=True):
| if user:
self._add_user_source()
if defaults:
self._add_default_source()
|
'Get the path to the user configuration directory. The
directory is guaranteed to exist as a postcondition (one may be
created if none exist).
If the application\'s ``...DIR`` environment variable is set, it
is used as the configuration directory. Otherwise,
platform-specific standard configuration locations are search... | def config_dir(self):
| if (self._env_var in os.environ):
appdir = os.environ[self._env_var]
appdir = os.path.abspath(os.path.expanduser(appdir))
if os.path.isfile(appdir):
raise ConfigError(u'{0} must be a directory'.format(self._env_var))
else:
for confdir in config_dirs():
... |
'Parses the file as YAML and inserts it into the configuration
sources with highest priority.'
| def set_file(self, filename):
| filename = os.path.abspath(filename)
self.set(ConfigSource(load_yaml(filename), filename))
|
'Dump the Configuration object to a YAML file.
The order of the keys is determined from the default
configuration file. All keys not in the default configuration
will be appended to the end of the file.
:param filename: The file to dump the configuration to, or None
if the YAML string should be returned instead
:type ... | def dump(self, full=True, redact=False):
| if full:
out_dict = self.flatten(redact=redact)
else:
sources = [s for s in self.sources if (not s.default)]
temp_root = RootView(sources)
temp_root.redactions = self.redactions
out_dict = temp_root.flatten(redact=redact)
yaml_out = yaml.dump(out_dict, Dumper=Dumper, ... |
'Remove all sources from this configuration.'
| def clear(self):
| super(LazyConfig, self).clear()
self._lazy_suffix = []
self._lazy_prefix = []
|
'Create a template with a given default value.
If `default` is the sentinel `REQUIRED` (as it is by default),
then an error will be raised when a value is missing. Otherwise,
missing values will instead return `default`.'
| def __init__(self, default=REQUIRED):
| self.default = default
|
'Invoking a template on a view gets the view\'s value according
to the template.'
| def __call__(self, view):
| return self.value(view, self)
|
'Get the value for a `ConfigView`.
May raise a `NotFoundError` if the value is missing (and the
template requires it) or a `ConfigValueError` for invalid values.'
| def value(self, view, template=None):
| if view.exists():
(value, _) = view.first()
return self.convert(value, view)
elif (self.default is REQUIRED):
raise NotFoundError(u'{0} not found'.format(view.name))
else:
return self.default
|
'Convert the YAML-deserialized value to a value of the desired
type.
Subclasses should override this to provide useful conversions.
May raise a `ConfigValueError` when the configuration is wrong.'
| def convert(self, value, view):
| return value
|
'Raise an exception indicating that a value cannot be
accepted.
`type_error` indicates whether the error is due to a type
mismatch rather than a malformed value. In this case, a more
specific exception is raised.'
| def fail(self, message, view, type_error=False):
| exc_class = (ConfigTypeError if type_error else ConfigValueError)
raise exc_class(u'{0}: {1}'.format(view.name, message))
|
'Check that the value is an integer. Floats are rounded.'
| def convert(self, value, view):
| if isinstance(value, int):
return value
elif isinstance(value, float):
return int(value)
else:
self.fail(u'must be a number', view, True)
|
'Check that the value is an int or a float.'
| def convert(self, value, view):
| if isinstance(value, NUMERIC_TYPES):
return value
else:
self.fail(u'must be numeric, not {0}'.format(type(value).__name__), view, True)
|
'Create a template according to a dict (mapping). The
mapping\'s values should themselves either be Types or
convertible to Types.'
| def __init__(self, mapping):
| subtemplates = {}
for (key, typ) in mapping.items():
subtemplates[key] = as_template(typ)
self.subtemplates = subtemplates
|
'Get a dict with the same keys as the template and values
validated according to the value types.'
| def value(self, view, template=None):
| out = AttrDict()
for (key, typ) in self.subtemplates.items():
out[key] = typ.value(view[key], self)
return out
|
'Create a template with the added optional `pattern` argument,
a regular expression string that the value should match.'
| def __init__(self, default=REQUIRED, pattern=None):
| super(String, self).__init__(default)
self.pattern = pattern
if pattern:
self.regex = re.compile(pattern)
|
'Check that the value is a string and matches the pattern.'
| def convert(self, value, view):
| if isinstance(value, BASESTRING):
if (self.pattern and (not self.regex.match(value))):
self.fail(u'must match the pattern {0}'.format(self.pattern), view)
return value
else:
self.fail(u'must be a string', view, True)
|
'Create a template that validates any of the values from the
iterable `choices`.
If `choices` is a map, then the corresponding value is emitted.
Otherwise, the value itself is emitted.'
| def __init__(self, choices):
| self.choices = choices
|
'Ensure that the value is among the choices (and remap if the
choices are a mapping).'
| def convert(self, value, view):
| if (value not in self.choices):
self.fail(u'must be one of {0}, not {1}'.format(repr(list(self.choices)), repr(value)), view)
if isinstance(self.choices, collections.Mapping):
return self.choices[value]
else:
return value
|
'Ensure that the value follows at least one template.'
| def convert(self, value, view):
| is_mapping = isinstance(self.template, MappingTemplate)
for candidate in self.allowed:
try:
if is_mapping:
if (isinstance(candidate, Filename) and candidate.relative_to):
next_template = candidate.template_with_relatives(view, self.template)
... |
'Create a new template.
`split` indicates whether, when the underlying value is a single
string, it should be split on whitespace. Otherwise, the
resulting value is a list containing a single string.'
| def __init__(self, split=True):
| super(StrSeq, self).__init__()
self.split = split
|
'`relative_to` is the name of a sibling value that is
being validated at the same time.
`in_app_dir` indicates whether the path should be resolved
inside the application\'s config directory (even when the setting
does not come from a file).'
| def __init__(self, default=REQUIRED, cwd=None, relative_to=None, in_app_dir=False):
| super(Filename, self).__init__(default)
self.cwd = cwd
self.relative_to = relative_to
self.in_app_dir = in_app_dir
|
'Create a template that checks that the value is an instance
of `typ`.'
| def __init__(self, typ, default=REQUIRED):
| super(TypeTemplate, self).__init__(default)
self.typ = typ
|
'Create a resizer object with an inferred method.'
| def __init__(self):
| self.method = self._check_method()
log.debug(u'artresizer: method is {0}', self.method)
self.can_compare = self._can_compare()
|
'Manipulate an image file according to the method, returning a
new path. For PIL or IMAGEMAGIC methods, resizes the image to a
temporary file. For WEBPROXY, returns `path_in` unmodified.'
| def resize(self, maxwidth, path_in, path_out=None):
| if self.local:
func = BACKEND_FUNCS[self.method[0]]
return func(maxwidth, path_in, path_out)
else:
return path_in
|
'Modifies an image URL according the method, returning a new
URL. For WEBPROXY, a URL on the proxy server is returned.
Otherwise, the URL is returned unmodified.'
| def proxy_url(self, maxwidth, url):
| if self.local:
return url
else:
return resize_url(url, maxwidth)
|
'A boolean indicating whether the resizing method is performed
locally (i.e., PIL or ImageMagick).'
| @property
def local(self):
| return (self.method[0] in BACKEND_FUNCS)
|
'Return the size of an image file as an int couple (width, height)
in pixels.
Only available locally'
| def get_size(self, path_in):
| if self.local:
func = BACKEND_GET_SIZE[self.method[0]]
return func(path_in)
|
'A boolean indicating whether image comparison is available'
| def _can_compare(self):
| return ((self.method[0] == IMAGEMAGICK) and (self.method[1] > (6, 8, 7)))
|
'Return a tuple indicating an available method and its version.'
| @staticmethod
def _check_method():
| version = get_im_version()
if version:
return (IMAGEMAGICK, version)
version = get_pil_version()
if version:
return (PIL, version)
return (WEBPROXY, 0)
|
'Evaluate the symbol in the environment, returning a Unicode
string.'
| def evaluate(self, env):
| if (self.ident in env.values):
return env.values[self.ident]
else:
return self.original
|
'Compile the variable lookup.'
| def translate(self):
| if six.PY2:
ident = self.ident.encode('utf-8')
else:
ident = self.ident
expr = ex_rvalue((VARIABLE_PREFIX + ident))
return ([expr], set([ident]), set())
|
'Evaluate the function call in the environment, returning a
Unicode string.'
| def evaluate(self, env):
| if (self.ident in env.functions):
arg_vals = [expr.evaluate(env) for expr in self.args]
try:
out = env.functions[self.ident](*arg_vals)
except Exception as exc:
return (u'<%s>' % six.text_type(exc))
return six.text_type(out)
else:
return self.origi... |
'Compile the function call.'
| def translate(self):
| varnames = set()
if six.PY2:
ident = self.ident.encode('utf-8')
else:
ident = self.ident
funcnames = set([ident])
arg_exprs = []
for arg in self.args:
(subexprs, subvars, subfuncs) = arg.translate()
varnames.update(subvars)
funcnames.update(subfuncs)
... |
'Evaluate the entire expression in the environment, returning
a Unicode string.'
| def evaluate(self, env):
| out = []
for part in self.parts:
if isinstance(part, six.string_types):
out.append(part)
else:
out.append(part.evaluate(env))
return u''.join(map(six.text_type, out))
|
'Compile the expression to a list of Python AST expressions, a
set of variable names used, and a set of function names.'
| def translate(self):
| expressions = []
varnames = set()
funcnames = set()
for part in self.parts:
if isinstance(part, six.string_types):
expressions.append(ex_literal(part))
else:
(e, v, f) = part.translate()
expressions.extend(e)
varnames.update(v)
... |
'Create a new parser.
:param in_arguments: boolean that indicates the parser is to be
used for parsing function arguments, ie. considering commas
(`ARG_SEP`) a special character'
| def __init__(self, string, in_argument=False):
| self.string = string
self.in_argument = in_argument
self.pos = 0
self.parts = []
|
'Parse a template expression starting at ``pos``. Resulting
components (Unicode strings, Symbols, and Calls) are added to
the ``parts`` field, a list. The ``pos`` field is updated to be
the next character after the expression.'
| def parse_expression(self):
| extra_special_chars = ()
special_char_re = self.special_char_re
if self.in_argument:
extra_special_chars = (ARG_SEP,)
special_char_re = re.compile(('[%s]|\\Z' % u''.join((re.escape(c) for c in (self.special_chars + extra_special_chars)))))
text_parts = []
while (self.pos < len(self.s... |
'Parse a variable reference (like ``$foo`` or ``${foo}``)
starting at ``pos``. Possibly appends a Symbol object (or,
failing that, text) to the ``parts`` field and updates ``pos``.
The character at ``pos`` must, as a precondition, be ``$``.'
| def parse_symbol(self):
| assert (self.pos < len(self.string))
assert (self.string[self.pos] == SYMBOL_DELIM)
if (self.pos == (len(self.string) - 1)):
self.parts.append(SYMBOL_DELIM)
self.pos += 1
return
next_char = self.string[(self.pos + 1)]
start_pos = self.pos
self.pos += 1
if (next_char =... |
'Parse a function call (like ``%foo{bar,baz}``) starting at
``pos``. Possibly appends a Call object to ``parts`` and update
``pos``. The character at ``pos`` must be ``%``.'
| def parse_call(self):
| assert (self.pos < len(self.string))
assert (self.string[self.pos] == FUNC_DELIM)
start_pos = self.pos
self.pos += 1
ident = self._parse_ident()
if (not ident):
self.parts.append(FUNC_DELIM)
return
if (self.pos >= len(self.string)):
self.parts.append(self.string[start... |
'Parse a list of arguments starting at ``pos``, returning a
list of Expression objects. Does not modify ``parts``. Should
leave ``pos`` pointing to a } character or the end of the
string.'
| def parse_argument_list(self):
| expressions = []
while (self.pos < len(self.string)):
subparser = Parser(self.string[self.pos:], in_argument=True)
subparser.parse_expression()
expressions.append(Expression(subparser.parts))
self.pos += subparser.pos
if ((self.pos >= len(self.string)) or (self.string[sel... |
'Parse an identifier and return it (possibly an empty string).
Updates ``pos``.'
| def _parse_ident(self):
| remainder = self.string[self.pos:]
ident = re.match('\\w*', remainder).group(0)
self.pos += len(ident)
return ident
|
'Like `substitute`, but forces the interpreter (rather than
the compiled version) to be used. The interpreter includes
exception-handling code for missing variables and buggy template
functions but is much slower.'
| def interpret(self, values={}, functions={}):
| return self.expr.evaluate(Environment(values, functions))
|
'Evaluate the template given the values and functions.'
| def substitute(self, values={}, functions={}):
| try:
res = self.compiled(values, functions)
except Exception:
res = self.interpret(values, functions)
return res
|
'Compile the template to a Python function.'
| def translate(self):
| (expressions, varnames, funcnames) = self.expr.translate()
argnames = []
for varname in varnames:
argnames.append((VARIABLE_PREFIX + varname))
for funcname in funcnames:
argnames.append((FUNCTION_PREFIX + funcname))
func = compile_func(argnames, [ast.Return(ast.List(expressions, ast.... |
'Create a basic storage strategy. Parameters:
- `key`: The key on the Mutagen file object used to access the
field\'s data.
- `as_type`: The Python type that the value is stored as
internally (`unicode`, `int`, `bool`, or `bytes`).
- `suffix`: When `as_type` is a string type, append this before
storing the value.
- `fl... | def __init__(self, key, as_type=six.text_type, suffix=None, float_places=2):
| self.key = key
self.as_type = as_type
self.suffix = suffix
self.float_places = float_places
if (self.suffix and (self.as_type is six.text_type) and (not isinstance(self.suffix, six.text_type))):
self.suffix = self.suffix.decode('utf-8')
|
'Get the value for the field using this style.'
| def get(self, mutagen_file):
| return self.deserialize(self.fetch(mutagen_file))
|
'Retrieve the raw value of for this tag from the Mutagen file
object.'
| def fetch(self, mutagen_file):
| try:
return mutagen_file[self.key][0]
except (KeyError, IndexError):
return None
|
'Given a raw value stored on a Mutagen object, decode and
return the represented value.'
| def deserialize(self, mutagen_value):
| if (self.suffix and isinstance(mutagen_value, six.text_type) and mutagen_value.endswith(self.suffix)):
return mutagen_value[:(- len(self.suffix))]
else:
return mutagen_value
|
'Assign the value for the field using this style.'
| def set(self, mutagen_file, value):
| self.store(mutagen_file, self.serialize(value))
|
'Store a serialized value in the Mutagen file object.'
| def store(self, mutagen_file, value):
| mutagen_file[self.key] = [value]
|
'Convert the external Python value to a type that is suitable for
storing in a Mutagen file object.'
| def serialize(self, value):
| if (isinstance(value, float) and (self.as_type is six.text_type)):
value = u'{0:.{1}f}'.format(value, self.float_places)
value = self.as_type(value)
elif (self.as_type is six.text_type):
if isinstance(value, bool):
value = six.text_type(int(bool(value)))
elif isinstan... |
'Remove the tag from the file.'
| def delete(self, mutagen_file):
| if (self.key in mutagen_file):
del mutagen_file[self.key]
|
'Get the first value in the field\'s value list.'
| def get(self, mutagen_file):
| try:
return self.get_list(mutagen_file)[0]
except IndexError:
return None
|
'Get a list of all values for the field using this style.'
| def get_list(self, mutagen_file):
| return [self.deserialize(item) for item in self.fetch(mutagen_file)]
|
'Get the list of raw (serialized) values.'
| def fetch(self, mutagen_file):
| try:
return mutagen_file[self.key]
except KeyError:
return []
|
'Set an individual value as the only value for the field using
this style.'
| def set(self, mutagen_file, value):
| self.set_list(mutagen_file, [value])
|
'Set all values for the field using this style. `values`
should be an iterable.'
| def set_list(self, mutagen_file, values):
| self.store(mutagen_file, [self.serialize(value) for value in values])
|
'Set the list of all raw (serialized) values for this field.'
| def store(self, mutagen_file, values):
| mutagen_file[self.key] = values
|
'Create a new ID3 storage style. `id3_lang` is the value for
the language field of newly created frames.'
| def __init__(self, key, id3_lang=None, **kwargs):
| self.id3_lang = id3_lang
super(MP3StorageStyle, self).__init__(key, **kwargs)
|
'Convert APIC frame into Image.'
| def deserialize(self, apic_frame):
| return Image(data=apic_frame.data, desc=apic_frame.desc, type=apic_frame.type)
|
'Return an APIC frame populated with data from ``image``.'
| def serialize(self, image):
| assert isinstance(image, Image)
frame = mutagen.id3.Frames[self.key]()
frame.data = image.data
frame.mime = image.mime_type
frame.desc = (image.desc or u'')
try:
frame.desc.encode('latin-1')
except UnicodeEncodeError:
frame.encoding = mutagen.id3.Encoding.UTF16
else:
... |
'Turn a Image into a base64 encoded FLAC picture block.'
| def serialize(self, image):
| pic = mutagen.flac.Picture()
pic.data = image.data
pic.type = image.type_index
pic.mime = image.mime_type
pic.desc = (image.desc or u'')
return base64.b64encode(pic.write()).decode('ascii')
|
'``pictures`` is a list of mutagen.flac.Picture instances.'
| def store(self, mutagen_file, pictures):
| mutagen_file.clear_pictures()
for pic in pictures:
mutagen_file.add_picture(pic)
|
'Turn a Image into a mutagen.flac.Picture.'
| def serialize(self, image):
| pic = mutagen.flac.Picture()
pic.data = image.data
pic.type = image.type_index
pic.mime = image.mime_type
pic.desc = (image.desc or u'')
return pic
|
'Remove all images from the file.'
| def delete(self, mutagen_file):
| mutagen_file.clear_pictures()
|
'Remove all images from the file.'
| def delete(self, mutagen_file):
| for cover_tag in self.TAG_NAMES.values():
try:
del mutagen_file[cover_tag]
except KeyError:
pass
|
'Creates a new MediaField.
:param styles: `StorageStyle` instances that describe the strategy
for reading and writing the field in particular
formats. There must be at least one style for
each possible file format.
:param out_type: the type of the value that should be returned when
getting this property.'
| def __init__(self, *styles, **kwargs):
| self.out_type = kwargs.get('out_type', six.text_type)
self._styles = styles
|
'Yields the list of storage styles of this field that can
handle the MediaFile\'s format.'
| def styles(self, mutagen_file):
| for style in self._styles:
if (mutagen_file.__class__.__name__ in style.formats):
(yield style)
|
'Get an appropriate "null" value for this field\'s type. This
is used internally when setting the field to None.'
| def _none_value(self):
| if (self.out_type == int):
return 0
elif (self.out_type == float):
return 0.0
elif (self.out_type == bool):
return False
elif (self.out_type == six.text_type):
return u''
|
'Returns a ``MediaField`` descriptor that gets and sets the
first item.'
| def single_field(self):
| options = {'out_type': self.out_type}
return MediaField(*self._styles, **options)
|
'``date_styles`` is a list of ``StorageStyle``s to store and
retrieve the whole date from. The ``year`` option is an
additional list of fallback styles for the year. The year is
always set on this style, but is only retrieved if the main
storage styles do not return a value.'
| def __init__(self, *date_styles, **kwargs):
| super(DateField, self).__init__(*date_styles)
year_style = kwargs.get('year', None)
if year_style:
self._year_field = MediaField(*year_style)
|
'Get a 3-item sequence representing the date consisting of a
year, month, and day number. Each number is either an integer or
None.'
| def _get_date_tuple(self, mediafile):
| datestring = super(DateField, self).__get__(mediafile, None)
if isinstance(datestring, six.string_types):
datestring = re.sub('[Tt ].*$', '', six.text_type(datestring))
items = re.split('[-/]', six.text_type(datestring))
else:
items = []
items = items[:3]
if (len(items) < ... |
'Set the value of the field given a year, month, and day
number. Each number can be an integer or None to indicate an
unset component.'
| def _set_date_tuple(self, mediafile, year, month=None, day=None):
| if (year is None):
self.__delete__(mediafile)
return
date = [u'{0:04d}'.format(int(year))]
if month:
date.append(u'{0:02d}'.format(int(month)))
if (month and day):
date.append(u'{0:02d}'.format(int(day)))
date = map(six.text_type, date)
super(DateField, self).__se... |
'Constructs a new `MediaFile` reflecting the file at path. May
throw `UnreadableFileError`.
By default, MP3 files are saved with ID3v2.4 tags. You can use
the older ID3v2.3 standard by specifying the `id3v23` option.'
| def __init__(self, path, id3v23=False):
| self.path = path
self.mgfile = mutagen_call('open', path, mutagen.File, path)
if (self.mgfile is None):
raise FileTypeError(path)
elif ((type(self.mgfile).__name__ == 'M4A') or (type(self.mgfile).__name__ == 'MP4')):
info = self.mgfile.info
if (info.codec and info.codec.startswit... |
'Write the object\'s tags back to the file. May
throw `UnreadableFileError`.'
| def save(self):
| kwargs = {}
if self.id3v23:
id3 = self.mgfile
if hasattr(id3, 'tags'):
id3 = id3.tags
id3.update_to_v23()
kwargs['v2_version'] = 3
mutagen_call('save', self.path, self.mgfile.save, **kwargs)
|
'Remove the current metadata tag from the file. May
throw `UnreadableFileError`.'
| def delete(self):
| mutagen_call('delete', self.path, self.mgfile.delete)
|
'Get the names of all writable properties that reflect
metadata tags (i.e., those that are instances of
:class:`MediaField`).'
| @classmethod
def fields(cls):
| for (property, descriptor) in cls.__dict__.items():
if isinstance(descriptor, MediaField):
if isinstance(property, bytes):
(yield property.decode('utf8', 'ignore'))
else:
(yield property)
|
'Get a sort key for a field name that determines the order
fields should be written in.
Fields names are kept unchanged, unless they are instances of
:class:`DateItemField`, in which case `year`, `month`, and `day`
are replaced by `date0`, `date1`, and `date2`, respectively, to
make them appear in that order.'
| @classmethod
def _field_sort_name(cls, name):
| if isinstance(cls.__dict__[name], DateItemField):
name = re.sub('year', 'date0', name)
name = re.sub('month', 'date1', name)
name = re.sub('day', 'date2', name)
return name
|
'Get the names of all writable metadata fields, sorted in the
order that they should be written.
This is a lexicographic order, except for instances of
:class:`DateItemField`, which are sorted in year-month-day
order.'
| @classmethod
def sorted_fields(cls):
| for property in sorted(cls.fields(), key=cls._field_sort_name):
(yield property)
|
'Get all metadata fields: the writable ones from
:meth:`fields` and also other audio properties.'
| @classmethod
def readable_fields(cls):
| for property in cls.fields():
(yield property)
for property in ('length', 'samplerate', 'bitdepth', 'bitrate', 'channels', 'format'):
(yield property)
|
'Add a field to store custom tags.
:param name: the name of the property the field is accessed
through. It must not already exist on this class.
:param descriptor: an instance of :class:`MediaField`.'
| @classmethod
def add_field(cls, name, descriptor):
| if (not isinstance(descriptor, MediaField)):
raise ValueError(u'{0} must be an instance of MediaField'.format(descriptor))
if (name in cls.__dict__):
raise ValueError(u'property "{0}" already exists on MediaField'.format(name))
setattr(cls, name, descriptor)
|
'Set all field values from a dictionary.
For any key in `dict` that is also a field to store tags the
method retrieves the corresponding value from `dict` and updates
the `MediaFile`. If a key has the value `None`, the
corresponding property is deleted from the `MediaFile`.'
| def update(self, dict):
| for field in self.sorted_fields():
if (field in dict):
if (dict[field] is None):
delattr(self, field)
else:
setattr(self, field, dict[field])
|
'The duration of the audio in seconds (a float).'
| @property
def length(self):
| return self.mgfile.info.length
|
'The audio\'s sample rate (an int).'
| @property
def samplerate(self):
| if hasattr(self.mgfile.info, 'sample_rate'):
return self.mgfile.info.sample_rate
elif (self.type == 'opus'):
return 48000
return 0
|
'The number of bits per sample in the audio encoding (an int).
Only available for certain file formats (zero where
unavailable).'
| @property
def bitdepth(self):
| if hasattr(self.mgfile.info, 'bits_per_sample'):
return self.mgfile.info.bits_per_sample
return 0
|
'The number of channels in the audio (an int).'
| @property
def channels(self):
| if hasattr(self.mgfile.info, 'channels'):
return self.mgfile.info.channels
return 0
|
'The number of bits per seconds used in the audio coding (an
int). If this is provided explicitly by the compressed file
format, this is a precise reflection of the encoding. Otherwise,
it is estimated from the on-disk file size. In this case, some
imprecision is possible because the file header is incorporated
in the ... | @property
def bitrate(self):
| if (hasattr(self.mgfile.info, 'bitrate') and self.mgfile.info.bitrate):
return self.mgfile.info.bitrate
else:
if (not self.length):
return 0
size = os.path.getsize(self.path)
return int(((size * 8) / self.length))
|
'A string describing the file format/codec.'
| @property
def format(self):
| return TYPES[self.type]
|
'Randomly permute the training roidb.'
| def _shuffle_roidb_inds(self):
| self._perm = np.random.permutation(np.arange(len(self._roidb)))
self._cur = 0
|
'Return the roidb indices for the next minibatch.'
| def _get_next_minibatch_inds(self):
| if ((self._cur + cfg.TRAIN.IMS_PER_BATCH) >= len(self._roidb)):
self._shuffle_roidb_inds()
db_inds = self._perm[self._cur:(self._cur + cfg.TRAIN.IMS_PER_BATCH)]
self._cur += cfg.TRAIN.IMS_PER_BATCH
"\n # sample images with gt objects\n ... |
'Return the blobs to be used for the next minibatch.'
| def _get_next_minibatch(self):
| db_inds = self._get_next_minibatch_inds()
minibatch_db = [self._roidb[i] for i in db_inds]
return get_minibatch(minibatch_db, self._num_classes)
|
'Set the roidb to be used by this layer during training.'
| def set_roidb(self, roidb):
| self._roidb = roidb
self._shuffle_roidb_inds()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.