sentence1 stringlengths 52 3.87M | sentence2 stringlengths 1 47.2k | label stringclasses 1
value |
|---|---|---|
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... | launch interactive shell session with all writable volumes
:param: list of strings to execute instead of bash | entailment |
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... | Install from requirements.txt file found in psrc
:param psrc: name of directory in environment directory | entailment |
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 + ... | Remove uploaded files, postgres db, solr index, venv | entailment |
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
"""
... | :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 | entailment |
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... | Create/replace ~/.datacats/run/proxy-environment and return
entry for ro mount for containers | entailment |
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... | 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 appr... | entailment |
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... | Recompiles less files in an environment.
Usage:
datacats less [ENVIRONMENT]
ENVIRONMENT may be an environment name or a path to an environment directory.
Default: '.' | entailment |
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... | 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 be acquired
target_filename: str or callable
The name of the ... | entailment |
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)
... | Delete the cache (converted files) for a dataset.
Parameters
----------
filenames: str
Filenames of files to delete | entailment |
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... | 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. | entailment |
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
Returns
-------
str or None
The path of the file in BatchUp's temporary directory or None if
the copy failed. | entailment |
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):
... | 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. | entailment |
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... | 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
... | entailment |
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.
""... | 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. | entailment |
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... | 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 --clean Reinstall packages ... | entailment |
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... | 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 to all questions.
Defaul... | entailment |
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
... | 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
ENVIRONMENT may be an environment name or a pat... | entailment |
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
... | 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
As a consequence, mini-batches can b... | entailment |
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 per-sample results.
The function `func` should return the result for each sample in the
mini-batch as an array. To return multiple results (e.g. loss and errors)
return a tuple of arrays (e.... | entailment |
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`
... | 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`
The `sum_axis` arguments tells `mean_batch_map` how to process the
results of `func` before accumulating them:
- If `sum_axis` is `None`... | entailment |
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, ... | 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, it is returned as is.
If it is ... | entailment |
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 ... | 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.
This method is a wrapper around the :func:`batch_map` function... | entailment |
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... | 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 retrieve
Returns
-------
list of arrays
... | entailment |
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-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.
If `shuffle` is `None` or `False` elements will be extra... | entailment |
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... | 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.
If `shuffle` is `None` or `False` el... | entailment |
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... | 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 slice
The samples to retrieve
Returns
---... | entailment |
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.
"""
... | 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. | entailment |
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
... | 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
that identify the samples to access
Returns
... | entailment |
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... | 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 match that of the tree of data sources
rooted at `self`
Pa... | entailment |
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... | 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 from which to draw
samples while `sample_indices` identifies... | entailment |
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 ... | 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 match that of the tree of data sources
rooted at `self`
Pa... | entailment |
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 *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
Returns
-------
nested list of arrays
A min... | entailment |
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 ... | 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 retrieve
Returns
-------
nested li... | entailment |
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... | 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 match that of the tree of data sources
rooted at `self`
Pa... | entailment |
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 ... | 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 Specify a site to be pu... | entailment |
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) | Print the error message to stdout with colors and borders | entailment |
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)) | Return a 16-character alphanumeric random string generated by the
operating system's secure pseudo random number generator | entailment |
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... | 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 list) | entailment |
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, ... | ro and rw {localdir: binddir} dicts to docker-py's
{localdir: {'bind': binddir, 'ro': T/F}} binds dicts | entailment |
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.
... | Run a single command in a web image optionally preloaded with the ckan
source and virtual envrionment.
:param command: command to execute
:param ro: {localdir: binddir} dict for read-only volumes
:param rw: {localdir: binddir} dict for read-write volumes
:param links: links passed to start
:par... | entailment |
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 ... | 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 to the docker image include the user's ssh credentials:
ssh_config file,
... | entailment |
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 create_container, start calls
:param log_syslog: bool flag to redirect container's logs to host's syslog
:returns: container info dict or None if container couldn't be created
Raises PortAllocatedError if container couldn't start on the
requested port. | entailment |
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 remove_container
:returns: True if container was found and removed | entailment |
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,
... | Wrapper for docker logs, attach commands. | entailment |
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 ... | 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 of the logs | entailment |
def pull_stream(image):
"""
Return generator of pull status objects
"""
return (json.loads(s) for s in _get_docker().pull(image, stream=True)) | Return generator of pull status objects | entailment |
def data_only_container(name, volumes):
"""
create "data-only container" if it doesn't already exist.
We'd like to avoid these, but postgres + boot2docker make
it difficult, see issue #5
"""
info = inspect_container(name)
if info:
return
c = _get_docker().create_container(
... | create "data-only container" if it doesn't already exist.
We'd like to avoid these, but postgres + boot2docker make
it difficult, see issue #5 | entailment |
def main():
"""
The main entry point for datacats cli tool
(as defined in setup.py's entry_points)
It parses the cli arguments for corresponding options
and runs the corresponding command
"""
# pylint: disable=bare-except
try:
command_fn, opts = _parse_arguments(sys.argv[1:])
... | The main entry point for datacats cli tool
(as defined in setup.py's entry_points)
It parses the cli arguments for corresponding options
and runs the corresponding command | entailment |
def _subcommand_arguments(args):
"""
Return (subcommand, (possibly adjusted) arguments for that subcommand)
Returns (None, args) when no subcommand is found
Parsing our arguments is hard. Each subcommand has its own docopt
validation, and some subcommands (paster and shell) have positional
opt... | Return (subcommand, (possibly adjusted) arguments for that subcommand)
Returns (None, args) when no subcommand is found
Parsing our arguments is hard. Each subcommand has its own docopt
validation, and some subcommands (paster and shell) have positional
options (some options passed to datacats and oth... | entailment |
def start(environment, opts):
"""Create containers and start serving environment
Usage:
datacats start [-b] [--site-url SITE_URL] [-p|--no-watch] [-s NAME]
[-i] [--syslog] [--address=IP] [ENVIRONMENT [PORT]]
datacats start -r [-b] [--site-url SITE_URL] [-s NAME] [--syslog]
[-i... | Create containers and start serving environment
Usage:
datacats start [-b] [--site-url SITE_URL] [-p|--no-watch] [-s NAME]
[-i] [--syslog] [--address=IP] [ENVIRONMENT [PORT]]
datacats start -r [-b] [--site-url SITE_URL] [-s NAME] [--syslog]
[-i] [--address=IP] [ENVIRONMENT]
Optio... | entailment |
def reload_(environment, opts):
"""Reload environment source and configuration
Usage:
datacats reload [-b] [-p|--no-watch] [--syslog] [-s NAME] [--site-url=SITE_URL]
[-i] [--address=IP] [ENVIRONMENT [PORT]]
datacats reload -r [-b] [--syslog] [-s NAME] [--address=IP] [--site-url=SITE... | Reload environment source and configuration
Usage:
datacats reload [-b] [-p|--no-watch] [--syslog] [-s NAME] [--site-url=SITE_URL]
[-i] [--address=IP] [ENVIRONMENT [PORT]]
datacats reload -r [-b] [--syslog] [-s NAME] [--address=IP] [--site-url=SITE_URL]
[-i] ... | entailment |
def info(environment, opts):
"""Display information about environment and running containers
Usage:
datacats info [-qr] [ENVIRONMENT]
Options:
-q --quiet Echo only the web URL or nothing if not running
ENVIRONMENT may be an environment name or a path to an environment directory.
Default: '.'
"""
... | Display information about environment and running containers
Usage:
datacats info [-qr] [ENVIRONMENT]
Options:
-q --quiet Echo only the web URL or nothing if not running
ENVIRONMENT may be an environment name or a path to an environment directory.
Default: '.' | entailment |
def logs(environment, opts):
"""Display or follow container logs
Usage:
datacats logs [--postgres | --solr | --datapusher] [-s NAME] [-tr] [--tail=LINES] [ENVIRONMENT]
datacats logs -f [--postgres | --solr | --datapusher] [-s NAME] [-r] [ENVIRONMENT]
Options:
--datapusher Show logs for datapusher inst... | Display or follow container logs
Usage:
datacats logs [--postgres | --solr | --datapusher] [-s NAME] [-tr] [--tail=LINES] [ENVIRONMENT]
datacats logs -f [--postgres | --solr | --datapusher] [-s NAME] [-r] [ENVIRONMENT]
Options:
--datapusher Show logs for datapusher instead of web logs
--postgres ... | entailment |
def open_(environment, opts):
# pylint: disable=unused-argument
"""Open web browser window to this environment
Usage:
datacats open [-r] [-s NAME] [ENVIRONMENT]
Options:
-s --site=NAME Choose a site to open [default: primary]
ENVIRONMENT may be an environment name or a path to an environment director... | Open web browser window to this environment
Usage:
datacats open [-r] [-s NAME] [ENVIRONMENT]
Options:
-s --site=NAME Choose a site to open [default: primary]
ENVIRONMENT may be an environment name or a path to an environment directory.
Default: '.' | entailment |
def tweak(environment, opts):
"""Commands operating on environment data
Usage:
datacats tweak --install-postgis [ENVIRONMENT]
datacats tweak --add-redis [ENVIRONMENT]
datacats tweak --admin-password [ENVIRONMENT]
Options:
--install-postgis Install postgis in ckan database
--add-redis Adds re... | Commands operating on environment data
Usage:
datacats tweak --install-postgis [ENVIRONMENT]
datacats tweak --add-redis [ENVIRONMENT]
datacats tweak --admin-password [ENVIRONMENT]
Options:
--install-postgis Install postgis in ckan database
--add-redis Adds redis next time this environment reload... | entailment |
def _split_path(path):
"""
A wrapper around the normal split function that ignores any trailing /.
:return: A tuple of the form (dirname, last) where last is the last element
in the path.
"""
# Get around a quirk in path_split where a / at the end will make the
# dirname (split[0])... | A wrapper around the normal split function that ignores any trailing /.
:return: A tuple of the form (dirname, last) where last is the last element
in the path. | entailment |
def _one_to_two(datadir):
"""After this command, your environment will be converted to format version {}.
and will only work with datacats version exceeding and including 1.0.0.
This migration is necessary to support multiple sites within the same environment.
Your current site will be kept and will be named "prima... | After this command, your environment will be converted to format version {}.
and will only work with datacats version exceeding and including 1.0.0.
This migration is necessary to support multiple sites within the same environment.
Your current site will be kept and will be named "primary".
Would you like to continue ... | entailment |
def _two_to_one(datadir):
"""After this command, your environment will be converted to format version {}
and will not work with Datacats versions beyond and including 1.0.0.
This format version doesn't support multiple sites, and after this only your
"primary" site will be usable, though other sites will be maintai... | After this command, your environment will be converted to format version {}
and will not work with Datacats versions beyond and including 1.0.0.
This format version doesn't support multiple sites, and after this only your
"primary" site will be usable, though other sites will be maintained if you
wish to do a migration... | entailment |
def convert_environment(datadir, version, always_yes):
"""
Converts an environment TO the version specified by `version`.
:param datadir: The datadir to convert.
:param version: The version to convert TO.
:param always_yes: True if the user shouldn't be prompted about the migration.
"""
# Si... | Converts an environment TO the version specified by `version`.
:param datadir: The datadir to convert.
:param version: The version to convert TO.
:param always_yes: True if the user shouldn't be prompted about the migration. | entailment |
def get_history_by_flight_number(self, flight_number, page=1, limit=100):
"""Fetch the history of a flight by its number.
This method can be used to get the history of a flight route by the number.
It checks the user authentication and returns the data accordingly.
Args:
fl... | Fetch the history of a flight by its number.
This method can be used to get the history of a flight route by the number.
It checks the user authentication and returns the data accordingly.
Args:
flight_number (str): The flight number, e.g. AI101
page (int): Optional pag... | entailment |
def get_history_by_tail_number(self, tail_number, page=1, limit=100):
"""Fetch the history of a particular aircraft by its tail number.
This method can be used to get the history of a particular aircraft by its tail number.
It checks the user authentication and returns the data accordingly.
... | Fetch the history of a particular aircraft by its tail number.
This method can be used to get the history of a particular aircraft by its tail number.
It checks the user authentication and returns the data accordingly.
Args:
tail_number (str): The tail number, e.g. VT-ANL
... | entailment |
def get_airports(self, country):
"""Returns a list of all the airports
For a given country this returns a list of dicts, one for each airport, with information like the iata code of the airport etc
Args:
country (str): The country for which the airports will be fetched
Exam... | Returns a list of all the airports
For a given country this returns a list of dicts, one for each airport, with information like the iata code of the airport etc
Args:
country (str): The country for which the airports will be fetched
Example::
from pyflightdata import ... | entailment |
def get_info_by_tail_number(self, tail_number, page=1, limit=100):
"""Fetch the details of a particular aircraft by its tail number.
This method can be used to get the details of a particular aircraft by its tail number.
Details include the serial number, age etc along with links to the images ... | Fetch the details of a particular aircraft by its tail number.
This method can be used to get the details of a particular aircraft by its tail number.
Details include the serial number, age etc along with links to the images of the aircraft.
It checks the user authentication and returns the dat... | entailment |
def get_fleet(self, airline_key):
"""Get the fleet for a particular airline.
Given a airline code form the get_airlines() method output, this method returns the fleet for the airline.
Args:
airline_key (str): The code for the airline on flightradar24
Returns:
A... | Get the fleet for a particular airline.
Given a airline code form the get_airlines() method output, this method returns the fleet for the airline.
Args:
airline_key (str): The code for the airline on flightradar24
Returns:
A list of dicts, one for each aircraft in the ... | entailment |
def get_flights(self, search_key):
"""Get the flights for a particular airline.
Given a full or partial flight number string, this method returns the first 100 flights matching that string.
Please note this method was different in earlier versions. The older versions took an airline code and r... | Get the flights for a particular airline.
Given a full or partial flight number string, this method returns the first 100 flights matching that string.
Please note this method was different in earlier versions. The older versions took an airline code and returned all scheduled flights for that airline... | entailment |
def get_flights_from_to(self, origin, destination):
"""Get the flights for a particular origin and destination.
Given an origin and destination this method returns the upcoming scheduled flights between these two points.
The data returned has the airline, airport and schedule information - this... | Get the flights for a particular origin and destination.
Given an origin and destination this method returns the upcoming scheduled flights between these two points.
The data returned has the airline, airport and schedule information - this is subject to change in future.
Args:
ori... | entailment |
def get_airport_weather(self, iata, page=1, limit=100):
"""Retrieve the weather at an airport
Given the IATA code of an airport, this method returns the weather information.
Args:
iata (str): The IATA code for an airport, e.g. HYD
page (int): Optional page number; for u... | Retrieve the weather at an airport
Given the IATA code of an airport, this method returns the weather information.
Args:
iata (str): The IATA code for an airport, e.g. HYD
page (int): Optional page number; for users who are on a plan with flightradar24 they can pass in higher p... | entailment |
def get_airport_metars(self, iata, page=1, limit=100):
"""Retrieve the metar data at the current time
Given the IATA code of an airport, this method returns the metar information.
Args:
iata (str): The IATA code for an airport, e.g. HYD
page (int): Optional page number;... | Retrieve the metar data at the current time
Given the IATA code of an airport, this method returns the metar information.
Args:
iata (str): The IATA code for an airport, e.g. HYD
page (int): Optional page number; for users who are on a plan with flightradar24 they can pass in h... | entailment |
def get_airport_metars_hist(self, iata):
"""Retrieve the metar data for past 72 hours. The data will not be parsed to readable format.
Given the IATA code of an airport, this method returns the metar information for last 72 hours.
Args:
iata (str): The IATA code for an airport, e.g... | Retrieve the metar data for past 72 hours. The data will not be parsed to readable format.
Given the IATA code of an airport, this method returns the metar information for last 72 hours.
Args:
iata (str): The IATA code for an airport, e.g. HYD
Returns:
The metar data f... | entailment |
def get_airport_stats(self, iata, page=1, limit=100):
"""Retrieve the performance statistics at an airport
Given the IATA code of an airport, this method returns the performance statistics for the airport.
Args:
iata (str): The IATA code for an airport, e.g. HYD
page (i... | Retrieve the performance statistics at an airport
Given the IATA code of an airport, this method returns the performance statistics for the airport.
Args:
iata (str): The IATA code for an airport, e.g. HYD
page (int): Optional page number; for users who are on a plan with fligh... | entailment |
def get_airport_details(self, iata, page=1, limit=100):
"""Retrieve the details of an airport
Given the IATA code of an airport, this method returns the detailed information like lat lon, full name, URL, codes etc.
Args:
iata (str): The IATA code for an airport, e.g. HYD
... | Retrieve the details of an airport
Given the IATA code of an airport, this method returns the detailed information like lat lon, full name, URL, codes etc.
Args:
iata (str): The IATA code for an airport, e.g. HYD
page (int): Optional page number; for users who are on a plan wit... | entailment |
def get_images_by_tail_number(self, tail_number, page=1, limit=100):
"""Fetch the images of a particular aircraft by its tail number.
This method can be used to get the images of the aircraft. The images are in 3 sizes and you can use what suits your need.
Args:
tail_number (str): ... | Fetch the images of a particular aircraft by its tail number.
This method can be used to get the images of the aircraft. The images are in 3 sizes and you can use what suits your need.
Args:
tail_number (str): The tail number, e.g. VT-ANL
page (int): Optional page number; for u... | entailment |
def login(self, email, password):
"""Login to the flightradar24 session
The API currently uses flightradar24 as the primary data source. The site provides different levels of data based on user plans.
For users who have signed up for a plan, this method allows to login with the credentials from... | Login to the flightradar24 session
The API currently uses flightradar24 as the primary data source. The site provides different levels of data based on user plans.
For users who have signed up for a plan, this method allows to login with the credentials from flightradar24. The API obtains
a tok... | entailment |
def decode_metar(self, metar):
"""
Simple method that decodes a given metar string.
Args:
metar (str): The metar data
Returns:
The metar data in readable format
Example::
from pyflightdata import FlightData
f=FlightData()
... | Simple method that decodes a given metar string.
Args:
metar (str): The metar data
Returns:
The metar data in readable format
Example::
from pyflightdata import FlightData
f=FlightData()
f.decode_metar('WSSS 181030Z 04009KT 010V080 ... | entailment |
def _get_auth_packet(self, username, password, client):
"""
Get the pyrad authentication packet for the username/password and the
given pyrad client.
"""
pkt = client.CreateAuthPacket(code=AccessRequest,
User_Name=username)
pkt["User-... | Get the pyrad authentication packet for the username/password and the
given pyrad client. | entailment |
def _get_client(self, server):
"""
Get the pyrad client for a given server. RADIUS server is described by
a 3-tuple: (<hostname>, <port>, <secret>).
"""
return Client(
server=server[0],
authport=server[1],
secret=server[2],
dict=sel... | Get the pyrad client for a given server. RADIUS server is described by
a 3-tuple: (<hostname>, <port>, <secret>). | entailment |
def _perform_radius_auth(self, client, packet):
"""
Perform the actual radius authentication by passing the given packet
to the server which `client` is bound to.
Returns True or False depending on whether the user is authenticated
successfully.
"""
try:
... | Perform the actual radius authentication by passing the given packet
to the server which `client` is bound to.
Returns True or False depending on whether the user is authenticated
successfully. | entailment |
def _radius_auth(self, server, username, password):
"""
Authenticate the given username/password against the RADIUS server
described by `server`.
"""
client = self._get_client(server)
packet = self._get_auth_packet(username, password, client)
return self._perform_... | Authenticate the given username/password against the RADIUS server
described by `server`. | entailment |
def get_django_user(self, username, password=None):
"""
Get the Django user with the given username, or create one if it
doesn't already exist. If `password` is given, then set the user's
password to that (regardless of whether the user was created or not).
"""
try:
... | Get the Django user with the given username, or create one if it
doesn't already exist. If `password` is given, then set the user's
password to that (regardless of whether the user was created or not). | entailment |
def authenticate(self, request, username=None, password=None):
"""
Check credentials against RADIUS server and return a User object or
None.
"""
if isinstance(username, basestring):
username = username.encode('utf-8')
if isinstance(password, basestring):
... | Check credentials against RADIUS server and return a User object or
None. | entailment |
def authenticate(self, request, username=None, password=None, realm=None):
"""
Check credentials against the RADIUS server identified by `realm` and
return a User object or None. If no argument is supplied, Django will
skip this backend and try the next one (as a TypeError will be raised... | Check credentials against the RADIUS server identified by `realm` and
return a User object or None. If no argument is supplied, Django will
skip this backend and try the next one (as a TypeError will be raised
and caught). | entailment |
def move(self, dst):
"Closes then moves the file to dst."
self.close()
shutil.move(self.path, dst) | Closes then moves the file to dst. | entailment |
def sigma_clipping(date, mag, err, threshold=3, iteration=1):
"""
Remove any fluctuated data points by magnitudes.
Parameters
----------
date : array_like
An array of dates.
mag : array_like
An array of magnitudes.
err : array_like
An array of magnitude errors.
t... | Remove any fluctuated data points by magnitudes.
Parameters
----------
date : array_like
An array of dates.
mag : array_like
An array of magnitudes.
err : array_like
An array of magnitude errors.
threshold : float, optional
Threshold for sigma-clipping.
itera... | entailment |
def from_spec(spec):
"""Return a schema object from a spec.
A spec is either a string for a scalar type, or a list of 0 or 1 specs,
or a dictionary with two elements: {'fields': { ... }, required: [...]}.
"""
if spec == '':
return any_schema
if framework.is_str(spec):
# Scalar type
if spec not... | Return a schema object from a spec.
A spec is either a string for a scalar type, or a list of 0 or 1 specs,
or a dictionary with two elements: {'fields': { ... }, required: [...]}. | entailment |
def validate(obj, schema):
"""Validate an object according to its own AND an externally imposed schema."""
if not framework.EvaluationContext.current().validate:
# Short circuit evaluation when disabled
return obj
# Validate returned object according to its own schema
if hasattr(obj, 'tuple_schema'):
... | Validate an object according to its own AND an externally imposed schema. | entailment |
def attach(obj, schema):
"""Attach the given schema to the given object."""
# We have a silly exception for lists, since they have no 'attach_schema'
# method, and I don't feel like making a subclass for List just to add it.
# So, we recursively search the list for tuples and attach the schema in
# there.
... | Attach the given schema to the given object. | entailment |
def get_feature_set_all():
"""
Return a list of entire features.
A set of entire features regardless of being used to train a model or
predict a class.
Returns
-------
feature_names : list
A list of features' names.
"""
features = get_feature_set()
features.append('cu... | Return a list of entire features.
A set of entire features regardless of being used to train a model or
predict a class.
Returns
-------
feature_names : list
A list of features' names. | entailment |
def parameters(self):
""" A property that returns all of the model's parameters. """
parameters = []
for hl in self.hidden_layers:
parameters.extend(hl.parameters)
parameters.extend(self.top_layer.parameters)
return parameters | A property that returns all of the model's parameters. | entailment |
def parameters(self, value):
""" Used to set all of the model's parameters to new values.
**Parameters:**
value : array_like
New values for the model parameters. Must be of length
``self.n_parameters``.
"""
if len(value) != self.n_parameters:
... | Used to set all of the model's parameters to new values.
**Parameters:**
value : array_like
New values for the model parameters. Must be of length
``self.n_parameters``. | entailment |
def checksum(self):
""" Returns an MD5 digest of the model.
This can be used to easily identify whether two models have the
same architecture.
"""
m = md5()
for hl in self.hidden_layers:
m.update(str(hl.architecture))
m.update(str(self.top_la... | Returns an MD5 digest of the model.
This can be used to easily identify whether two models have the
same architecture. | entailment |
def evaluate(self, input_data, targets,
return_cache=False, prediction=True):
""" Evaluate the loss function without computing gradients.
**Parameters:**
input_data : GPUArray
Data to evaluate
targets: GPUArray
Targets
return_cache : b... | Evaluate the loss function without computing gradients.
**Parameters:**
input_data : GPUArray
Data to evaluate
targets: GPUArray
Targets
return_cache : bool, optional
Whether to return intermediary variables from the
computation and the... | entailment |
def training_pass(self, input_data, targets):
""" Perform a full forward and backward pass through the model.
**Parameters:**
input_data : GPUArray
Data to train the model with.
targets : GPUArray
Training targets.
**Returns:**
loss : float
... | Perform a full forward and backward pass through the model.
**Parameters:**
input_data : GPUArray
Data to train the model with.
targets : GPUArray
Training targets.
**Returns:**
loss : float
Value of loss function as evaluated on the data ... | entailment |
def feed_forward(self, input_data, return_cache=False, prediction=True):
""" Run data forward through the model.
**Parameters:**
input_data : GPUArray
Data to run through the model.
return_cache : bool, optional
Whether to return the intermediary results.
... | Run data forward through the model.
**Parameters:**
input_data : GPUArray
Data to run through the model.
return_cache : bool, optional
Whether to return the intermediary results.
prediction : bool, optional
Whether to run in prediction mode. Only r... | entailment |
def shallow_run(self):
"""Derive not-period-based features."""
# Number of data points
self.n_points = len(self.date)
# Weight calculation.
# All zero values.
if not self.err.any():
self.err = np.ones(len(self.mag)) * np.std(self.mag)
# Some zero valu... | Derive not-period-based features. | entailment |
def deep_run(self):
"""Derive period-based features."""
# Lomb-Scargle period finding.
self.get_period_LS(self.date, self.mag, self.n_threads, self.min_period)
# Features based on a phase-folded light curve
# such as Eta, slope-percentile, etc.
# Should be called after t... | Derive period-based features. | entailment |
def get_period_LS(self, date, mag, n_threads, min_period):
"""
Period finding using the Lomb-Scargle algorithm.
Finding two periods. The second period is estimated after whitening
the first period. Calculating various other features as well
using derived periods.
Parame... | Period finding using the Lomb-Scargle algorithm.
Finding two periods. The second period is estimated after whitening
the first period. Calculating various other features as well
using derived periods.
Parameters
----------
date : array_like
An array of obser... | entailment |
def get_period_uncertainty(self, fx, fy, jmax, fx_width=100):
"""
Get uncertainty of a period.
The uncertainty is defined as the half width of the frequencies
around the peak, that becomes lower than average + standard deviation
of the power spectrum.
Since we may not h... | Get uncertainty of a period.
The uncertainty is defined as the half width of the frequencies
around the peak, that becomes lower than average + standard deviation
of the power spectrum.
Since we may not have fine resolution around the peak,
we do not assume it is gaussian. So, ... | entailment |
def residuals(self, pars, x, y, order):
"""
Residual of Fourier Series.
Parameters
----------
pars : array_like
Fourier series parameters.
x : array_like
An array of date.
y : array_like
An array of true values to fit.
... | Residual of Fourier Series.
Parameters
----------
pars : array_like
Fourier series parameters.
x : array_like
An array of date.
y : array_like
An array of true values to fit.
order : int
An order of Fourier Series. | entailment |
def fourier_series(self, pars, x, order):
"""
Function to fit Fourier Series.
Parameters
----------
x : array_like
An array of date divided by period. It doesn't need to be sorted.
pars : array_like
Fourier series parameters.
order : int
... | Function to fit Fourier Series.
Parameters
----------
x : array_like
An array of date divided by period. It doesn't need to be sorted.
pars : array_like
Fourier series parameters.
order : int
An order of Fourier series. | entailment |
def get_stetson_k(self, mag, avg, err):
"""
Return Stetson K feature.
Parameters
----------
mag : array_like
An array of magnitude.
avg : float
An average value of magnitudes.
err : array_like
An array of magnitude errors.
... | Return Stetson K feature.
Parameters
----------
mag : array_like
An array of magnitude.
avg : float
An average value of magnitudes.
err : array_like
An array of magnitude errors.
Returns
-------
stetson_k : float
... | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.