INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Create an iterator that generates randomly shuffled mini - batches of sample indices. The batches will have batch_size elements.
def shuffled_indices_batch_iterator(self, batch_size, shuffle_rng): """ Create an iterator that generates randomly shuffled mini-batches of sample indices. The batches will have `batch_size` elements. The generated mini-batches indices take the form of 1D NumPy integer arrays. ...
Compute sample weight given an array of sample classes. The weights are assigned on a per - class basis and the per - class weights are inversely proportional to their frequency.
def class_balancing_sample_weights(y): """ Compute sample weight given an array of sample classes. The weights are assigned on a per-class basis and the per-class weights are inversely proportional to their frequency. Parameters ---------- y: NumPy array, 1D dtyp...
Create an iterator that generates randomly shuffled mini - batches of sample indices. The batches will have batch_size elements.
def shuffled_indices_batch_iterator(self, batch_size, shuffle_rng): """ Create an iterator that generates randomly shuffled mini-batches of sample indices. The batches will have `batch_size` elements. The generated mini-batches indices take the form of 1D NumPy integer arrays. ...
Construct a WeightedSubsetSampler that compensates for class imbalance.
def class_balancing_sampler(y, indices): """ Construct a `WeightedSubsetSampler` that compensates for class imbalance. Parameters ---------- y: NumPy array, 1D dtype=int sample classes, values must be 0 or positive indices: NumPy array, 1D dtype=int ...
Wait up to timeout seconds for service at host: port to start.
def wait_for_service_available(container, url, timeout): """ Wait up to timeout seconds for service at host:port to start. Returns True if service becomes available, False if the container stops or raises ServiceTimeout if timeout is reached. """ start = time.time() remaining = time...
Get the path of the given file within the batchup data directory
def get_data_path(filename): """ Get the path of the given file within the batchup data directory Parameters ---------- filename: str The filename to locate within the batchup data directory Returns ------- str The full path of the file """ if os.path.isabs(file...
Download a file to a given path from a given URL if it does not exist.
def download(path, source_url): """ Download a file to a given path from a given URL, if it does not exist. Parameters ---------- path: str The (destination) path of the file on the local filesystem source_url: str The URL from which to download the file Returns -------...
Compute the SHA - 256 hash of the file at the given path
def compute_sha256(path): """ Compute the SHA-256 hash of the file at the given path Parameters ---------- path: str The path of the file Returns ------- str The SHA-256 HEX digest """ hasher = hashlib.sha256() with open(path, 'rb') as f: # 10MB chun...
Verify the integrity of a file by checking its SHA - 256 hash. If no digest is supplied the digest is printed to the console.
def verify_file(path, sha256): """ Verify the integrity of a file by checking its SHA-256 hash. If no digest is supplied, the digest is printed to the console. Closely follows the code in `torchvision.datasets.utils.check_integrity` Parameters ---------- path: str The path of the f...
Download a file to a given path from a given URL if it does not exist. After downloading it verify it integrity by checking the SHA - 256 hash.
def download_and_verify(path, source_url, sha256): """ Download a file to a given path from a given URL, if it does not exist. After downloading it, verify it integrity by checking the SHA-256 hash. Parameters ---------- path: str The (destination) path of the file on the local filesyst...
Copy a file to a given path from a given path if it does not exist. After copying it verify it integrity by checking the SHA - 256 hash.
def copy_and_verify(path, source_path, sha256): """ Copy a file to a given path from a given path, if it does not exist. After copying it, verify it integrity by checking the SHA-256 hash. Parameters ---------- path: str The (destination) path of the file on the local filesystem sou...
Create ckanext - ( name ) in target directory.
def ckan_extension_template(name, target): """ Create ckanext-(name) in target directory. """ setupdir = '{0}/ckanext-{1}theme'.format(target, name) extdir = setupdir + '/ckanext/{0}theme'.format(name) templatedir = extdir + '/templates/' staticdir = extdir + '/static/datacats' makedirs...
Run a command or interactive shell within this environment
def shell(environment, opts): """Run a command or interactive shell within this environment Usage: datacats [-d] [-s NAME] shell [ENVIRONMENT [COMMAND...]] Options: -d --detach Run the resulting container in the background -s --site=NAME Specify a site to run the shell on [default: primary] ENVIRON...
Run a paster command from the current directory
def paster(opts): """Run a paster command from the current directory Usage: datacats paster [-d] [-s NAME] [COMMAND...] Options: -s --site=NAME Specify a site to run this paster command on [default: primary] -d --detach Run the resulting container in the background You must be inside a datacats env...
Add a site s configuration to the source dir and site dir
def save_new_site(site_name, sitedir, srcdir, port, address, site_url, passwords): """ Add a site's configuration to the source dir and site dir """ cp = ConfigParser.SafeConfigParser() cp.read([srcdir + '/.datacats-environment']) section_name = 'site_' + site_name if not cp.has_se...
Save an environment s configuration to the source dir and data dir
def save_new_environment(name, datadir, srcdir, ckan_version, deploy_target=None, always_prod=False): """ Save an environment's configuration to the source dir and data dir """ with open(datadir + '/.version', 'w') as f: f.write('2') cp = ConfigParser.SafeConfigParser() cp.read...
: param environment_name: exising environment name path or None to look in current or parent directories for project
def find_environment_dirs(environment_name=None, data_only=False): """ :param environment_name: exising environment name, path or None to look in current or parent directories for project returns (srcdir, extension_dir, datadir) extension_dir is the name of extension directory user was in/ref...
Load configuration values for an environment
def load_environment(srcdir, datadir=None, allow_old=False): """ Load configuration values for an environment :param srcdir: environment source directory :param datadir: environment data direcory, if None will be discovered from srcdir :param allow_old: Don't throw an exception ...
Load configuration values for a site.
def load_site(srcdir, datadir, site_name=None): """ Load configuration values for a site. Returns (port, address, site_url, passwords) """ if site_name is None: site_name = 'primary' if not validate.valid_name(site_name): raise DatacatsError('{} is not a valid site name.'.format...
Check if a new environment or site can be created at the given path.
def new_environment_check(srcpath, site_name, ckan_version): """ Check if a new environment or site can be created at the given path. Returns (name, datadir, sitedir, srcdir) or raises DatacatsError """ docker.require_images() workdir, name = path.split(path.abspath(path.expanduser(srcpath))) ...
Return True if the directories and containers we re expecting are present in datadir sitedir and containers
def data_complete(datadir, sitedir, get_container_name): """ Return True if the directories and containers we're expecting are present in datadir, sitedir and containers """ if any(not path.isdir(sitedir + x) for x in ('/files', '/run', '/solr')): return False if docker.is_b...
Create expected directories in datadir sitedir and optionally srcdir
def create_directories(datadir, sitedir, srcdir=None): """ Create expected directories in datadir, sitedir and optionally srcdir """ # It's possible that the datadir already exists # (we're making a secondary site) if not path.isdir(datadir): os.makedirs(datadir, mode=0o700) try:...
Populate venv from preloaded image
def create_virtualenv(srcdir, datadir, preload_image, get_container_name): """ Populate venv from preloaded image """ try: if docker.is_boot2docker(): docker.data_only_container( get_container_name('venv'), ['/usr/lib/ckan'], ) ...
Copy ckan source datapusher source ( optional ) who. ini and schema. xml from preload image into srcdir
def create_source(srcdir, preload_image, datapusher=False): """ Copy ckan source, datapusher source (optional), who.ini and schema.xml from preload image into srcdir """ try: docker.web_command( command='/bin/cp -a /project/ckan /project_target/ckan', rw={srcdir: '/pr...
Start all supporting containers ( containers required for CKAN to operate ) if they aren t already running along with some extra containers specified by the user
def start_supporting_containers(sitedir, srcdir, passwords, get_container_name, extra_containers, log_syslog=False): """ Start all supporting containers (containers required for CKAN to operate) if they aren't already running, along with some extra containers specified by the user """ if...
Stop postgres and solr containers along with any specified extra containers
def stop_supporting_containers(get_container_name, extra_containers): """ Stop postgres and solr containers, along with any specified extra containers """ docker.remove_container(get_container_name('postgres')) docker.remove_container(get_container_name('solr')) for container in extra_containers...
Return a list of containers tracked by this environment that are running
def containers_running(get_container_name): """ Return a list of containers tracked by this environment that are running """ running = [] for n in ['web', 'postgres', 'solr', 'datapusher', 'redis']: info = docker.inspect_container(get_container_name(n)) if info and not info['State'][...
Gets the names of all of the sites from the datadir and stores them in self. sites. Also returns this list.
def _load_sites(self): """ Gets the names of all of the sites from the datadir and stores them in self.sites. Also returns this list. """ if not self.sites: self.sites = task.list_sites(self.datadir) return self.sites
Save environment settings in the directory that need to be saved even when creating only a new sub - site env.
def save_site(self, create=True): """ Save environment settings in the directory that need to be saved even when creating only a new sub-site env. """ self._load_sites() if create: self.sites.append(self.site_name) task.save_new_site(self.site_name, s...
Save environment settings into environment directory overwriting any existing configuration and discarding site config
def save(self): """ Save environment settings into environment directory, overwriting any existing configuration and discarding site config """ task.save_new_environment(self.name, self.datadir, self.target, self.ckan_version, self.deploy_target, self.always_prod)
Return a Environment object with settings for a new project. No directories or containers are created by this call.
def new(cls, path, ckan_version, site_name, **kwargs): """ Return a Environment object with settings for a new project. No directories or containers are created by this call. :params path: location for new project directory, may be relative :params ckan_version: release of CKAN ...
Return an Environment object based on an existing environnment + site.
def load(cls, environment_name=None, site_name='primary', data_only=False, allow_old=False): """ Return an Environment object based on an existing environnment+site. :param environment_name: exising environment name, path or None to look in current or parent directories for project ...
Return True if all the expected datadir files are present
def data_complete(self): """ Return True if all the expected datadir files are present """ return task.data_complete(self.datadir, self.sitedir, self._get_container_name)
raise a DatacatsError if the datadir or volumes are missing or damaged
def require_data(self): """ raise a DatacatsError if the datadir or volumes are missing or damaged """ files = task.source_missing(self.target) if files: raise DatacatsError('Missing files in source directory:\n' + '\n'.join(files)) ...
Call once for new projects to create the initial project directories.
def create_directories(self, create_project_dir=True): """ Call once for new projects to create the initial project directories. """ return task.create_directories(self.datadir, self.sitedir, self.target if create_project_dir else None)
Populate venv from preloaded image
def create_virtualenv(self): """ Populate venv from preloaded image """ return task.create_virtualenv(self.target, self.datadir, self._preload_image(), self._get_container_name)
Empty our virtualenv so that new ( or older ) dependencies may be installed
def clean_virtualenv(self): """ Empty our virtualenv so that new (or older) dependencies may be installed """ self.user_run_script( script=scripts.get_script_path('clean_virtualenv.sh'), args=[], rw_venv=True, )
Populate ckan directory from preloaded image and copy who. ini and schema. xml info conf directory
def create_source(self, datapusher=True): """ Populate ckan directory from preloaded image and copy who.ini and schema.xml info conf directory """ task.create_source(self.target, self._preload_image(), datapusher)
Start all supporting containers ( containers required for CKAN to operate ) if they aren t already running.
def start_supporting_containers(self, log_syslog=False): """ Start all supporting containers (containers required for CKAN to operate) if they aren't already running. :param log_syslog: A flag to redirect all container logs to host's syslog """ log_syslog = True if ...
Use make - config to generate an initial development. ini file
def create_ckan_ini(self): """ Use make-config to generate an initial development.ini file """ self.run_command( command='/scripts/run_as_user.sh /usr/lib/ckan/bin/paster make-config' ' ckan /project/development.ini', rw_project=True, ro={s...
Use config - tool to update development. ini with our environment settings
def update_ckan_ini(self, skin=True): """ Use config-tool to update development.ini with our environment settings :param skin: use environment template skin plugin True/False """ command = [ '/usr/lib/ckan/bin/paster', '--plugin=ckan', 'config-tool', '/pr...
Create an example ckan extension for this environment and install it
def create_install_template_skin(self): """ Create an example ckan extension for this environment and install it """ ckan_extension_template(self.name, self.target) self.install_package_develop('ckanext-' + self.name + 'theme')
Run db init to create all ckan tables
def ckan_db_init(self, retry_seconds=DB_INIT_RETRY_SECONDS): """ Run db init to create all ckan tables :param retry_seconds: how long to retry waiting for db to start """ # XXX workaround for not knowing how long we need to wait # for postgres to be ready. fix this by ch...
Start the apache server or paster serve
def start_ckan(self, production=False, log_syslog=False, paster_reload=True, interactive=False): """ Start the apache server or paster serve :param log_syslog: A flag to redirect all container logs to host's syslog :param production: True for apache, False for paster ...
Create run/ development. ini in datadir with debug and site_url overridden and with correct db passwords inserted
def _create_run_ini(self, port, production, output='development.ini', source='development.ini', override_site_url=True): """ Create run/development.ini in datadir with debug and site_url overridden and with correct db passwords inserted """ cp = SafeConfig...
Start web container on port with command
def _run_web_container(self, port, command, address, log_syslog=False, datapusher=True, interactive=False): """ Start web container on port with command """ if is_boot2docker(): ro = {} volumes_from = self._get_container_name('venv') ...
Wait for the web server to become available or raise DatacatsError if it fails to start.
def wait_for_web_available(self): """ Wait for the web server to become available or raise DatacatsError if it fails to start. """ try: if not wait_for_service_available( self._get_container_name('web'), self.web_address(), ...
Return a port number from 5000 - 5999 based on the environment name to be used as a default when the user hasn t selected one.
def _choose_port(self): """ Return a port number from 5000-5999 based on the environment name to be used as a default when the user hasn't selected one. """ # instead of random let's base it on the name chosen (and the site name) return 5000 + unpack('Q', ...
Return another port from the 5000 - 5999 range
def _next_port(self, port): """ Return another port from the 5000-5999 range """ port = 5000 + (port + 1) % 1000 if port == self.port: raise DatacatsError('Too many instances running') return port
Stop and remove the web container
def stop_ckan(self): """ Stop and remove the web container """ remove_container(self._get_container_name('web'), force=True) remove_container(self._get_container_name('datapusher'), force=True)
return just the port number for the web container or None if not running
def _current_web_port(self): """ return just the port number for the web container, or None if not running """ info = inspect_container(self._get_container_name('web')) if info is None: return None try: if not info['State']['Running']: ...
Add a container as a extra. These are running containers which are not necessary for running default CKAN but are useful for certain extensions: param container: The container name to add: param error_on_exists: Raise a DatacatsError if the extra container already exists.
def add_extra_container(self, container, error_on_exists=False): """ Add a container as a 'extra'. These are running containers which are not necessary for running default CKAN but are useful for certain extensions :param container: The container name to add :param error_on_exist...
Return the url of the web server or None if not running
def web_address(self): """ Return the url of the web server or None if not running """ port = self._current_web_port() address = self.address or '127.0.0.1' if port is None: return None return 'http://{0}:{1}/'.format( address if address an...
create admin account with given password
def create_admin_set_password(self, password): """ create 'admin' account with given password """ with open(self.sitedir + '/run/admin.json', 'w') as out: json.dump({ 'name': 'admin', 'email': 'none', 'password': password, ...
launch interactive shell session with all writable volumes
def interactive_shell(self, command=None, paster=False, detach=False): """ launch interactive shell session with all writable volumes :param: list of strings to execute instead of bash """ if not exists(self.target + '/.bash_profile'): # this file is required for act...
Install from requirements. txt file found in psrc
def install_package_requirements(self, psrc, stream_output=None): """ Install from requirements.txt file found in psrc :param psrc: name of directory in environment directory """ package = self.target + '/' + psrc assert isdir(package), package reqname = '/requir...
Remove uploaded files postgres db solr index venv
def purge_data(self, which_sites=None, never_delete=False): """ Remove uploaded files, postgres db, solr index, venv """ # Default to the set of all sites if not exists(self.datadir + '/.version'): format_version = 1 else: with open(self.datadir + ...
: param container: web solr or postgres: param tail: number of lines to show: param follow: True to return generator instead of list: param timestamps: True to include timestamps
def logs(self, container, tail='all', follow=False, timestamps=False): """ :param container: 'web', 'solr' or 'postgres' :param tail: number of lines to show :param follow: True to return generator instead of list :param timestamps: True to include timestamps """ ...
Create/ replace ~/. datacats/ run/ proxy - environment and return entry for ro mount for containers
def _proxy_settings(self): """ Create/replace ~/.datacats/run/proxy-environment and return entry for ro mount for containers """ if not ('https_proxy' in environ or 'HTTPS_PROXY' in environ or 'http_proxy' in environ or 'HTTP_PROXY' in environ): return...
Gets the full name of a container of the type specified. Currently the supported types are: - venv - postgres - solr - web - pgdata - lessc - datapusher - redis The name will be formatted appropriately with any prefixes and postfixes needed.
def _get_container_name(self, container_type): """ Gets the full name of a container of the type specified. Currently the supported types are: - 'venv' - 'postgres' - 'solr' - 'web' - 'pgdata' - 'lessc' - 'datapu...
Recompiles less files in an environment.
def less(environment, opts): # pylint: disable=unused-argument """Recompiles less files in an environment. Usage: datacats less [ENVIRONMENT] ENVIRONMENT may be an environment name or a path to an environment directory. Default: '.' """ require_extra_image(LESSC_IMAGE) print 'Converting .less files...
Decorator applied to a dataset conversion function that converts acquired source files into a dataset file that BatchUp can use.
def fetch_and_convert_dataset(source_files, target_filename): """ Decorator applied to a dataset conversion function that converts acquired source files into a dataset file that BatchUp can use. Parameters ---------- source_file: list of `AbstractSourceFile` instances A list of files to...
Delete the cache ( converted files ) for a dataset.
def delete_dataset_cache(*filenames): """ Delete the cache (converted files) for a dataset. Parameters ---------- filenames: str Filenames of files to delete """ for filename in filenames: filename = path_string(filename) path = config.get_data_path(filename) ...
Download the file and return its path
def acquire(self, **kwargs): """ Download the file and return its path Returns ------- str or None The path of the file in BatchUp's temporary directory or None if the download failed. """ return config.download_data(self.temp_filename, se...
Copy the file and return its path
def acquire(self, **kwargs): """ Copy the file and return its path Returns ------- str or None The path of the file in BatchUp's temporary directory or None if the copy failed. """ if self.source_path is None: source_path = kwa...
Copy the file and return its path
def acquire(self, **kwargs): """ Copy the file and return its path Returns ------- str or None The path of the file or None if it does not exist or if verification failed. """ path = path_string(self.path) if os.path.exists(path): ...
A function which retries a given function num times and calls retry_notif each time the function is retried.: param func: The function to retry num times.: param num: The number of times to try before giving up.: param retry_notif: Will be called with the same parameter as func if we have to retry the function. Will al...
def _retry_func(func, param, num, retry_notif, error_msg): """ A function which retries a given function num times and calls retry_notif each time the function is retried. :param func: The function to retry num times. :param num: The number of times to try before giving up. :param retry_notif: W...
Retrieve a result from executing a task. Note that tasks are executed in order and that if the next task has not yet completed this call will block until the result is available.
def retrieve(self): """ Retrieve a result from executing a task. Note that tasks are executed in order and that if the next task has not yet completed, this call will block until the result is available. Returns ------- A result from the result buffer. ""...
Install or reinstall Python packages within this environment
def install(environment, opts): """Install or reinstall Python packages within this environment Usage: datacats install [-q] [--address=IP] [ENVIRONMENT [PACKAGE ...]] datacats install -c [q] [--address=IP] [ENVIRONMENT] Options: --address=IP The address to bind to when reloading after install -c...
Migrate an environment to a given revision of the datadir format.
def migrate(opts): """Migrate an environment to a given revision of the datadir format. Usage: datacats migrate [-y] [-r VERSION] [ENVIRONMENT_DIR] Options: -r --revision=VERSION The version of the datadir format you want to convert to [default: 2] -y --yes Answer yes...
Deploy environment to production DataCats. com cloud service
def deploy(environment, opts, profile): """Deploy environment to production DataCats.com cloud service Usage: datacats deploy [--create] [ENVIRONMENT [TARGET_NAME]] Options: --create Create a new environment on DataCats.com instead of updating an existing environment ...
Trim the mini - batch batch to the size length.
def _trim_batch(batch, length): """Trim the mini-batch `batch` to the size `length`. `batch` can be: - a NumPy array, in which case it's first axis will be trimmed to size `length` - a tuple, in which case `_trim_batch` applied recursively to each element and the resulting tuple returned ...
Apply a function to all the samples that are accessed as mini - batches obtained from an iterator. Returns the per - sample results.
def batch_map_concat(func, batch_iter, progress_iter_func=None, n_batches=None, prepend_args=None): """ Apply a function to all the samples that are accessed as mini-batches obtained from an iterator. Returns the per-sample results. The function `func` should return the result ...
Apply a function to all the samples that are accessed as mini - batches obtained from an iterator. Returns the across - samples mean of the results returned by func
def batch_map_mean(func, batch_iter, progress_iter_func=None, sum_axis=None, n_batches=None, prepend_args=None): """ Apply a function to all the samples that are accessed as mini-batches obtained from an iterator. Returns the across-samples mean of the results returned by `func` ...
Helper function to coerce an object into a data source selecting the appropriate data source class for the given object. If x is already a data source it is returned as is.
def coerce_data_source(x): """ Helper function to coerce an object into a data source, selecting the appropriate data source class for the given object. If `x` is already a data source it is returned as is. Parameters ---------- x: any The object to coerce. If `x` is a data source, ...
A batch oriented implementation of map. Applies a function to all the samples in this data source by breaking the data into mini - batches and applying the function to each mini - batch. Returns the per - sample results.
def batch_map_concat(self, func, batch_size, progress_iter_func=None, n_batches=None, prepend_args=None, **kwargs): """A batch oriented implementation of `map`. Applies a function to all the samples in this data source by breaking the data into mini-batches and applying ...
Gather a batch of samples by indices applying the mapping described by the ( optional ) indices array passed to the constructor.
def samples_by_indices(self, indices): """ Gather a batch of samples by indices, applying the mapping described by the (optional) `indices` array passed to the constructor. Parameters ---------- indices: 1D-array of ints or slice The samples to retrie...
Create an iterator that generates mini - batch sample indices. The batches will have batch_size elements with the exception of the final batch which will have less if there are insufficient elements left to make a complete batch.
def batch_indices_iterator(self, batch_size, shuffle=None, **kwargs): """ Create an iterator that generates mini-batch sample indices. The batches will have `batch_size` elements, with the exception of the final batch which will have less if there are insufficient elements left t...
Create an iterator that generates mini - batches extracted from this data source. The batches will have batch_size elements with the exception of the final batch which will have less if there are insufficient elements left to make a complete batch.
def batch_iterator(self, batch_size, shuffle=None, **kwargs): """ Create an iterator that generates mini-batches extracted from this data source. The batches will have `batch_size` elements, with the exception of the final batch which will have less if there are insufficient ele...
Gather a batch of samples by indices * without * applying any index mapping resulting from the ( optional ) use of the indices array passed to the constructor.
def samples_by_indices_nomapping(self, indices): """ Gather a batch of samples by indices *without* applying any index mapping resulting from the (optional) use of the `indices` array passed to the constructor. Parameters ---------- indices: 1D-array of ints or s...
Get the number of samples in this data source.
def num_samples(self, **kwargs): """ Get the number of samples in this data source. Returns ------- int, `np.inf` or `None`. An int if the number of samples is known, `np.inf` if it is infinite or `None` if the number of samples is unknown. """ ...
Gather a batch of samples by indices * without * applying any index mapping.
def samples_by_indices_nomapping(self, indices): """ Gather a batch of samples by indices *without* applying any index mapping. Parameters ---------- indices: list of either 1D-array of ints or slice A list of index arrays or slices; one for each data source ...
Create an iterator that generates mini - batch sample indices
def batch_indices_iterator(self, batch_size, **kwargs): """ Create an iterator that generates mini-batch sample indices The generated mini-batches indices take the form of nested lists of either: - 1D NumPy integer arrays - slices The list nesting structure with...
Gather a batch of samples by indices * without * applying any index mapping.
def samples_by_indices_nomapping(self, indices): """ Gather a batch of samples by indices *without* applying any index mapping. Parameters ---------- indices: a tuple of the form `(dataset_index, sample_indices)` The `dataset_index` identifies the dataset fro...
Create an iterator that generates mini - batch sample indices
def batch_indices_iterator(self, batch_size, shuffle=None, **kwargs): """ Create an iterator that generates mini-batch sample indices The generated mini-batches indices take the form of nested lists of either: - 1D NumPy integer arrays - slices The list nesting ...
Gather a batch of samples by indices * without * applying any index mapping.
def samples_by_indices_nomapping(self, indices): """ Gather a batch of samples by indices *without* applying any index mapping. Parameters ---------- indices: 1D-array of ints or slice An index array or a slice that selects the samples to retrieve Re...
Gather a batch of samples by indices applying any index mapping defined by the underlying data sources.
def samples_by_indices(self, indices): """ Gather a batch of samples by indices, applying any index mapping defined by the underlying data sources. Parameters ---------- indices: 1D-array of ints or slice An index array or a slice that selects the samples to ...
Create an iterator that generates mini - batch sample indices
def batch_indices_iterator(self, batch_size, **kwargs): """ Create an iterator that generates mini-batch sample indices The generated mini-batches indices take the form of nested lists of either: - 1D NumPy integer arrays - slices The list nesting structure with...
Purge environment database and uploaded files
def purge(opts): """Purge environment database and uploaded files Usage: datacats purge [-s NAME | --delete-environment] [-y] [ENVIRONMENT] Options: --delete-environment Delete environment directory as well as its data, as well as the data for **all** sites. -s --site=NAME ...
Print the error message to stdout with colors and borders
def pretty_print(self): """ Print the error message to stdout with colors and borders """ print colored.blue("-" * 40) print colored.red("datacats: problem was encountered:") print self.message print colored.blue("-" * 40)
Return a 16 - character alphanumeric random string generated by the operating system s secure pseudo random number generator
def generate_password(): """ Return a 16-character alphanumeric random string generated by the operating system's secure pseudo random number generator """ chars = uppercase + lowercase + digits return ''.join(SystemRandom().choice(chars) for x in xrange(16))
This method calls to docker - machine on the command line and makes sure that it is up and ready.
def _machine_check_connectivity(): """ This method calls to docker-machine on the command line and makes sure that it is up and ready. Potential improvements to be made: - Support multiple machine names (run a `docker-machine ls` and then see which machines are active. Use a priority li...
ro and rw { localdir: binddir } dicts to docker - py s { localdir: { bind: binddir ro: T/ F }} binds dicts
def ro_rw_to_binds(ro, rw): """ ro and rw {localdir: binddir} dicts to docker-py's {localdir: {'bind': binddir, 'ro': T/F}} binds dicts """ out = {} if ro: for localdir, binddir in ro.iteritems(): out[localdir] = {'bind': binddir, 'ro': True} if rw: for localdir, ...
Run a single command in a web image optionally preloaded with the ckan source and virtual envrionment.
def web_command(command, ro=None, rw=None, links=None, image='datacats/web', volumes_from=None, commit=False, clean_up=False, stream_output=None, entrypoint=None): """ Run a single command in a web image optionally preloaded with the ckan source and virtual envrionment. ...
Wraps web_command function with docker bindings needed to connect to a remote server ( such as datacats. com ) and run commands there ( for example when you want to copy your catalog to that server ).
def remote_server_command(command, environment, user_profile, **kwargs): """ Wraps web_command function with docker bindings needed to connect to a remote server (such as datacats.com) and run commands there (for example, when you want to copy your catalog to that server). The files binded ...
Wrapper for docker create_container start calls
def run_container(name, image, command=None, environment=None, ro=None, rw=None, links=None, detach=True, volumes_from=None, port_bindings=None, log_syslog=False): """ Wrapper for docker create_container, start calls :param log_syslog: bool flag to redirect container's l...
Wrapper for docker remove_container
def remove_container(name, force=False): """ Wrapper for docker remove_container :returns: True if container was found and removed """ try: if not force: _get_docker().stop(name) except APIError: pass try: _get_docker().remove_container(name, force=True)...
Wrapper for docker logs attach commands.
def container_logs(name, tail, follow, timestamps): """ Wrapper for docker logs, attach commands. """ if follow: return _get_docker().attach( name, stdout=True, stderr=True, stream=True ) return _docker.logs( name, ...
Returns a string representation of the logs from a container. This is similar to container_logs but uses the follow option and flattens the logs into a string instead of a generator.
def collect_logs(name): """ Returns a string representation of the logs from a container. This is similar to container_logs but uses the `follow` option and flattens the logs into a string instead of a generator. :param name: The container name to grab logs for :return: A string representation ...
Return generator of pull status objects
def pull_stream(image): """ Return generator of pull status objects """ return (json.loads(s) for s in _get_docker().pull(image, stream=True))