Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def bind(self, field_name, parent):
assert parent.Meta.model is not None, \
"DRYPermissions is used on '{}' without a model".format(parent.__class__.__name__)
for action in self.actions:
if not self.object_only:
... | [
"\n Check the model attached to the serializer to see what methods are defined and save them.\n "
] |
Please provide a description of the function:def to_representation(self, value):
results = {}
for action, method_names in self.action_method_map.items():
# If using global permissions and the global method exists for this action.
if not self.object_only and method_names.... | [
"\n Calls the developer defined permission methods\n (both global and object) and formats the results into a dictionary.\n "
] |
Please provide a description of the function:def skip_prepare(func):
@wraps(func)
def _wrapper(self, *args, **kwargs):
value = func(self, *args, **kwargs)
return Data(value, should_prepare=False)
return _wrapper | [
"\n A convenience decorator for indicating the raw data should not be prepared.\n "
] |
Please provide a description of the function:def as_view(cls, view_type, *init_args, **init_kwargs):
@wraps(cls)
def _wrapper(request, *args, **kwargs):
# Make a new instance so that no state potentially leaks between
# instances.
inst = cls(*init_args, **ini... | [
"\n Used for hooking up the all endpoints (including custom ones), this\n returns a wrapper function that creates a new instance of the resource\n class & calls the correct view method for it.\n\n :param view_type: Should be one of ``list``, ``detail`` or ``custom``.\n :type view_... |
Please provide a description of the function:def build_error(self, err):
data = {
'error': err.args[0],
}
if self.is_debug():
# Add the traceback.
data['traceback'] = format_traceback(sys.exc_info())
body = self.serializer.serialize(data)
... | [
"\n When an exception is encountered, this generates a JSON error message\n for display to the user.\n\n :param err: The exception seen. The message is exposed to the user, so\n beware of sensitive data leaking.\n :type err: Exception\n\n :returns: A response object\n ... |
Please provide a description of the function:def deserialize(self, method, endpoint, body):
if endpoint == 'list':
return self.deserialize_list(body)
return self.deserialize_detail(body) | [
"\n A convenience method for deserializing the body of a request.\n\n If called on a list-style endpoint, this calls ``deserialize_list``.\n Otherwise, it will call ``deserialize_detail``.\n\n :param method: The HTTP method of the current request\n :type method: string\n\n ... |
Please provide a description of the function:def serialize(self, method, endpoint, data):
if endpoint == 'list':
# Create is a special-case, because you POST it to the collection,
# not to a detail.
if method == 'POST':
return self.serialize_detail(da... | [
"\n A convenience method for serializing data for a response.\n\n If called on a list-style endpoint, this calls ``serialize_list``.\n Otherwise, it will call ``serialize_detail``.\n\n :param method: The HTTP method of the current request\n :type method: string\n\n :param e... |
Please provide a description of the function:def serialize_list(self, data):
if data is None:
return ''
# Check for a ``Data``-like object. We should assume ``True`` (all
# data gets prepared) unless it's explicitly marked as not.
if not getattr(data, 'should_prepar... | [
"\n Given a collection of data (``objects`` or ``dicts``), serializes them.\n\n :param data: The collection of items to serialize\n :type data: list or iterable\n\n :returns: The serialized body\n :rtype: string\n "
] |
Please provide a description of the function:def serialize_detail(self, data):
if data is None:
return ''
# Check for a ``Data``-like object. We should assume ``True`` (all
# data gets prepared) unless it's explicitly marked as not.
if not getattr(data, 'should_prep... | [
"\n Given a single item (``object`` or ``dict``), serializes it.\n\n :param data: The item to serialize\n :type data: object or dict\n\n :returns: The serialized body\n :rtype: string\n "
] |
Please provide a description of the function:def _method(self, *args, **kwargs):
yield self.resource_handler.handle(self.__resource_view_type__, *args, **kwargs) | [
"\n the body of those http-methods used in tornado.web.RequestHandler\n "
] |
Please provide a description of the function:def as_view(cls, view_type, *init_args, **init_kwargs):
global _method
new_cls = type(
cls.__name__ + '_' + _BridgeMixin.__name__ + '_restless',
(_BridgeMixin, cls._request_handler_base_,),
dict(
_... | [
"\n Return a subclass of tornado.web.RequestHandler and\n apply required setting.\n ",
"\n Add required http-methods to the newly created class\n We need to scan through MRO to find what functions users declared,\n and then add corresponding http-methods used by Tornado.\... |
Please provide a description of the function:def handle(self, endpoint, *args, **kwargs):
method = self.request_method()
try:
if not method in self.http_methods.get(endpoint, {}):
raise MethodNotImplemented(
"Unsupported method '{}' for {} endpoi... | [
"\n almost identical to Resource.handle, except\n the way we handle the return value of view_method.\n "
] |
Please provide a description of the function:def prepare(self, data):
result = {}
if not self.fields:
# No fields specified. Serialize everything.
return data
for fieldname, lookup in self.fields.items():
if isinstance(lookup, SubPreparer):
... | [
"\n Handles transforming the provided data into the fielded data that should\n be exposed to the end user.\n\n Uses the ``lookup_data`` method to traverse dotted paths.\n\n Returns a dictionary of data as the response.\n "
] |
Please provide a description of the function:def lookup_data(self, lookup, data):
value = data
parts = lookup.split('.')
if not parts or not parts[0]:
return value
part = parts[0]
remaining_lookup = '.'.join(parts[1:])
if callable(getattr(data, 'ke... | [
"\n Given a lookup string, attempts to descend through nested data looking for\n the value.\n\n Can work with either dictionary-alikes or objects (or any combination of\n those).\n\n Lookups should be a string. If it is a dotted path, it will be split on\n ``.`` & it will t... |
Please provide a description of the function:def prepare(self, data):
result = []
for item in self.get_inner_data(data):
result.append(self.preparer.prepare(item))
return result | [
"\n Handles passing each item in the collection data to the configured\n subpreparer.\n\n Uses a loop and the ``get_inner_data`` method to provide the correct\n item of the data.\n\n Returns a list of data as the response.\n "
] |
Please provide a description of the function:def build_url_name(cls, name, name_prefix=None):
if name_prefix is None:
name_prefix = 'api_{}'.format(
cls.__name__.replace('Resource', '').lower()
)
name_prefix = name_prefix.rstrip('_')
return '_'.j... | [
"\n Given a ``name`` & an optional ``name_prefix``, this generates a name\n for a URL.\n\n :param name: The name for the URL (ex. 'detail')\n :type name: string\n\n :param name_prefix: (Optional) A prefix for the URL's name (for\n resolving). The default is ``None``, wh... |
Please provide a description of the function:def urls(cls, name_prefix=None):
return [
url(r'^$', cls.as_list(), name=cls.build_url_name('list', name_prefix)),
url(r'^(?P<pk>[\w-]+)/$', cls.as_detail(), name=cls.build_url_name('detail', name_prefix)),
] | [
"\n A convenience method for hooking up the URLs.\n\n This automatically adds a list & a detail endpoint to your URLconf.\n\n :param name_prefix: (Optional) A prefix for the URL's name (for\n resolving). The default is ``None``, which will autocreate a prefix\n based on th... |
Please provide a description of the function:def build_endpoint_name(cls, name, endpoint_prefix=None):
if endpoint_prefix is None:
endpoint_prefix = 'api_{}'.format(
cls.__name__.replace('Resource', '').lower()
)
endpoint_prefix = endpoint_prefix.rstrip(... | [
"\n Given a ``name`` & an optional ``endpoint_prefix``, this generates a name\n for a URL.\n\n :param name: The name for the URL (ex. 'detail')\n :type name: string\n\n :param endpoint_prefix: (Optional) A prefix for the URL's name (for\n resolving). The default is ``No... |
Please provide a description of the function:def add_url_rules(cls, app, rule_prefix, endpoint_prefix=None):
methods = ['GET', 'POST', 'PUT', 'DELETE']
app.add_url_rule(
rule_prefix,
endpoint=cls.build_endpoint_name('list', endpoint_prefix),
view_func=cls.as... | [
"\n A convenience method for hooking up the URLs.\n\n This automatically adds a list & a detail endpoint to your routes.\n\n :param app: The ``Flask`` object for your app.\n :type app: ``flask.Flask``\n\n :param rule_prefix: The start of the URL to handle.\n :type rule_pref... |
Please provide a description of the function:def build_routename(cls, name, routename_prefix=None):
if routename_prefix is None:
routename_prefix = 'api_{}'.format(
cls.__name__.replace('Resource', '').lower()
)
routename_prefix = routename_prefix.rstrip... | [
"\n Given a ``name`` & an optional ``routename_prefix``, this generates a\n name for a URL.\n\n :param name: The name for the URL (ex. 'detail')\n :type name: string\n\n :param routename_prefix: (Optional) A prefix for the URL's name (for\n resolving). The default is ``... |
Please provide a description of the function:def add_views(cls, config, rule_prefix, routename_prefix=None):
methods = ('GET', 'POST', 'PUT', 'DELETE')
config.add_route(
cls.build_routename('list', routename_prefix),
rule_prefix
)
config.add_view(
... | [
"\n A convenience method for registering the routes and views in pyramid.\n\n This automatically adds a list and detail endpoint to your routes.\n\n :param config: The pyramid ``Configurator`` object for your app.\n :type config: ``pyramid.config.Configurator``\n\n :param rule_pre... |
Please provide a description of the function:def deserialize(self, body):
try:
if isinstance(body, bytes):
return json.loads(body.decode('utf-8'))
return json.loads(body)
except ValueError:
raise BadRequest('Request body is not valid JSON') | [
"\n The low-level deserialization.\n\n Underpins ``deserialize``, ``deserialize_list`` &\n ``deserialize_detail``.\n\n Has no built-in smarts, simply loads the JSON.\n\n :param body: The body of the current request\n :type body: string\n\n :returns: The deserialized ... |
Please provide a description of the function:def convert_mnist(directory, output_directory, output_filename=None,
dtype=None):
if not output_filename:
if dtype:
output_filename = 'mnist_{}.hdf5'.format(dtype)
else:
output_filename = 'mnist.hdf5'
out... | [
"Converts the MNIST dataset to HDF5.\n\n Converts the MNIST dataset to an HDF5 dataset compatible with\n :class:`fuel.datasets.MNIST`. The converted dataset is\n saved as 'mnist.hdf5'.\n\n This method assumes the existence of the following files:\n `train-images-idx3-ubyte.gz`, `train-labels-idx1-uby... |
Please provide a description of the function:def fill_subparser(subparser):
subparser.add_argument(
"--dtype", help="dtype to save to; by default, images will be " +
"returned in their original unsigned byte format",
choices=('float32', 'float64', 'bool'), type=str, default=None)
re... | [
"Sets up a subparser to convert the MNIST dataset files.\n\n Parameters\n ----------\n subparser : :class:`argparse.ArgumentParser`\n Subparser handling the `mnist` command.\n\n "
] |
Please provide a description of the function:def read_mnist_images(filename, dtype=None):
with gzip.open(filename, 'rb') as f:
magic, number, rows, cols = struct.unpack('>iiii', f.read(16))
if magic != MNIST_IMAGE_MAGIC:
raise ValueError("Wrong magic number reading MNIST image file"... | [
"Read MNIST images from the original ubyte file format.\n\n Parameters\n ----------\n filename : str\n Filename/path from which to read images.\n\n dtype : 'float32', 'float64', or 'bool'\n If unspecified, images will be returned in their original\n unsigned byte format.\n\n Retu... |
Please provide a description of the function:def read_mnist_labels(filename):
with gzip.open(filename, 'rb') as f:
magic, _ = struct.unpack('>ii', f.read(8))
if magic != MNIST_LABEL_MAGIC:
raise ValueError("Wrong magic number reading MNIST label file")
array = numpy.frombuff... | [
"Read MNIST labels from the original ubyte file format.\n\n Parameters\n ----------\n filename : str\n Filename/path from which to read labels.\n\n Returns\n -------\n labels : :class:`~numpy.ndarray`, shape (nlabels, 1)\n A one-dimensional unsigned byte array containing the\n ... |
Please provide a description of the function:def prepare_metadata(devkit_archive, test_groundtruth_path):
# Read what's necessary from the development kit.
synsets, cost_matrix, raw_valid_groundtruth = read_devkit(devkit_archive)
# Mapping to take WordNet IDs to our internal 0-999 encoding.
wnid_m... | [
"Extract dataset metadata required for HDF5 file setup.\n\n Parameters\n ----------\n devkit_archive : str or file-like object\n The filename or file-handle for the gzipped TAR archive\n containing the ILSVRC2010 development kit.\n test_groundtruth_path : str or file-like object\n T... |
Please provide a description of the function:def prepare_hdf5_file(hdf5_file, n_train, n_valid, n_test):
n_total = n_train + n_valid + n_test
splits = create_splits(n_train, n_valid, n_test)
hdf5_file.attrs['split'] = H5PYDataset.create_split_array(splits)
vlen_dtype = h5py.special_dtype(vlen=numpy... | [
"Create datasets within a given HDF5 file.\n\n Parameters\n ----------\n hdf5_file : :class:`h5py.File` instance\n HDF5 file handle to which to write.\n n_train : int\n The number of training set examples.\n n_valid : int\n The number of validation set examples.\n n_test : int... |
Please provide a description of the function:def process_train_set(hdf5_file, train_archive, patch_archive, n_train,
wnid_map, shuffle_seed=None):
producer = partial(train_set_producer, train_archive=train_archive,
patch_archive=patch_archive, wnid_map=wnid_map)
... | [
"Process the ILSVRC2010 training set.\n\n Parameters\n ----------\n hdf5_file : :class:`h5py.File` instance\n HDF5 file handle to which to write. Assumes `features`, `targets`\n and `filenames` already exist and have first dimension larger than\n `n_train`.\n train_archive : str or... |
Please provide a description of the function:def train_set_producer(socket, train_archive, patch_archive, wnid_map):
patch_images = extract_patch_images(patch_archive, 'train')
num_patched = 0
with tar_open(train_archive) as tar:
for inner_tar_info in tar:
with tar_open(tar.extractf... | [
"Load/send images from the training set TAR file or patch images.\n\n Parameters\n ----------\n socket : :class:`zmq.Socket`\n PUSH socket on which to send loaded images.\n train_archive : str or file-like object\n Filename or file handle for the TAR archive of training images.\n patch... |
Please provide a description of the function:def image_consumer(socket, hdf5_file, num_expected, shuffle_seed=None,
offset=0):
with progress_bar('images', maxval=num_expected) as pb:
if shuffle_seed is None:
index_gen = iter(xrange(num_expected))
else:
... | [
"Fill an HDF5 file with incoming images from a socket.\n\n Parameters\n ----------\n socket : :class:`zmq.Socket`\n PULL socket on which to receive images.\n hdf5_file : :class:`h5py.File` instance\n HDF5 file handle to which to write. Assumes `features`, `targets`\n and `filenames`... |
Please provide a description of the function:def process_other_set(hdf5_file, which_set, image_archive, patch_archive,
groundtruth, offset):
producer = partial(other_set_producer, image_archive=image_archive,
patch_archive=patch_archive,
groun... | [
"Process the validation or test set.\n\n Parameters\n ----------\n hdf5_file : :class:`h5py.File` instance\n HDF5 file handle to which to write. Assumes `features`, `targets`\n and `filenames` already exist and have first dimension larger than\n `sum(images_per_class)`.\n which_set ... |
Please provide a description of the function:def other_set_producer(socket, which_set, image_archive, patch_archive,
groundtruth):
patch_images = extract_patch_images(patch_archive, which_set)
num_patched = 0
with tar_open(image_archive) as tar:
filenames = sorted(info.na... | [
"Push image files read from the valid/test set TAR to a socket.\n\n Parameters\n ----------\n socket : :class:`zmq.Socket`\n PUSH socket on which to send images.\n which_set : str\n Which set of images is being processed. One of 'train', 'valid',\n 'test'. Used for extracting the a... |
Please provide a description of the function:def load_from_tar_or_patch(tar, image_filename, patch_images):
patched = True
image_bytes = patch_images.get(os.path.basename(image_filename), None)
if image_bytes is None:
patched = False
try:
image_bytes = tar.extractfile(image_... | [
"Do everything necessary to process an image inside a TAR.\n\n Parameters\n ----------\n tar : `TarFile` instance\n The tar from which to read `image_filename`.\n image_filename : str\n Fully-qualified path inside of `tar` from which to read an\n image file.\n patch_images : dict... |
Please provide a description of the function:def read_devkit(f):
with tar_open(f) as tar:
# Metadata table containing class hierarchy, textual descriptions, etc.
meta_mat = tar.extractfile(DEVKIT_META_PATH)
synsets, cost_matrix = read_metadata_mat_file(meta_mat)
# Raw validatio... | [
"Read relevant information from the development kit archive.\n\n Parameters\n ----------\n f : str or file-like object\n The filename or file-handle for the gzipped TAR archive\n containing the ILSVRC2010 development kit.\n\n Returns\n -------\n synsets : ndarray, 1-dimensional, comp... |
Please provide a description of the function:def extract_patch_images(f, which_set):
if which_set not in ('train', 'valid', 'test'):
raise ValueError('which_set must be one of train, valid, or test')
which_set = 'val' if which_set == 'valid' else which_set
patch_images = {}
with tar_open(f)... | [
"Extracts a dict of the \"patch images\" for ILSVRC2010.\n\n Parameters\n ----------\n f : str or file-like object\n The filename or file-handle to the patch images TAR file.\n which_set : str\n Which set of images to extract. One of 'train', 'valid', 'test'.\n\n Returns\n -------\n ... |
Please provide a description of the function:def convert_cifar10(directory, output_directory,
output_filename='cifar10.hdf5'):
output_path = os.path.join(output_directory, output_filename)
h5file = h5py.File(output_path, mode='w')
input_file = os.path.join(directory, DISTRIBUTION_FI... | [
"Converts the CIFAR-10 dataset to HDF5.\n\n Converts the CIFAR-10 dataset to an HDF5 dataset compatible with\n :class:`fuel.datasets.CIFAR10`. The converted dataset is saved as\n 'cifar10.hdf5'.\n\n It assumes the existence of the following file:\n\n * `cifar-10-python.tar.gz`\n\n Parameters\n ... |
Please provide a description of the function:def check_exists(required_files):
def function_wrapper(f):
@wraps(f)
def wrapped(directory, *args, **kwargs):
missing = []
for filename in required_files:
if not os.path.isfile(os.path.join(directory, filename)... | [
"Decorator that checks if required files exist before running.\n\n Parameters\n ----------\n required_files : list of str\n A list of strings indicating the filenames of regular files\n (not directories) that should be found in the input directory\n (which is the first argument to the ... |
Please provide a description of the function:def fill_hdf5_file(h5file, data):
# Check that all sources for a split have the same length
split_names = set(split_tuple[0] for split_tuple in data)
for name in split_names:
lengths = [len(split_tuple[2]) for split_tuple in data
i... | [
"Fills an HDF5 file in a H5PYDataset-compatible manner.\n\n Parameters\n ----------\n h5file : :class:`h5py.File`\n File handle for an HDF5 file.\n data : tuple of tuple\n One element per split/source pair. Each element consists of a\n tuple of (split_name, source_name, data_array, ... |
Please provide a description of the function:def progress_bar(name, maxval, prefix='Converting'):
widgets = ['{} {}: '.format(prefix, name), Percentage(), ' ',
Bar(marker='=', left='[', right=']'), ' ', ETA()]
bar = ProgressBar(widgets=widgets, max_value=maxval, fd=sys.stdout).start()
tr... | [
"Manages a progress bar for a conversion.\n\n Parameters\n ----------\n name : str\n Name of the file being converted.\n maxval : int\n Total number of steps for the conversion.\n\n "
] |
Please provide a description of the function:def convert_iris(directory, output_directory, output_filename='iris.hdf5'):
classes = {b'Iris-setosa': 0, b'Iris-versicolor': 1, b'Iris-virginica': 2}
data = numpy.loadtxt(
os.path.join(directory, 'iris.data'),
converters={4: lambda x: classes[x]... | [
"Convert the Iris dataset to HDF5.\n\n Converts the Iris dataset to an HDF5 dataset compatible with\n :class:`fuel.datasets.Iris`. The converted dataset is\n saved as 'iris.hdf5'.\n This method assumes the existence of the file `iris.data`.\n\n Parameters\n ----------\n directory : str\n ... |
Please provide a description of the function:def fill_subparser(subparser):
urls = ([None] * len(ALL_FILES))
filenames = list(ALL_FILES)
subparser.set_defaults(urls=urls, filenames=filenames)
subparser.add_argument('-P', '--url-prefix', type=str, default=None,
help="URL p... | [
"Sets up a subparser to download the ILSVRC2012 dataset files.\n\n Note that you will need to use `--url-prefix` to download the\n non-public files (namely, the TARs of images). This is a single\n prefix that is common to all distributed files, which you can\n obtain by registering at the ImageNet websi... |
Please provide a description of the function:def _get_target_index(self):
return (self.index + self.source_window * (not self.overlapping) +
self.offset) | [
"Return the index where the target window starts."
] |
Please provide a description of the function:def _get_end_index(self):
return max(self.index + self.source_window,
self._get_target_index() + self.target_window) | [
"Return the end of both windows."
] |
Please provide a description of the function:def convert_svhn_format_1(directory, output_directory,
output_filename='svhn_format_1.hdf5'):
try:
output_path = os.path.join(output_directory, output_filename)
h5file = h5py.File(output_path, mode='w')
TMPDIR = temp... | [
"Converts the SVHN dataset (format 1) to HDF5.\n\n This method assumes the existence of the files\n `{train,test,extra}.tar.gz`, which are accessible through the\n official website [SVHNSITE].\n\n .. [SVHNSITE] http://ufldl.stanford.edu/housenumbers/\n\n Parameters\n ----------\n directory : st... |
Please provide a description of the function:def convert_svhn_format_2(directory, output_directory,
output_filename='svhn_format_2.hdf5'):
output_path = os.path.join(output_directory, output_filename)
h5file = h5py.File(output_path, mode='w')
train_set = loadmat(os.path.join(... | [
"Converts the SVHN dataset (format 2) to HDF5.\n\n This method assumes the existence of the files\n `{train,test,extra}_32x32.mat`, which are accessible through the\n official website [SVHNSITE].\n\n Parameters\n ----------\n directory : str\n Directory in which input files reside.\n out... |
Please provide a description of the function:def convert_svhn(which_format, directory, output_directory,
output_filename=None):
if which_format not in (1, 2):
raise ValueError("SVHN format needs to be either 1 or 2.")
if not output_filename:
output_filename = 'svhn_format_{... | [
"Converts the SVHN dataset to HDF5.\n\n Converts the SVHN dataset [SVHN] to an HDF5 dataset compatible\n with :class:`fuel.datasets.SVHN`. The converted dataset is\n saved as 'svhn_format_1.hdf5' or 'svhn_format_2.hdf5', depending\n on the `which_format` argument.\n\n .. [SVHN] Yuval Netzer, Tao Wang... |
Please provide a description of the function:def open_(filename, mode='r', encoding=None):
if filename.endswith('.gz'):
if six.PY2:
zf = io.BufferedReader(gzip.open(filename, mode))
if encoding:
return codecs.getreader(encoding)(zf)
else:
... | [
"Open a text file with encoding and optional gzip compression.\n\n Note that on legacy Python any encoding other than ``None`` or opening\n GZipped files will return an unpicklable file-like object.\n\n Parameters\n ----------\n filename : str\n The filename to read.\n mode : str, optional\... |
Please provide a description of the function:def tar_open(f):
if isinstance(f, six.string_types):
return tarfile.open(name=f)
else:
return tarfile.open(fileobj=f) | [
"Open either a filename or a file-like object as a TarFile.\n\n Parameters\n ----------\n f : str or file-like object\n The filename or file-like object from which to read.\n\n Returns\n -------\n TarFile\n A `TarFile` instance.\n\n "
] |
Please provide a description of the function:def cache_file(filename):
dataset_local_dir = config.local_data_path
dataset_remote_dir = os.path.dirname(filename)
if dataset_remote_dir == "" or dataset_local_dir == "":
log.debug("Local dataset cache is deactivated")
remote_name = filename
... | [
"Caches a file locally if possible.\n\n If caching was succesfull, or if\n the file was previously successfully cached, this method returns the\n path to the local copy of the file. If not, it returns the path to\n the original file.\n\n Parameters\n ----------\n filename : str\n Remote ... |
Please provide a description of the function:def copy_from_server_to_local(dataset_remote_dir, dataset_local_dir,
remote_fname, local_fname):
log.debug("Copying file `{}` to a local directory `{}`."
.format(remote_fname, dataset_local_dir))
head, tail = os.path.... | [
"Copies a remote file locally.\n\n Parameters\n ----------\n remote_fname : str\n Remote file to copy\n local_fname : str\n Path and name of the local copy to be made of the remote file.\n\n "
] |
Please provide a description of the function:def convert_to_one_hot(y):
max_value = max(y)
min_value = min(y)
length = len(y)
one_hot = numpy.zeros((length, (max_value - min_value + 1)))
one_hot[numpy.arange(length), y] = 1
return one_hot | [
"\n converts y into one hot reprsentation.\n\n Parameters\n ----------\n y : list\n A list containing continous integer values.\n\n Returns\n -------\n one_hot : numpy.ndarray\n A numpy.ndarray object, which is one-hot representation of y.\n\n "
] |
Please provide a description of the function:def convert_adult(directory, output_directory,
output_filename='adult.hdf5'):
train_path = os.path.join(directory, 'adult.data')
test_path = os.path.join(directory, 'adult.test')
output_path = os.path.join(output_directory, output_filename)... | [
"\n Convert the Adult dataset to HDF5.\n\n Converts the Adult dataset to an HDF5 dataset compatible with\n :class:`fuel.datasets.Adult`. The converted dataset is saved as\n 'adult.hdf5'.\n This method assumes the existence of the file `adult.data` and\n `adult.test`.\n\n Parameters\n -------... |
Please provide a description of the function:def convert_binarized_mnist(directory, output_directory,
output_filename='binarized_mnist.hdf5'):
output_path = os.path.join(output_directory, output_filename)
h5file = h5py.File(output_path, mode='w')
train_set = numpy.loadtxt(
... | [
"Converts the binarized MNIST dataset to HDF5.\n\n Converts the binarized MNIST dataset used in R. Salakhutdinov's DBN\n paper [DBN] to an HDF5 dataset compatible with\n :class:`fuel.datasets.BinarizedMNIST`. The converted dataset is\n saved as 'binarized_mnist.hdf5'.\n\n This method assumes the exis... |
Please provide a description of the function:def fill_subparser(subparser):
url = 'http://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz'
filename = 'cifar-10-python.tar.gz'
subparser.set_defaults(urls=[url], filenames=[filename])
return default_downloader | [
"Sets up a subparser to download the CIFAR-10 dataset file.\n\n The CIFAR-10 dataset file is downloaded from Alex Krizhevsky's\n website [ALEX].\n\n Parameters\n ----------\n subparser : :class:`argparse.ArgumentParser`\n Subparser handling the `cifar10` command.\n\n "
] |
Please provide a description of the function:def convert_celeba_aligned_cropped(directory, output_directory,
output_filename=OUTPUT_FILENAME):
output_path = os.path.join(output_directory, output_filename)
h5file = _initialize_conversion(directory, output_path, (218, 178))... | [
"Converts the aligned and cropped CelebA dataset to HDF5.\n\n Converts the CelebA dataset to an HDF5 dataset compatible with\n :class:`fuel.datasets.CelebA`. The converted dataset is saved as\n 'celeba_aligned_cropped.hdf5'.\n\n It assumes the existence of the following files:\n\n * `img_align_celeba... |
Please provide a description of the function:def convert_celeba(which_format, directory, output_directory,
output_filename=None):
if which_format not in ('aligned_cropped', '64'):
raise ValueError("CelebA format needs to be either "
"'aligned_cropped' or '64'... | [
"Converts the CelebA dataset to HDF5.\n\n Converts the CelebA dataset to an HDF5 dataset compatible with\n :class:`fuel.datasets.CelebA`. The converted dataset is\n saved as 'celeba_aligned_cropped.hdf5' or 'celeba_64.hdf5',\n depending on the `which_format` argument.\n\n Parameters\n ----------\n... |
Please provide a description of the function:def disk_usage(path):
st = os.statvfs(path)
total = st.f_blocks * st.f_frsize
used = (st.f_blocks - st.f_bfree) * st.f_frsize
return total, used | [
"Return free usage about the given path, in bytes.\n\n Parameters\n ----------\n path : str\n Folder for which to return disk usage\n\n Returns\n -------\n output : tuple\n Tuple containing total space in the folder and currently\n used space in the folder\n\n "
] |
Please provide a description of the function:def safe_mkdir(folder_name, force_perm=None):
if os.path.exists(folder_name):
return
intermediary_folders = folder_name.split(os.path.sep)
# Remove invalid elements from intermediary_folders
if intermediary_folders[-1] == "":
intermediar... | [
"Create the specified folder.\n\n If the parent folders do not exist, they are also created.\n If the folder already exists, nothing is done.\n\n Parameters\n ----------\n folder_name : str\n Name of the folder to create.\n force_perm : str\n Mode to use for folder creation.\n\n "... |
Please provide a description of the function:def check_enough_space(dataset_local_dir, remote_fname, local_fname,
max_disk_usage=0.9):
storage_need = os.path.getsize(remote_fname)
storage_total, storage_used = disk_usage(dataset_local_dir)
# Instead of only looking if there's en... | [
"Check if the given local folder has enough space.\n\n Check if the given local folder has enough space to store\n the specified remote file.\n\n Parameters\n ----------\n remote_fname : str\n Path to the remote file\n remote_fname : str\n Path to the local folder\n max_disk_usage... |
Please provide a description of the function:def convert_cifar100(directory, output_directory,
output_filename='cifar100.hdf5'):
output_path = os.path.join(output_directory, output_filename)
h5file = h5py.File(output_path, mode="w")
input_file = os.path.join(directory, 'cifar-100-p... | [
"Converts the CIFAR-100 dataset to HDF5.\n\n Converts the CIFAR-100 dataset to an HDF5 dataset compatible with\n :class:`fuel.datasets.CIFAR100`. The converted dataset is saved as\n 'cifar100.hdf5'.\n\n This method assumes the existence of the following file:\n `cifar-100-python.tar.gz`\n\n Parame... |
Please provide a description of the function:def verify_axis_labels(self, expected, actual, source_name):
if not getattr(self, '_checked_axis_labels', False):
self._checked_axis_labels = defaultdict(bool)
if not self._checked_axis_labels[source_name]:
if actual is None:
... | [
"Verify that axis labels for a given source are as expected.\n\n Parameters\n ----------\n expected : tuple\n A tuple of strings representing the expected axis labels.\n actual : tuple or None\n A tuple of strings representing the actual axis labels, or\n ... |
Please provide a description of the function:def get_data(self, request=None):
if request is None:
raise ValueError
data = [[] for _ in self.sources]
for i in range(request):
try:
for source_data, example in zip(
data, next... | [
"Get data from the dataset."
] |
Please provide a description of the function:def _producer_wrapper(f, port, addr='tcp://127.0.0.1'):
try:
context = zmq.Context()
socket = context.socket(zmq.PUSH)
socket.connect(':'.join([addr, str(port)]))
f(socket)
finally:
# Works around a Python 3.x bug.
... | [
"A shim that sets up a socket and starts the producer callable.\n\n Parameters\n ----------\n f : callable\n Callable that takes a single argument, a handle\n for a ZeroMQ PUSH socket. Must be picklable.\n port : int\n The port on which the socket should connect.\n addr : str, op... |
Please provide a description of the function:def _spawn_producer(f, port, addr='tcp://127.0.0.1'):
process = Process(target=_producer_wrapper, args=(f, port, addr))
process.start()
return process | [
"Start a process that sends results on a PUSH socket.\n\n Parameters\n ----------\n f : callable\n Callable that takes a single argument, a handle\n for a ZeroMQ PUSH socket. Must be picklable.\n\n Returns\n -------\n process : multiprocessing.Process\n The process handle of t... |
Please provide a description of the function:def producer_consumer(producer, consumer, addr='tcp://127.0.0.1',
port=None, context=None):
context_created = False
if context is None:
context_created = True
context = zmq.Context()
try:
consumer_socket = contex... | [
"A producer-consumer pattern.\n\n Parameters\n ----------\n producer : callable\n Callable that takes a single argument, a handle\n for a ZeroMQ PUSH socket. Must be picklable.\n consumer : callable\n Callable that takes a single argument, a handle\n for a ZeroMQ PULL socket.... |
Please provide a description of the function:def convert_dogs_vs_cats(directory, output_directory,
output_filename='dogs_vs_cats.hdf5'):
# Prepare output file
output_path = os.path.join(output_directory, output_filename)
h5file = h5py.File(output_path, mode='w')
dtype = h5p... | [
"Converts the Dogs vs. Cats dataset to HDF5.\n\n Converts the Dogs vs. Cats dataset to an HDF5 dataset compatible with\n :class:`fuel.datasets.dogs_vs_cats`. The converted dataset is saved as\n 'dogs_vs_cats.hdf5'.\n\n It assumes the existence of the following files:\n\n * `dogs_vs_cats.train.zip`\n ... |
Please provide a description of the function:def main(args=None):
built_in_datasets = dict(downloaders.all_downloaders)
if fuel.config.extra_downloaders:
for name in fuel.config.extra_downloaders:
extra_datasets = dict(
importlib.import_module(name).all_downloaders)
... | [
"Entry point for `fuel-download` script.\n\n This function can also be imported and used from Python.\n\n Parameters\n ----------\n args : iterable, optional (default: None)\n A list of arguments that will be passed to Fuel's downloading\n utility. If this argument is not specified, `sys.a... |
Please provide a description of the function:def fill_subparser(subparser):
filenames = ['train-images-idx3-ubyte.gz', 'train-labels-idx1-ubyte.gz',
't10k-images-idx3-ubyte.gz', 't10k-labels-idx1-ubyte.gz']
urls = ['http://yann.lecun.com/exdb/mnist/' + f for f in filenames]
subparser.s... | [
"Sets up a subparser to download the MNIST dataset files.\n\n The following MNIST dataset files are downloaded from Yann LeCun's\n website [LECUN]:\n `train-images-idx3-ubyte.gz`, `train-labels-idx1-ubyte.gz`,\n `t10k-images-idx3-ubyte.gz`, `t10k-labels-idx1-ubyte.gz`.\n\n Parameters\n ----------\... |
Please provide a description of the function:def main(args=None):
parser = argparse.ArgumentParser(
description='Extracts metadata from a Fuel-converted HDF5 file.')
parser.add_argument("filename", help="HDF5 file to analyze")
args = parser.parse_args()
with h5py.File(args.filename, 'r') a... | [
"Entry point for `fuel-info` script.\n\n This function can also be imported and used from Python.\n\n Parameters\n ----------\n args : iterable, optional (default: None)\n A list of arguments that will be passed to Fuel's information\n utility. If this argument is not specified, `sys.argv[... |
Please provide a description of the function:def convert_silhouettes(size, directory, output_directory,
output_filename=None):
if size not in (16, 28):
raise ValueError('size must be 16 or 28')
if output_filename is None:
output_filename = 'caltech101_silhouettes{}.... | [
" Convert the CalTech 101 Silhouettes Datasets.\n\n Parameters\n ----------\n size : {16, 28}\n Convert either the 16x16 or 28x28 sized version of the dataset.\n directory : str\n Directory in which the required input files reside.\n output_filename : str\n Where to save the conv... |
Please provide a description of the function:def cross_validation(scheme_class, num_examples, num_folds, strict=True,
**kwargs):
if strict and num_examples % num_folds != 0:
raise ValueError(("{} examples are not divisible in {} evenly-sized " +
"folds. To... | [
"Return pairs of schemes to be used for cross-validation.\n\n Parameters\n ----------\n scheme_class : subclass of :class:`IndexScheme` or :class:`BatchScheme`\n The type of the returned schemes. The constructor is called with an\n iterator and `**kwargs` as arguments.\n num_examples : int... |
Please provide a description of the function:def main(args=None):
built_in_datasets = dict(converters.all_converters)
if fuel.config.extra_converters:
for name in fuel.config.extra_converters:
extra_datasets = dict(
importlib.import_module(name).all_converters)
... | [
"Entry point for `fuel-convert` script.\n\n This function can also be imported and used from Python.\n\n Parameters\n ----------\n args : iterable, optional (default: None)\n A list of arguments that will be passed to Fuel's conversion\n utility. If this argument is not specified, `sys.arg... |
Please provide a description of the function:def refresh_lock(lock_file):
unique_id = '%s_%s_%s' % (
os.getpid(),
''.join([str(random.randint(0, 9)) for i in range(10)]), hostname)
try:
lock_write = open(lock_file, 'w')
lock_write.write(unique_id + '\n')
lock_write.c... | [
"'Refresh' an existing lock.\n\n 'Refresh' an existing lock by re-writing the file containing the\n owner's unique id, using a new (randomly generated) id, which is also\n returned.\n\n "
] |
Please provide a description of the function:def lock(tmp_dir, timeout=NOT_SET, min_wait=None, max_wait=None, verbosity=1):
if min_wait is None:
min_wait = MIN_WAIT
if max_wait is None:
max_wait = min_wait * 2
if timeout is NOT_SET:
timeout = TIMEOUT
# Create base of lock di... | [
"Obtain lock.\n\n Obtain lock access by creating a given temporary directory (whose base\n will be created if needed, but will not be deleted after the lock is\n removed). If access is refused by the same lock owner during more than\n 'timeout' seconds, then the current lock is overridden. If timeout is... |
Please provide a description of the function:def get_lock(lock_dir, **kw):
if not hasattr(get_lock, 'n_lock'):
# Initialization.
get_lock.n_lock = 0
if not hasattr(get_lock, 'lock_is_enabled'):
# Enable lock by default.
get_lock.lock_is_enabled = True
get... | [
"Obtain lock on compilation directory.\n\n Parameters\n ----------\n lock_dir : str\n Lock directory.\n kw : dict\n Additional arguments to be forwarded to the `lock` function when\n acquiring the lock.\n\n Notes\n -----\n We can lock only on 1 directory at a time.\n\n "... |
Please provide a description of the function:def release_lock():
get_lock.n_lock -= 1
assert get_lock.n_lock >= 0
# Only really release lock once all lock requests have ended.
if get_lock.lock_is_enabled and get_lock.n_lock == 0:
get_lock.start_time = None
get_lock.unlocker.unlock() | [
"Release lock on compilation directory."
] |
Please provide a description of the function:def release_readlock(lockdir_name):
# Make sure the lock still exists before deleting it
if os.path.exists(lockdir_name) and os.path.isdir(lockdir_name):
os.rmdir(lockdir_name) | [
"Release a previously obtained readlock.\n\n Parameters\n ----------\n lockdir_name : str\n Name of the previously obtained readlock\n\n "
] |
Please provide a description of the function:def get_readlock(pid, path):
timestamp = int(time.time() * 1e6)
lockdir_name = "%s.readlock.%i.%i" % (path, pid, timestamp)
os.mkdir(lockdir_name)
# Register function to release the readlock at the end of the script
atexit.register(release_readlock,... | [
"Obtain a readlock on a file.\n\n Parameters\n ----------\n path : str\n Name of the file on which to obtain a readlock\n\n "
] |
Please provide a description of the function:def unlock(self):
# If any error occurs, we assume this is because someone else tried to
# unlock this directory at the same time.
# Note that it is important not to have both remove statements within
# the same try/except block. The ... | [
"Remove current lock.\n\n This function does not crash if it is unable to properly\n delete the lock file and directory. The reason is that it\n should be allowed for multiple jobs running in parallel to\n unlock the same directory at the same time (e.g. when reaching\n their time... |
Please provide a description of the function:def filename_from_url(url, path=None):
r = requests.get(url, stream=True)
if 'Content-Disposition' in r.headers:
filename = re.findall(r'filename=([^;]+)',
r.headers['Content-Disposition'])[0].strip('"\"')
else:
... | [
"Parses a URL to determine a file name.\n\n Parameters\n ----------\n url : str\n URL to parse.\n\n "
] |
Please provide a description of the function:def download(url, file_handle, chunk_size=1024):
r = requests.get(url, stream=True)
total_length = r.headers.get('content-length')
if total_length is None:
maxval = UnknownLength
else:
maxval = int(total_length)
name = file_handle.nam... | [
"Downloads a given URL to a specific file.\n\n Parameters\n ----------\n url : str\n URL to download.\n file_handle : file\n Where to save the downloaded URL.\n\n "
] |
Please provide a description of the function:def default_downloader(directory, urls, filenames, url_prefix=None,
clear=False):
# Parse file names from URL if not provided
for i, url in enumerate(urls):
filename = filenames[i]
if not filename:
filename = fi... | [
"Downloads or clears files from URLs and filenames.\n\n Parameters\n ----------\n directory : str\n The directory in which downloaded files are saved.\n urls : list\n A list of URLs to download.\n filenames : list\n A list of file names for the corresponding URLs.\n url_prefix... |
Please provide a description of the function:def find_in_data_path(filename):
for path in config.data_path:
path = os.path.expanduser(os.path.expandvars(path))
file_path = os.path.join(path, filename)
if os.path.isfile(file_path):
return file_path
raise IOError("{} not f... | [
"Searches for a file within Fuel's data path.\n\n This function loops over all paths defined in Fuel's data path and\n returns the first path in which the file is found.\n\n Parameters\n ----------\n filename : str\n Name of the file to find.\n\n Returns\n -------\n file_path : str\n ... |
Please provide a description of the function:def lazy_property_factory(lazy_property):
def lazy_property_getter(self):
if not hasattr(self, '_' + lazy_property):
self.load()
if not hasattr(self, '_' + lazy_property):
raise ValueError("{} wasn't loaded".format(lazy_proper... | [
"Create properties that perform lazy loading of attributes."
] |
Please provide a description of the function:def do_not_pickle_attributes(*lazy_properties):
r
def wrap_class(cls):
if not hasattr(cls, 'load'):
raise ValueError("no load method implemented")
# Attach the lazy loading properties to the class
for lazy_property in lazy_propert... | [
"Decorator to assign non-pickable properties.\n\n Used to assign properties which will not be pickled on some class.\n This decorator creates a series of properties whose values won't be\n serialized; instead, their values will be reloaded (e.g. from disk) by\n the :meth:`load` function after deserializ... |
Please provide a description of the function:def sorted_fancy_indexing(indexable, request):
if len(request) > 1:
indices = numpy.argsort(request)
data = numpy.empty(shape=(len(request),) + indexable.shape[1:],
dtype=indexable.dtype)
dat... | [
"Safe fancy indexing.\n\n Some objects, such as h5py datasets, only support list indexing\n if the list is sorted.\n\n This static method adds support for unsorted list indexing by\n sorting the requested indices, accessing the corresponding\n elements and re-shuffling the result.... |
Please provide a description of the function:def slice_to_numerical_args(slice_, num_examples):
start = slice_.start if slice_.start is not None else 0
stop = slice_.stop if slice_.stop is not None else num_examples
step = slice_.step if slice_.step is not None else 1
return sta... | [
"Translate a slice's attributes into numerical attributes.\n\n Parameters\n ----------\n slice_ : :class:`slice`\n Slice for which numerical attributes are wanted.\n num_examples : int\n Number of examples in the indexable that is to be sliced\n through. ... |
Please provide a description of the function:def get_list_representation(self):
if self.is_list:
return self.list_or_slice
else:
return self[list(range(self.num_examples))] | [
"Returns this subset's representation as a list of indices."
] |
Please provide a description of the function:def index_within_subset(self, indexable, subset_request,
sort_indices=False):
# Translate the request within the context of this subset to a
# request to the indexable object
if isinstance(subset_request, numbers.I... | [
"Index an indexable object within the context of this subset.\n\n Parameters\n ----------\n indexable : indexable object\n The object to index through.\n subset_request : :class:`list` or :class:`slice`\n List of positive integer indices or slice that constitutes\n ... |
Please provide a description of the function:def num_examples(self):
if self.is_list:
return len(self.list_or_slice)
else:
start, stop, step = self.slice_to_numerical_args(
self.list_or_slice, self.original_num_examples)
return stop - start | [
"The number of examples this subset spans."
] |
Please provide a description of the function:def get_epoch_iterator(self, **kwargs):
if not self._fresh_state:
self.next_epoch()
else:
self._fresh_state = False
return super(DataStream, self).get_epoch_iterator(**kwargs) | [
"Get an epoch iterator for the data stream."
] |
Please provide a description of the function:def fill_subparser(subparser):
sets = ['train', 'valid', 'test']
urls = ['http://www.cs.toronto.edu/~larocheh/public/datasets/' +
'binarized_mnist/binarized_mnist_{}.amat'.format(s) for s in sets]
filenames = ['binarized_mnist_{}.amat'.format(s) ... | [
"Sets up a subparser to download the binarized MNIST dataset files.\n\n The binarized MNIST dataset files\n (`binarized_mnist_{train,valid,test}.amat`) are downloaded from\n Hugo Larochelle's website [HUGO].\n\n .. [HUGO] http://www.cs.toronto.edu/~larocheh/public/datasets/\n binarized_mnist/binar... |
Please provide a description of the function:def linkcode_resolve(domain, info):
if domain != 'py':
return None
modname = info['module']
fullname = info['fullname']
submod = sys.modules.get(modname)
if submod is None:
return None
obj = submod
for part in fullname.spli... | [
"\n Determine the URL corresponding to Python object\n "
] |
Please provide a description of the function:def download(directory, youtube_id, clear=False):
filepath = os.path.join(directory, '{}.m4a'.format(youtube_id))
if clear:
os.remove(filepath)
return
if not PAFY_AVAILABLE:
raise ImportError("pafy is required to download YouTube vide... | [
"Download the audio of a YouTube video.\n\n The audio is downloaded in the highest available quality. Progress is\n printed to `stdout`. The file is named `youtube_id.m4a`, where\n `youtube_id` is the 11-character code identifiying the YouTube video\n (can be determined from the URL).\n\n Parameters\... |
Please provide a description of the function:def fill_subparser(subparser):
subparser.add_argument(
'--youtube-id', type=str, required=True,
help=("The YouTube ID of the video from which to extract audio, "
"usually an 11-character string.")
)
return download | [
"Sets up a subparser to download audio of YouTube videos.\n\n Adds the compulsory `--youtube-id` flag.\n\n Parameters\n ----------\n subparser : :class:`argparse.ArgumentParser`\n Subparser handling the `youtube_audio` command.\n\n "
] |
Please provide a description of the function:def convert_youtube_audio(directory, output_directory, youtube_id, channels,
sample, output_filename=None):
input_file = os.path.join(directory, '{}.m4a'.format(youtube_id))
wav_filename = '{}.wav'.format(youtube_id)
wav_file = os.p... | [
"Converts downloaded YouTube audio to HDF5 format.\n\n Requires `ffmpeg` to be installed and available on the command line\n (i.e. available on your `PATH`).\n\n Parameters\n ----------\n directory : str\n Directory in which input files reside.\n output_directory : str\n Directory in... |
Please provide a description of the function:def fill_subparser(subparser):
subparser.add_argument(
'--youtube-id', type=str, required=True,
help=("The YouTube ID of the video from which to extract audio, "
"usually an 11-character string.")
)
subparser.add_argument(
... | [
"Sets up a subparser to convert YouTube audio files.\n\n Adds the compulsory `--youtube-id` flag as well as the optional\n `sample` and `channels` flags.\n\n Parameters\n ----------\n subparser : :class:`argparse.ArgumentParser`\n Subparser handling the `youtube_audio` command.\n\n "
] |
Please provide a description of the function:def convert_ilsvrc2012(directory, output_directory,
output_filename='ilsvrc2012.hdf5',
shuffle_seed=config.default_seed):
devkit_path = os.path.join(directory, DEVKIT_ARCHIVE)
train, valid, test = [os.path.join(direc... | [
"Converter for data from the ILSVRC 2012 competition.\n\n Source files for this dataset can be obtained by registering at\n [ILSVRC2012WEB].\n\n Parameters\n ----------\n input_directory : str\n Path from which to read raw data files.\n output_directory : str\n Path to which to save ... |
Please provide a description of the function:def fill_subparser(subparser):
subparser.add_argument(
"--shuffle-seed", help="Seed to use for randomizing order of the "
"training set on disk.",
default=config.default_seed, type=int, required=False)
return conver... | [
"Sets up a subparser to convert the ILSVRC2012 dataset files.\n\n Parameters\n ----------\n subparser : :class:`argparse.ArgumentParser`\n Subparser handling the `ilsvrc2012` command.\n\n "
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.