text_prompt stringlengths 157 13.1k | code_prompt stringlengths 7 19.8k ⌀ |
|---|---|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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(),
WEB_START_TIMEOUT_SECONDS):
raise DatacatsError('Error while starting web container:\n' +
cont... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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',
sha((self.name + self.site_name)
.decode('ascii')).digest()[:8])[0] % 1000 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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']:
return None
return info['NetworkSettings']['Ports']['5000/tcp'][0]['HostPort']
except TypeError:
r... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 and not is_boot2docker() else docker_host(),
port) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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,
'sysadmin': True},
out)
self.user_run_script(
script=scripts.get_script_pa... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def interactive_shell(self, command=None, paster=False, detach=False):
""" launch interactive shell session with all writable volumes :param: list of strings to ... |
if not exists(self.target + '/.bash_profile'):
# this file is required for activating the virtualenv
self.create_bash_profile()
if not command:
command = []
use_tty = sys.stdin.isatty() and sys.stdout.isatty()
background = environ.get('CIRCLECI', Fa... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def install_package_requirements(self, psrc, stream_output=None):
""" Install from requirements.txt file found in psrc :param psrc: name of directory in environm... |
package = self.target + '/' + psrc
assert isdir(package), package
reqname = '/requirements.txt'
if not exists(package + reqname):
reqname = '/pip-requirements.txt'
if not exists(package + reqname):
return
return self.user_run_script(
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 + '/.version') as f:
format_version = int(f.read().strip())
if format_version == 1:
print 'WARNING: Defaultin... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def less(environment, opts):
# pylint: disable=unused-argument """Recompiles less files in an environment. Usage: datacats less [ENVIRONMENT] ENVIRONMENT may be ... |
require_extra_image(LESSC_IMAGE)
print 'Converting .less files to .css...'
for log in environment.compile_less():
print log |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fetch_and_convert_dataset(source_files, target_filename):
""" Decorator applied to a dataset conversion function that converts acquired source files into a d... |
if not isinstance(target_filename, six.string_types) and \
not callable(target_filename):
raise TypeError(
'target_filename must either be a string or be callable (it is '
'a {})'.format(type(target_filename)))
for src in source_files:
if not isinstance(src,... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 ... |
return config.download_data(self.temp_filename, self.url,
self.sha256) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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... |
if len(self.__result_buffer) > 0:
res = self.__result_buffer.popleft()
value = res.get()
else:
return None
self.__populate_buffer()
return value |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def install(environment, opts):
"""Install or reinstall Python packages within this environment Usage: datacats install -c [q] [--address=IP] [ENVIRONMENT] Optio... |
environment.require_data()
install_all(environment, opts['--clean'], verbose=not opts['--quiet'],
packages=opts['PACKAGE'])
for site in environment.sites:
environment = Environment.load(environment.name, site)
if 'web' in environment.containers_running():
# FIXME: reloa... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def migrate(opts):
"""Migrate an environment to a given revision of the datadir format. Usage: datacats migrate [-y] [-r VERSION] [ENVIRONMENT_DIR] Options: -r -... |
try:
version = int(opts['--revision'])
except:
raise DatacatsError('--revision parameter must be an integer.')
always_yes = opts['--yes']
if 'ENVIRONMENT_DIR' not in opts or not opts['ENVIRONMENT_DIR']:
cwd = getcwd()
# Get the dirname
opts['ENVIRONMENT_DIR'] =... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 trimm... |
if isinstance(batch, tuple):
return tuple([_trim_batch(b, length) for b in batch])
else:
return batch[:length] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 ... |
# Accumulator for results and number of samples
results = []
# If `progress_iter_func` is not `None`, apply it
if progress_iter_func is not None:
batch_iter = progress_iter_func(batch_iter, total=n_batches,
leave=False)
# Apply `func` to each batch
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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... |
# Accumulator for results and number of samples
results_accum = None
n_samples_accum = 0
# If `progress_iter_func` is not `None`, apply it
if progress_iter_func is not None:
batch_iter = progress_iter_func(batch_iter, total=n_batches,
leave=False)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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` i... |
if isinstance(x, AbstractDataSource):
return x
elif isinstance(x, (list, tuple)):
# Sequence of array-likes
items = []
for item in x:
if _is_array_like(item):
items.append(item)
else:
raise TypeError(
'C... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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`. ... |
if n_batches is None:
n = self.num_samples(**kwargs)
if n == np.inf:
raise ValueError('Data set has infinite size or sampler will '
'generate infinite samples but no n_batches '
'limit specified')
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def batch_indices_iterator(self, batch_size, shuffle=None, **kwargs):
""" Create an iterator that generates mini-batch sample indices. The batches will have `bat... |
shuffle_rng = self._get_shuffle_rng(shuffle)
if shuffle_rng is not None:
return self.sampler.shuffled_indices_batch_iterator(
batch_size, shuffle_rng)
else:
return self.sampler.in_order_indices_batch_iterator(batch_size) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def batch_iterator(self, batch_size, shuffle=None, **kwargs):
""" Create an iterator that generates mini-batches extracted from this data source. The batches wil... |
for batch_ndx in self.batch_indices_iterator(
batch_size, shuffle=shuffle, **kwargs):
yield self.samples_by_indices_nomapping(batch_ndx) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 k... |
if self.num_samples_fn is None:
return None
elif callable(self.num_samples_fn):
return self.num_samples_fn(**kwargs)
else:
return self.num_samples_fn |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def samples_by_indices(self, indices):
""" Gather a batch of samples by indices, applying any index mapping defined by the underlying data sources. Parameters in... |
if not self._random_access:
raise TypeError('samples_by_indices method not supported as one '
'or more of the underlying data sources does '
'not support random access')
batch = self.source.samples_by_indices(indices)
return se... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def purge(opts):
"""Purge environment database and uploaded files Usage: datacats purge [-s NAME | --delete-environment] [-y] [ENVIRONMENT] Options: --delete-env... |
old = False
try:
environment = Environment.load(opts['ENVIRONMENT'], opts['--site'])
except DatacatsError:
environment = Environment.load(opts['ENVIRONMENT'], opts['--site'], data_only=True)
if get_format_version(environment.datadir) == 1:
old = True
environm... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 ... |
with open(devnull, 'w') as devnull_f:
try:
status = subprocess.check_output(
['docker-machine', 'status', 'dev'],
stderr=devnull_f).strip()
if status == 'Stopped':
raise DatacatsError('Please start your docker-machine '
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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)... |
binds = ro_rw_to_binds(ro, rw)
c = _get_docker().create_container(
image=image,
command=command,
volumes=binds_to_volumes(binds),
detach=False,
host_config=_get_docker().create_host_config(binds=binds, volumes_from=volumes_from, links=links),
entrypoint=entrypoin... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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)... |
binds = ro_rw_to_binds(ro, rw)
log_config = LogConfig(type=LogConfig.types.JSON)
if log_syslog:
log_config = LogConfig(
type=LogConfig.types.SYSLOG,
config={'syslog-tag': name})
host_config = _get_docker().create_host_config(binds=binds, log_config=log_config, links=link... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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)
return True
except APIError:
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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,
stdout=True,
stderr=True,
tail=tail,
timestamps=timestamps,
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 flat... |
logs = container_logs(name, "all", True, None)
string = ""
for s in logs:
string += s
return string |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pull_stream(image):
""" Return generator of pull status objects """ |
return (json.loads(s) for s in _get_docker().pull(image, stream=True)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 i... |
info = inspect_container(name)
if info:
return
c = _get_docker().create_container(
name=name,
image='datacats/postgres', # any image will do
command='true',
volumes=volumes,
detach=True)
return c |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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... |
# pylint: disable=bare-except
try:
command_fn, opts = _parse_arguments(sys.argv[1:])
# purge handles loading differently
# 1 - Bail and just call the command if it doesn't have ENVIRONMENT.
if command_fn == purge.purge or 'ENVIRONMENT' not in opts:
return command_fn(... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def start(environment, opts):
"""Create containers and start serving environment Usage: datacats start [-b] [--site-url SITE_URL] [-p|--no-watch] [-s NAME] [-i] ... |
environment.require_data()
if environment.fully_running():
print 'Already running at {0}'.format(environment.web_address())
return
reload_(environment, opts) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def reload_(environment, opts):
"""Reload environment source and configuration Usage: datacats reload [-b] [-p|--no-watch] [--syslog] [-s NAME] [--site-url=SITE_... |
if opts['--interactive']:
# We can't wait for the server if we're tty'd
opts['--background'] = True
if opts['--address'] and is_boot2docker():
raise DatacatsError('Cannot specify address on boot2docker.')
environment.require_data()
environment.stop_ckan()
if opts['PORT'] or ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def info(environment, opts):
"""Display information about environment and running containers Usage: datacats info [-qr] [ENVIRONMENT] Options: -q --quiet Echo on... |
damaged = False
sites = environment.sites
if not environment.sites:
sites = []
damaged = True
if opts['--quiet']:
if damaged:
raise DatacatsError('Damaged datadir: cannot get address.')
for site in sites:
environment.site_name = site
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def logs(environment, opts):
"""Display or follow container logs Usage: datacats logs [--postgres | --solr | --datapusher] [-s NAME] [-tr] [--tail=LINES] [ENVIRO... |
container = 'web'
if opts['--solr']:
container = 'solr'
if opts['--postgres']:
container = 'postgres'
if opts['--datapusher']:
container = 'datapusher'
tail = opts['--tail']
if tail != 'all':
tail = int(tail)
l = environment.logs(container, tail, opts['--foll... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def open_(environment, opts):
# pylint: disable=unused-argument """Open web browser window to this environment Usage: datacats open [-r] [-s NAME] [ENVIRONMENT] ... |
environment.require_data()
addr = environment.web_address()
if not addr:
print "Site not currently running"
else:
webbrowser.open(addr) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def tweak(environment, opts):
"""Commands operating on environment data Usage: datacats tweak --install-postgis [ENVIRONMENT] datacats tweak --add-redis [ENVIRON... |
environment.require_data()
if opts['--install-postgis']:
print "Installing postgis"
environment.install_postgis_sql()
if opts['--add-redis']:
# Let the user know if they are trying to add it and it is already there
print ('Adding redis extra container... Please note that yo... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 hist... |
url = FLT_BASE.format(flight_number, str(self.AUTH_TOKEN), page, limit)
return self._fr24.get_data(url) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 t... |
url = REG_BASE.format(tail_number, str(self.AUTH_TOKEN), page, limit)
return self._fr24.get_data(url, True) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 l... |
url = AIRPORT_BASE.format(country.replace(" ", "-"))
return self._fr24.get_airports_data(url) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 g... |
url = REG_BASE.format(tail_number, str(self.AUTH_TOKEN), page, limit)
return self._fr24.get_aircraft_data(url) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 ... |
url = AIRLINE_FLEET_BASE.format(airline_key)
return self._fr24.get_airline_fleet_data(url, self.AUTH_TOKEN != '') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 f... |
# assume limit 100 to return first 100 of any wild card search
url = AIRLINE_FLT_BASE.format(search_key, 100)
return self._fr24.get_airline_flight_data(url) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_flights_from_to(self, origin, destination):
"""Get the flights for a particular origin and destination. Given an origin and destination this method retur... |
# assume limit 100 to return first 100 of any wild card search
url = AIRLINE_FLT_BASE_POINTS.format(origin, destination)
return self._fr24.get_airline_flight_data(url, by_airports=True) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 ... |
url = AIRPORT_DATA_BASE.format(iata, str(self.AUTH_TOKEN), page, limit)
weather = self._fr24.get_airport_weather(url)
mi = weather['sky']['visibility']['mi']
if (mi is not None) and (mi != "None"):
mi = float(mi)
km = mi * 1.6094
weather['sky']['visib... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 ... |
url = AIRPORT_DATA_BASE.format(iata, str(self.AUTH_TOKEN), page, limit)
w = self._fr24.get_airport_weather(url)
return w['metar'] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 ... |
url = AIRPORT_BASE.format(iata) + "/weather"
return self._fr24.get_airport_metars_hist(url) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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... |
url = AIRPORT_DATA_BASE.format(iata, str(self.AUTH_TOKEN), page, limit)
return self._fr24.get_airport_stats(url) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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... |
url = AIRPORT_DATA_BASE.format(iata, str(self.AUTH_TOKEN), page, limit)
details = self._fr24.get_airport_details(url)
weather = self._fr24.get_airport_weather(url)
# weather has more correct and standard elevation details in feet and meters
details['position']['elevation'] = wea... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 ... |
url = REG_BASE.format(tail_number, str(self.AUTH_TOKEN), page, limit)
return self._fr24.get_aircraft_image_data(url) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def login(self, email, password):
"""Login to the flightradar24 session The API currently uses flightradar24 as the primary data source. The site provides differ... |
response = FlightData.session.post(
url=LOGIN_URL,
data={
'email': email,
'password': password,
'remember': 'true',
'type': 'web'
},
headers={
'Origin': 'https://www.flightradar24.com... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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... |
try:
from metar import Metar
except:
return "Unable to parse metars. Please install parser from https://github.com/tomp/python-metar."
m = Metar.Metar(metar)
return m.string() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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... |
try:
reply = client.SendPacket(packet)
except Timeout as e:
logging.error("RADIUS timeout occurred contacting %s:%s" % (
client.server, client.authport))
return False
except Exception as e:
logging.error("RADIUS error: %s" % e)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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):
password = password.encode('utf-8')
server = self._get_server_from_settings()
result = self._radius_auth(server, username, password)
if result... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def move(self, dst):
"Closes then moves the file to dst."
self.close()
shutil.move(self.path, dst) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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... |
# Check length.
if (len(date) != len(mag)) \
or (len(date) != len(err)) \
or (len(mag) != len(err)):
raise RuntimeError('The length of date, mag, and err must be same.')
# By magnitudes
for i in range(int(iteration)):
mean = np.median(mag)
std = np.std(mag)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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, """ |
if spec == '':
return any_schema
if framework.is_str(spec):
# Scalar type
if spec not in SCALAR_TYPES:
raise exceptions.SchemaError('Not a valid schema type: %r' % spec)
return ScalarSchema(spec)
if framework.is_list(spec):
return ListSchema(spec[0] if len(spec) else any_schema)
if... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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'):
obj.tuple_schema.validate(obj)
# Validate object according to externally imposed schema
if schema:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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.
if framework.is_list(obj) and isinstance(schema, ListSchema):
for x in ob... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 -... |
features = get_feature_set()
features.append('cusum')
features.append('eta')
features.append('n_points')
features.append('period_SNR')
features.append('period_log10FAP')
features.append('period_uncertainty')
features.append('weighted_mean')
features.append('weighted_std')
fea... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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.... |
if len(value) != self.n_parameters:
raise ValueError("Incorrect length of parameter vector. "
"Model has %d parameters, but got %d" %
(self.n_parameters, len(value)))
i = 0
for hl in self.hidden_layers:
hl.p... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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_layer.architecture))
return m.hexdigest() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def evaluate(self, input_data, targets, return_cache=False, prediction=True):
""" Evaluate the loss function without computing gradients. **Parameters:** input_d... |
# Forward pass
activations, hidden_cache = self.feed_forward(
input_data, return_cache=True, prediction=prediction)
loss = self.top_layer.train_error(None,
targets, average=False, cache=activations,
prediction=prediction)
for hl in self.hidden_laye... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def training_pass(self, input_data, targets):
""" Perform a full forward and backward pass through the model. **Parameters:** input_data : GPUArray Data to train... |
# Forward pass
loss, hidden_cache, logistic_cache = self.evaluate(
input_data, targets, return_cache=True, prediction=False)
if not np.isfinite(loss):
raise ValueError('Infinite activations!')
# Backpropagation
if self.hidden_layers:
hidden... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def feed_forward(self, input_data, return_cache=False, prediction=True):
""" Run data forward through the model. **Parameters:** input_data : GPUArray Data to ru... |
hidden_cache = None # Create variable in case there are no hidden layers
if self.hidden_layers:
# Forward pass
hidden_cache = []
for i in range(len(self.hidden_layers)):
hidden_activations = hidden_cache[i - 1][0] if i else input_data
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 values.
elif not self.err.all():
np.putmask(self.err, ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 the getPeriodLS() is called.
# Created phased a folded ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 estimat... |
# DO NOT CHANGE THESE PARAMETERS.
oversampling = 3.
hifac = int((max(date) - min(date)) / len(date) / min_period * 2.)
# Minimum hifac
if hifac < 100:
hifac = 100
# Lomb-Scargle.
fx, fy, nout, jmax, prob = pLS.fasper(date, mag, oversampling, hifac,... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 ar... |
# Get subset
start_index = jmax - fx_width
end_index = jmax + fx_width
if start_index < 0:
start_index = 0
if end_index > len(fx) - 1:
end_index = len(fx) - 1
fx_subset = fx[start_index:end_index]
fy_subset = fy[start_index:end_index]
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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. ... |
return y - self.fourier_series(pars, x, order) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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... |
sum = pars[0]
for i in range(order):
sum += pars[i * 2 + 1] * np.sin(2 * np.pi * (i + 1) * x) \
+ pars[i * 2 + 2] * np.cos(2 * np.pi * (i + 1) * x)
return sum |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 magnitud... |
residual = (mag - avg) / err
stetson_k = np.sum(np.fabs(residual)) \
/ np.sqrt(np.sum(residual * residual)) / np.sqrt(len(mag))
return stetson_k |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_eta(self, mag, std):
""" Return Eta feature. Parameters mag : array_like An array of magnitudes. std : array_like A standard deviation of magnitudes. Ret... |
diff = mag[1:] - mag[:len(mag) - 1]
eta = np.sum(diff * diff) / (len(mag) - 1.) / std / std
return eta |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def slope_percentile(self, date, mag):
""" Return 10% and 90% percentile of slope. Parameters date : array_like An array of phase-folded date. Sorted. mag : arra... |
date_diff = date[1:] - date[:len(date) - 1]
mag_diff = mag[1:] - mag[:len(mag) - 1]
# Remove zero mag_diff.
index = np.where(mag_diff != 0.)
date_diff = date_diff[index]
mag_diff = mag_diff[index]
# Derive slope.
slope = date_diff / mag_diff
p... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_cusum(self, mag):
""" Return max - min of cumulative sum. Parameters mag : array_like An array of magnitudes. Returns ------- mm_cusum : float Max - min ... |
c = np.cumsum(mag - self.weighted_mean) / len(mag) / self.weighted_std
return np.max(c) - np.min(c) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def init(device_id=None, random_seed=None):
"""Initialize Hebel. This function creates a CUDA context, CUBLAS context and initializes and seeds the pseudo-random... |
if device_id is None:
random_seed = _os.environ.get('CUDA_DEVICE')
if random_seed is None:
random_seed = _os.environ.get('RANDOM_SEED')
global is_initialized
if not is_initialized:
is_initialized = True
global context
context.init_context(device_id)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def inflate_context_tuple(ast_rootpath, root_env):
"""Instantiate a Tuple from a TupleNode. Walking the AST tree upwards, evaluate from the root down again. """ |
with util.LogTime('inflate_context_tuple'):
# We only need to look at tuple members going down.
inflated = ast_rootpath[0].eval(root_env)
current = inflated
env = root_env
try:
for node in ast_rootpath[1:]:
if is_tuple_member_node(node):
assert framework.is_tuple(current)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_identifier_position(rootpath):
"""Return whether the cursor is in identifier-position in a member declaration.""" |
if len(rootpath) >= 2 and is_tuple_member_node(rootpath[-2]) and is_identifier(rootpath[-1]):
return True
if len(rootpath) >= 1 and is_tuple_node(rootpath[-1]):
# No deeper node than tuple? Must be identifier position, otherwise we'd have a TupleMemberNode.
return True
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def find_completions_at_cursor(ast_tree, filename, line, col, root_env=gcl.default_env):
"""Find completions at the cursor. Return a dict of { name => Completion... |
q = gcl.SourceQuery(filename, line, col - 1)
rootpath = ast_tree.find_tokens(q)
if is_identifier_position(rootpath):
return find_inherited_key_completions(rootpath, root_env)
try:
ret = find_deref_completions(rootpath, root_env) or enumerate_scope(rootpath, root_env=root_env)
assert isinstance(re... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def find_inherited_key_completions(rootpath, root_env):
"""Return completion keys from INHERITED tuples. Easiest way to get those is to evaluate the tuple, check... |
tup = inflate_context_tuple(rootpath, root_env)
if isinstance(tup, runtime.CompositeTuple):
keys = set(k for t in tup.tuples[:-1] for k in t.keys())
return {n: get_completion(tup, n) for n in keys}
return {} |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def find_value_at_cursor(ast_tree, filename, line, col, root_env=gcl.default_env):
"""Find the value of the object under the cursor.""" |
q = gcl.SourceQuery(filename, line, col)
rootpath = ast_tree.find_tokens(q)
rootpath = path_until(rootpath, is_thunk)
if len(rootpath) <= 1:
# Just the file tuple itself, or some non-thunk element at the top level
return None
tup = inflate_context_tuple(rootpath, root_env)
try:
if isinstance(... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_vec_to_mat(mat, vec, axis=None, inplace=False, target=None, substract=False):
""" Add a vector to a matrix """ |
assert mat.flags.c_contiguous
if axis is None:
if vec.shape[0] == mat.shape[0]:
axis = 0
elif vec.shape[0] == mat.shape[1]:
axis = 1
else:
raise ValueError('Vector length must be equal '
'to one side of the matrix')
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def vector_normalize(mat, max_vec_norm=1.):
""" Normalize each column vector in mat to length max_vec_norm if it is longer than max_vec_norm """ |
assert mat.flags.c_contiguous
n, m = mat.shape
vector_normalize_kernel.prepared_call(
(m, 1, 1), (32, 1, 1),
mat.gpudata,
np.float32(max_vec_norm),
np.int32(m),
np.int32(n)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def tokenize_by_number(s):
""" splits a string into a list of tokens each is either a string containing no numbers or a float """ |
r = find_number(s)
if r == None:
return [ s ]
else:
tokens = []
if r[0] > 0:
tokens.append(s[0:r[0]])
tokens.append( float(s[r[0]:r[1]]) )
if r[1] < len(s):
tokens.extend(tokenize_by_number(s[r[1]:]))
return tokens
assert False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def number_aware_alphabetical_cmp(str1, str2):
""" cmp function for sorting a list of strings by alphabetical order, but with numbers sorted numerically. i.e., f... |
def flatten_tokens(tokens):
l = []
for token in tokens:
if isinstance(token, str):
for char in token:
l.append(char)
else:
assert isinstance(token, float)
l.append(token)
return l
seq1 = flatte... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_period_alias(period):
""" Check if a given period is possibly an alias. Parameters period : float A period to test if it is a possible alias or not. Retur... |
# Based on the period vs periodSN plot of EROS-2 dataset (Kim+ 2014).
# Period alias occurs mostly at ~1 and ~30.
# Check each 1, 2, 3, 4, 5 factors.
for i in range(1, 6):
# One-day and one-month alias
if (.99 / float(i)) < period < (1.004 / float(i)):
return True
i... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def save(filepath, obj, on_overwrite = 'ignore'):
""" Serialize `object` to a file denoted by `filepath`. Parameters filepath : str A filename. If the suffix is ... |
filepath = preprocess(filepath)
if os.path.exists(filepath):
if on_overwrite == 'backup':
backup = filepath + '.bak'
shutil.move(filepath, backup)
save(filepath, obj)
try:
os.remove(backup)
except Exception, e:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_pickle_protocol():
""" Allow configuration of the pickle protocol on a per-machine basis. This way, if you use multiple platforms with different versions... |
try:
protocol_str = os.environ['PYLEARN2_PICKLE_PROTOCOL']
except KeyError:
# If not defined, we default to 0 because this is the default
# protocol used by cPickle.dump (and because it results in
# maximum portability)
protocol_str = '0'
if protocol_str == 'pickle.H... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load_train_file(config_file_path):
"""Loads and parses a yaml file for a Train object. Publishes the relevant training environment variables""" |
from pylearn2.config import yaml_parse
suffix_to_strip = '.yaml'
# publish environment variables related to file name
if config_file_path.endswith(suffix_to_strip):
config_file_full_stem = config_file_path[0:-len(suffix_to_strip)]
else:
config_file_full_stem = config_file_path
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def POINTER(obj):
""" Create ctypes pointer to object. Notes ----- This function converts None to a real NULL pointer because of bug in how ctypes handles None o... |
p = ctypes.POINTER(obj)
if not isinstance(p.from_param, classmethod):
def from_param(cls, x):
if x is None:
return cls()
else:
return x
p.from_param = classmethod(from_param)
return p |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def gpuarray_ptr(g):
""" Return ctypes pointer to data in GPUAarray object. """ |
addr = int(g.gpudata)
if g.dtype == np.int8:
return ctypes.cast(addr, POINTER(ctypes.c_byte))
if g.dtype == np.uint8:
return ctypes.cast(addr, POINTER(ctypes.c_ubyte))
if g.dtype == np.int16:
return ctypes.cast(addr, POINTER(ctypes.c_short))
if g.dtype == np.uint16:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cudaMalloc(count, ctype=None):
""" Allocate device memory. Allocate memory on the device associated with the current active context. Parameters count : int N... |
ptr = ctypes.c_void_p()
status = _libcudart.cudaMalloc(ctypes.byref(ptr), count)
cudaCheckStatus(status)
if ctype != None:
ptr = ctypes.cast(ptr, ctypes.POINTER(ctype))
return ptr |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cudaMallocPitch(pitch, rows, cols, elesize):
""" Allocate pitched device memory. Allocate pitched memory on the device associated with the current active con... |
ptr = ctypes.c_void_p()
status = _libcudart.cudaMallocPitch(ctypes.byref(ptr),
ctypes.c_size_t(pitch), cols*elesize,
rows)
cudaCheckStatus(status)
return ptr, pitch |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.