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 extract_flac (archive, compression, cmd, verbosity, interactive, outdir):
"""Decompress a FLAC archive to a WAV file.""" |
outfile = util.get_single_outfile(outdir, archive, extension=".wav")
cmdlist = [cmd, '--decode', archive, '--output-name', outfile]
return cmdlist |
<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_flac (archive, compression, cmd, verbosity, interactive, filenames):
"""Compress a WAV file to a FLAC archive.""" |
cmdlist = [cmd, filenames[0], '--best', '--output-name', archive]
return cmdlist |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def extract_rar (archive, compression, cmd, verbosity, interactive, outdir):
"""Extract a RAR archive.""" |
cmdlist = [cmd, 'x']
if not interactive:
cmdlist.extend(['-p-', '-y'])
cmdlist.extend(['--', os.path.abspath(archive)])
return (cmdlist, {'cwd': outdir}) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def extract_cpio (archive, compression, cmd, verbosity, interactive, outdir):
"""Extract a CPIO archive.""" |
cmdlist = [util.shell_quote(cmd), '--extract', '--make-directories',
'--preserve-modification-time']
if sys.platform.startswith('linux') and not cmd.endswith('bsdcpio'):
cmdlist.extend(['--no-absolute-filenames',
'--force-local', '--nonmatching', r'"*\.\.*"'])
if verbosity > 1:
... |
<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_cpio(archive, compression, cmd, verbosity, interactive, filenames):
"""Create a CPIO archive.""" |
cmdlist = [util.shell_quote(cmd), '--create']
if verbosity > 1:
cmdlist.append('-v')
if len(filenames) != 0:
findcmd = ['find']
findcmd.extend([util.shell_quote(x) for x in filenames])
findcmd.extend(['-print0', '|'])
cmdlist[0:0] = findcmd
cmdlist.append('-0... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def extract_arc (archive, compression, cmd, verbosity, interactive, outdir):
"""Extract a ARC archive.""" |
# Since extracted files will be placed in the current directory,
# the cwd argument has to be the output directory.
cmdlist = [cmd, 'x', os.path.abspath(archive)]
return (cmdlist, {'cwd': outdir}) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def list_arc (archive, compression, cmd, verbosity, interactive):
"""List a ARC archive.""" |
cmdlist = [cmd]
if verbosity > 1:
cmdlist.append('v')
else:
cmdlist.append('l')
cmdlist.append(archive)
return cmdlist |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def extract_gzip (archive, compression, cmd, verbosity, interactive, outdir):
"""Extract a GZIP archive with the gzip Python module.""" |
targetname = util.get_single_outfile(outdir, archive)
try:
with gzip.GzipFile(archive) as gzipfile:
with open(targetname, 'wb') as targetfile:
data = gzipfile.read(READ_SIZE_BYTES)
while data:
targetfile.write(data)
dat... |
<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_gzip (archive, compression, cmd, verbosity, interactive, filenames):
"""Create a GZIP archive with the gzip Python module.""" |
if len(filenames) > 1:
raise util.PatoolError('multi-file compression not supported in Python gzip')
try:
with gzip.GzipFile(archive, 'wb') as gzipfile:
filename = filenames[0]
with open(filename, 'rb') as srcfile:
data = srcfile.read(READ_SIZE_BYTES)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _extract(archive, compression, cmd, format, verbosity, outdir):
"""Extract an LZMA or XZ archive with the lzma Python module.""" |
targetname = util.get_single_outfile(outdir, archive)
try:
with lzma.LZMAFile(archive, **_get_lzma_options(format)) as lzmafile:
with open(targetname, 'wb') as targetfile:
data = lzmafile.read(READ_SIZE_BYTES)
while data:
targetfile.write(... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def extract_lzma(archive, compression, cmd, verbosity, interactive, outdir):
"""Extract an LZMA archive with the lzma Python module.""" |
return _extract(archive, compression, cmd, 'alone', verbosity, outdir) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def extract_xz(archive, compression, cmd, verbosity, interactive, outdir):
"""Extract an XZ archive with the lzma Python module.""" |
return _extract(archive, compression, cmd, 'xz', verbosity, outdir) |
<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(archive, compression, cmd, format, verbosity, filenames):
"""Create an LZMA or XZ archive with the lzma Python module.""" |
if len(filenames) > 1:
raise util.PatoolError('multi-file compression not supported in Python lzma')
try:
with lzma.LZMAFile(archive, mode='wb', **_get_lzma_options(format, preset=9)) as lzmafile:
filename = filenames[0]
with open(filename, 'rb') as srcfile:
... |
<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_lzma(archive, compression, cmd, verbosity, interactive, filenames):
"""Create an LZMA archive with the lzma Python module.""" |
return _create(archive, compression, cmd, 'alone', verbosity, filenames) |
<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_xz(archive, compression, cmd, verbosity, interactive, filenames):
"""Create an XZ archive with the lzma Python module.""" |
return _create(archive, compression, cmd, 'xz', verbosity, filenames) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ssl_required(allow_non_ssl=False):
""" Views decorated with this will always get redirected to https except when allow_non_ssl is set to true. """ |
def wrapper(view_func):
def _checkssl(request, *args, **kwargs):
# allow_non_ssl=True lets non-https requests to come
# through to this view (and hence not redirect)
if hasattr(settings, 'SSL_ENABLED') and settings.SSL_ENABLED \
and not request.is_sec... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def anonymous_required(view, redirect_to=None):
""" Only allow if user is NOT authenticated. """ |
if redirect_to is None:
redirect_to = settings.LOGIN_REDIRECT_URL
@wraps(view)
def wrapper(request, *a, **k):
if request.user and request.user.is_authenticated():
return HttpResponseRedirect(redirect_to)
return view(request, *a, **k)
return wrapper |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def generic_var(self, key, value=None):
""" Stores generic variables in the session prepending it with _GENERIC_VAR_KEY_PREFIX. """ |
return self._get_or_set('{0}{1}'.format(self._GENERIC_VAR_KEY_PREFIX, key), 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 authenticate(self, username=None, password=None, **kwargs):
""" "username" being passed is really email address and being compared to as such. """ |
try:
user = User.objects.get(email=username)
if user.check_password(password):
return user
except (User.DoesNotExist, User.MultipleObjectsReturned):
logging.warning('Unsuccessful login attempt using username/email: {0}'.format(username))
retu... |
<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_arguments(self, parser):
""" Define optional arguments with default values """ |
parser.add_argument('--length', default=self.length,
type=int, help=_('SECRET_KEY length default=%d' % self.length))
parser.add_argument('--alphabet', default=self.allowed_chars,
type=str, help=_('alphabet to use default=%s' % self.allowed_chars)... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def send_mail(subject, message, from_email, recipient_emails, files=None, html=False, reply_to=None, bcc=None, cc=None, files_manually=None):
""" Sends email wit... |
import django.core.mail
try:
logging.debug('Sending mail to: {0}'.format(', '.join(r for r in recipient_emails)))
logging.debug('Message: {0}'.format(message))
email = django.core.mail.EmailMessage(subject, message, from_email, recipient_emails,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def skip_redundant(iterable, skipset=None):
""" Redundant items are repeated items or items in the original skipset. """ |
if skipset is None:
skipset = set()
for item in iterable:
if item not in skipset:
skipset.add(item)
yield item |
<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_noconflict_metaclass(bases, left_metas, right_metas):
""" Not intended to be used outside of this module, unless you know what you are doing. """ |
# make tuple of needed metaclasses in specified priority order
metas = left_metas + tuple(map(type, bases)) + right_metas
needed_metas = remove_redundant(metas)
# return existing confict-solving meta, if any
if needed_metas in memoized_metaclasses_map:
return memoized_metaclasses_map[neede... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def on_api_error_14(self, request):
""" 14. Captcha needed """ |
request.method_params['captcha_key'] = self.get_captcha_key(request)
request.method_params['captcha_sid'] = request.api_error.captcha_sid
return self.send(request) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def on_api_error_15(self, request):
""" 15. Access denied - due to scope """ |
logger.error('Authorization failed. Access token will be dropped')
self.access_token = self.get_access_token()
return self.send(request) |
<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_message(self):
""" Gets the latest object from the backend, and handles unpickling and validation. """ |
try:
m = self.get_from_backend()
if m and m["type"] not in SKIP_TYPES:
return self.decrypt(m["data"])
except AttributeError:
raise Exception("Tried to call get message without having subscribed first!")
except (KeyboardInterrupt, SystemExit):... |
<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_edgerc(rcinput, section='default'):
"""Returns an EdgeGridAuth object from the configuration from the given section of the given edgerc file. :param fil... |
from .edgerc import EdgeRc
if isinstance(rcinput, EdgeRc):
rc = rcinput
else:
rc = EdgeRc(rcinput)
return EdgeGridAuth(
client_token=rc.get(section, 'client_token'),
client_secret=rc.get(section, 'client_secret'),
access_toke... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getlist(self, section, option):
""" returns the named option as a list, splitting the original value by ',' """ |
value = self.get(section, option)
if value:
return value.split(',')
else:
return None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def real(self):
''' Get realtime data
:rtype: dict
:returns: 代碼可以參考:http://goristock.appspot.com/API#apiweight
'''
result = self.__raw['1'].copy()
result['c'] = self.__raw['1']['value']
result['value'] = self.__raw['200']['v2']
result['date'] = 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 importcsv(self):
''' import data from csv '''
csv_path = os.path.join(os.path.dirname(__file__), self.stock_no_files)
with open(csv_path) as csv_file:
csv_data = csv.reader(csv_file)
result = {}
for i in csv_data:
try:
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 __loadindcomps(self):
''' import industry comps '''
csv_path = os.path.join(os.path.dirname(__file__), self.stock_no_files)
with open(csv_path) as csv_file:
csv_data = csv.reader(csv_file)
result = {}
check_words = re.compile(r'^[\d]{2,}[\w]?')
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def caldata(self, time):
''' Market open or not.
:param datetime time: 欲判斷的日期
:rtype: bool
:returns: True 為開市、False 為休市
'''
if time.date() in self.__ocdate['close']: # 判對是否為法定休市
return False
elif time.date() in self.__ocdate['open']: # 判... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def flaky(max_runs=None, min_passes=None, rerun_filter=None):
""" Decorator used to mark a test as "flaky". When used in conjuction with the flaky nosetests plug... |
# In case @flaky is applied to a function or class without arguments
# (and without parentheses), max_runs will refer to the wrapped object.
# In this case, the default value can be used.
wrapped = None
if hasattr(max_runs, '__call__'):
wrapped, max_runs = max_runs, None
attrib = defau... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def options(self, parser, env=os.environ):
""" Base class override. Add options to the nose argument parser. """ |
# pylint:disable=dangerous-default-value
super(FlakyPlugin, self).options(parser, env=env)
self.add_report_option(parser.add_option)
group = OptionGroup(
parser, "Force flaky", "Force all tests to be flaky.")
self.add_force_flaky_options(group.add_option)
par... |
<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_stream(self, multiprocess=False):
""" Get the stream used to store the flaky report. If this nose run is going to use the multiprocess plugin, then use ... |
if multiprocess:
from flaky.multiprocess_string_io import MultiprocessingStringIO
return MultiprocessingStringIO()
return self._stream |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def configure(self, options, conf):
"""Base class override.""" |
super(FlakyPlugin, self).configure(options, conf)
if not self.enabled:
return
is_multiprocess = int(getattr(options, 'multiprocess_workers', 0)) > 0
self._stream = self._get_stream(is_multiprocess)
self._flaky_result = TextTestResult(self._stream, [], 0)
self... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def handleError(self, test, err):
""" Baseclass override. Called when a test raises an exception. If the test isn't going to be rerun again, then report the erro... |
# pylint:disable=invalid-name
want_error = self._handle_test_error_or_failure(test, err)
if not want_error and id(test) in self._tests_that_reran:
self._nose_result.addError(test, err)
return want_error or None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def handleFailure(self, test, err):
""" Baseclass override. Called when a test fails. If the test isn't going to be rerun again, then report the failure to the n... |
# pylint:disable=invalid-name
want_failure = self._handle_test_error_or_failure(test, err)
if not want_failure and id(test) in self._tests_that_reran:
self._nose_result.addFailure(test, err)
return want_failure or None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def addSuccess(self, test):
""" Baseclass override. Called when a test succeeds. Count remaining retries and compare with number of required successes that have ... |
# pylint:disable=invalid-name
will_handle = self._handle_test_success(test)
test_id = id(test)
# If this isn't a rerun, the builtin reporter is going to report it as a success
if will_handle and test_id not in self._tests_that_reran:
self._tests_that_have_been_report... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def default_flaky_attributes(max_runs=None, min_passes=None, rerun_filter=None):
""" Returns the default flaky attributes to set on a flaky test. :param max_runs... |
if max_runs is None:
max_runs = 2
if min_passes is None:
min_passes = 1
if min_passes <= 0:
raise ValueError('min_passes must be positive')
if max_runs < min_passes:
raise ValueError('min_passes cannot be greater than max_runs!')
return {
FlakyNames.MAX_RUNS... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ensure_unicode_string(obj):
""" Return a unicode string representation of the given obj. :param obj: The obj we want to represent in unicode :type obj: varie... |
try:
return unicode_type(obj)
except UnicodeDecodeError:
if hasattr(obj, 'decode'):
return obj.decode('utf-8', 'replace')
return str(obj).decode('utf-8', 'replace') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _report_final_failure(self, err, flaky, name):
""" Report that the test has failed too many times to pass at least min_passes times. By default, this means t... |
min_passes = flaky[FlakyNames.MIN_PASSES]
current_passes = flaky[FlakyNames.CURRENT_PASSES]
message = self._failure_message.format(
current_passes,
min_passes,
)
self._log_test_failure(name, err, message) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _log_intermediate_failure(self, err, flaky, name):
""" Report that the test has failed, but still has reruns left. Then rerun the test. :param err: Informati... |
max_runs = flaky[FlakyNames.MAX_RUNS]
runs_left = max_runs - flaky[FlakyNames.CURRENT_RUNS]
message = self._retry_failure_message.format(
runs_left,
max_runs,
)
self._log_test_failure(name, err, message) |
<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_report_option(add_option):
""" Add an option to the test runner to suppress the flaky report. :param add_option: A function that can add an option to the... |
add_option(
'--no-flaky-report',
action='store_false',
dest='flaky_report',
default=True,
help="Suppress the report at the end of the "
"run detailing flaky test results.",
)
add_option(
'--no-success-flaky... |
<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_force_flaky_options(add_option):
""" Add options to the test runner that force all tests to be flaky. :param add_option: A function that can add an optio... |
add_option(
'--force-flaky',
action="store_true",
dest="force_flaky",
default=False,
help="If this option is specified, we will treat all tests as "
"flaky."
)
add_option(
'--max-runs',
action="... |
<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_flaky_report(self, stream):
""" Baseclass override. Write details about flaky tests to the test report. :param stream: The test stream to which the repo... |
value = self._stream.getvalue()
# If everything succeeded and --no-success-flaky-report is specified
# don't print anything.
if not self._flaky_success_report and not value:
return
stream.write('===Flaky Test Report===\n\n')
# Python 2 will write to the st... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _copy_flaky_attributes(cls, test, test_class):
""" Copy flaky attributes from the test callable or class to the test. :param test: The test that is being pre... |
test_callable = cls._get_test_callable(test)
if test_callable is None:
return
for attr, value in cls._get_flaky_attributes(test_class).items():
already_set = hasattr(test, attr)
if already_set:
continue
attr_on_callable = getattr(t... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _increment_flaky_attribute(cls, test_item, flaky_attribute):
""" Increments the value of an attribute on a flaky test. :param test_item: The test callable on... |
cls._set_flaky_attribute(test_item, flaky_attribute, cls._get_flaky_attribute(test_item, flaky_attribute) + 1) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _has_flaky_attributes(cls, test):
""" Returns True if the test callable in question is marked as flaky. :param test: The test that is being prepared to run :... |
current_runs = cls._get_flaky_attribute(test, FlakyNames.CURRENT_RUNS)
return current_runs is not None |
<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_flaky_attributes(cls, test_item):
""" Get all the flaky related attributes from the test. :param test_item: The test callable from which to get the flak... |
return {
attr: cls._get_flaky_attribute(
test_item,
attr,
) for attr in FlakyNames()
} |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def connection_ok():
"""Check web connection. Returns True if web connection is OK, False otherwise. """ |
try:
urlopen(Dataset.base_url, timeout=1)
# if an index page is ever added, this will pass through
return True
except HTTPError:
# There's no index for BASE_URL so Error 404 is expected
return True
except URLError:
# This is raised if there is no internet con... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _download_datasets():
"""Utility to download datasets into package source""" |
def filepath(*args):
return abspath(join(dirname(__file__), '..', 'vega_datasets', *args))
dataset_listing = {}
for name in DATASETS_TO_DOWNLOAD:
data = Dataset(name)
url = data.url
filename = filepath('_data', data.filename)
print("retrieving data {0} -> {1}".format... |
<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(cls, name):
"""Return an instance of this class or an appropriate subclass""" |
clsdict = {subcls.name: subcls for subcls in cls.__subclasses__()
if hasattr(subcls, 'name')}
return clsdict.get(name, cls)(name) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _infodict(cls, name):
"""load the info dictionary for the given name""" |
info = cls._dataset_info.get(name, None)
if info is None:
raise ValueError('No such dataset {0} exists, '
'use list_datasets() to get a list '
'of available datasets.'.format(name))
return info |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def raw(self, use_local=True):
"""Load the raw dataset from remote URL or local file Parameters use_local : boolean If True (default), then attempt to load the d... |
if use_local and self.is_local:
return pkgutil.get_data('vega_datasets', self.pkg_filename)
else:
return urlopen(self.url).read() |
<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(self):
""" Downloads, unzips and installs chromedriver. If a chromedriver binary is found in PATH it will be copied, otherwise downloaded. """ |
chromedriver_dir = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'chromedriver_binary')
chromedriver_filename = find_binary_in_path(get_chromedriver_filename())
if chromedriver_filename:
print("\nChromedriver already installed at {}...\n".format(chromedriver_filename))
... |
<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_chromedriver_to_path():
""" Appends the directory of the chromedriver binary file to PATH. """ |
chromedriver_dir = os.path.abspath(os.path.dirname(__file__))
if 'PATH' not in os.environ:
os.environ['PATH'] = chromedriver_dir
elif chromedriver_dir not in os.environ['PATH']:
os.environ['PATH'] += utils.get_variable_separator()+chromedriver_dir |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def _remote_close(self, exc=None):
"""close session from remote.""" |
if self.state in (STATE_CLOSING, STATE_CLOSED):
return
log.info("close session: %s", self.id)
self.state = STATE_CLOSING
if exc is not None:
self.exception = exc
self.interrupted = True
try:
await self.handler(SockjsMessage(MSG_CL... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def send(self, msg):
"""send message to client.""" |
assert isinstance(msg, str), "String is required"
if self._debug:
log.info("outgoing message: %s, %s", self.id, str(msg)[:200])
if self.state != STATE_OPEN:
return
self._feed(FRAME_MESSAGE, msg) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def send_frame(self, frm):
"""send message frame to client.""" |
if self._debug:
log.info("outgoing message: %s, %s", self.id, frm[:200])
if self.state != STATE_OPEN:
return
self._feed(FRAME_MESSAGE_BLOB, frm) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def clear(self):
"""Manually expire all sessions in the pool.""" |
for session in list(self.values()):
if session.state != STATE_CLOSED:
await session._remote_closed()
self.sessions.clear()
super(SessionManager, self).clear() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def new(cls, alias, cert):
""" Helper function to create a new TrustedCertEntry. :param str alias: The alias for the Trusted Cert Entry :param str certs: The cer... |
timestamp = int(time.time()) * 1000
tke = cls(timestamp = timestamp,
# Alias must be lower case or it will corrupt the keystore for Java Keytool and Keytool Explorer
alias = alias.lower(),
cert = cert)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def new(cls, alias, certs, key, key_format='pkcs8'):
""" Helper function to create a new PrivateKeyEntry. :param str alias: The alias for the Private Key Entry :... |
timestamp = int(time.time()) * 1000
cert_chain = []
for cert in certs:
cert_chain.append(('X.509', cert))
pke = cls(timestamp = timestamp,
# Alias must be lower case or it will corrupt the keystore for Java Keytool and Keytool Explorer
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def encrypt(self, key_password):
""" Encrypts the private key, so that it can be saved to a keystore. This will make it necessary to decrypt it again if it is go... |
if not self.is_decrypted():
return
encrypted_private_key = sun_crypto.jks_pkey_encrypt(self.pkey_pkcs8, key_password)
a = AlgorithmIdentifier()
a.setComponentByName('algorithm', sun_crypto.SUN_JKS_ALGO_ID)
a.setComponentByName('parameters', '\x05\x00')
epki... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def new(cls, alias, sealed_obj, algorithm, key, key_size):
""" Helper function to create a new SecretKeyEntry. :returns: A loaded :class:`SecretKeyEntry` instanc... |
timestamp = int(time.time()) * 1000
raise NotImplementedError("Creating Secret Keys not implemented") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def new(cls, store_type, store_entries):
""" Helper function to create a new KeyStore. :param string store_type: What kind of keystore the store should be. Valid... |
if store_type not in ['jks', 'jceks']:
raise UnsupportedKeystoreTypeException("The Keystore Type '%s' is not supported" % store_type)
entries = {}
for entry in store_entries:
if not isinstance(entry, AbstractKeystoreEntry):
raise UnsupportedKeystoreEntry... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def saves(self, store_password):
""" Saves the keystore so that it can be read by other applications. If any of the private keys are unencrypted, they will be en... |
if self.store_type == 'jks':
keystore = MAGIC_NUMBER_JKS
elif self.store_type == 'jceks':
raise NotImplementedError("Saving of JCEKS keystores is not implemented")
else:
raise UnsupportedKeystoreTypeException("Only JKS and JCEKS keystores are supported")
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _java_is_subclass(cls, obj, class_name):
"""Given a deserialized JavaObject as returned by the javaobj library, determine whether it's a subclass of the give... |
clazz = obj.get_class()
while clazz:
if clazz.name == class_name:
return True
clazz = clazz.superclass
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 _adjust(a, a_offset, b):
""" a = bytearray a_offset = int b = bytearray """ |
x = (b[-1] & 0xFF) + (a[a_offset + len(b) - 1] & 0xFF) + 1
a[a_offset + len(b) - 1] = ctypes.c_ubyte(x).value
x >>= 8
for i in range(len(b)-2, -1, -1):
x += (b[i] & 0xFF) + (a[a_offset + i] & 0xFF)
a[a_offset + i] = ctypes.c_ubyte(x).value
x >>= 8 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def jks_pkey_encrypt(key, password_str):
""" Encrypts the private key with password protection algorithm used by JKS keystores. """ |
password_bytes = password_str.encode('utf-16be') # Java chars are UTF-16BE code units
iv = os.urandom(20)
key = bytearray(key)
xoring = zip(key, _jks_keystream(iv, password_bytes))
data = bytearray([d^k for d,k in xoring])
check = hashlib.sha1(bytes(password_bytes + key)).digest()
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 _jks_keystream(iv, password):
"""Helper keystream generator for _jks_pkey_decrypt""" |
cur = iv
while 1:
xhash = hashlib.sha1(bytes(password + cur)) # hashlib.sha1 in python 2.6 does not accept a bytearray argument
cur = bytearray(xhash.digest()) # make sure we iterate over ints in both Py2 and Py3
for byte in cur:
yield byte |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def bitstring_to_bytes(bitstr):
""" Converts a pyasn1 univ.BitString instance to byte sequence of type 'bytes'. The bit string is interpreted big-endian and is l... |
bitlist = list(bitstr)
bits_missing = (8 - len(bitlist) % 8) % 8
bitlist = [0]*bits_missing + bitlist # pad with 0 bits to a multiple of 8
result = bytearray()
for i in range(0, len(bitlist), 8):
byte = 0
for j in range(8):
byte = (byte << 1) | bitlist[i+j]
resul... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _read_bks_key(cls, data, pos, store_type):
"""Given a data stream, attempt to parse a stored BKS key entry at the given position, and return it as a BksKeyEn... |
key_type = b1.unpack_from(data, pos)[0]; pos += 1
key_format, pos = BksKeyStore._read_utf(data, pos, kind="key format")
key_algorithm, pos = BksKeyStore._read_utf(data, pos, kind="key algorithm")
key_enc, pos = BksKeyStore._read_data(data, pos)
entry = BksKeyEntry(key_type, key... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def calc_columns_rows(n):
""" Calculate the number of columns and rows required to divide an image into ``n`` parts. Return a tuple of integers in the format (nu... |
num_columns = int(ceil(sqrt(n)))
num_rows = int(ceil(n / float(num_columns)))
return (num_columns, num_rows) |
<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_combined_size(tiles):
"""Calculate combined size of tiles.""" |
# TODO: Refactor calculating layout to avoid repetition.
columns, rows = calc_columns_rows(len(tiles))
tile_size = tiles[0].image.size
return (tile_size[0] * columns, tile_size[1] * rows) |
<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_image(image, number_tiles):
"""Basic sanity checks prior to performing a split.""" |
TILE_LIMIT = 99 * 99
try:
number_tiles = int(number_tiles)
except:
raise ValueError('number_tiles could not be cast to integer.')
if number_tiles > TILE_LIMIT or number_tiles < 2:
raise ValueError('Number of tiles must be between 2 and {} (you \
asked... |
<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_image_col_row(image , col , row):
"""Basic checks for columns and rows values""" |
SPLIT_LIMIT = 99
try:
col = int(col)
row = int(row)
except:
raise ValueError('columns and rows values could not be cast to integer.')
if col < 2:
raise ValueError('Number of columns must be between 2 and {} (you \
asked for {}).'.format(SPLIT_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def slice(filename, number_tiles=None, col=None, row=None, save=True):
""" Split an image into a specified number of tiles. Args: filename (str):
The filename o... |
im = Image.open(filename)
im_w, im_h = im.size
columns = 0
rows = 0
if not number_tiles is None:
validate_image(im, number_tiles)
columns, rows = calc_columns_rows(number_tiles)
extras = (columns * rows) - number_tiles
else:
validate_image_col_row(im, col, row)
... |
<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_filename(self, directory=os.getcwd(), prefix='tile', format='png', path=True):
"""Construct and return a filename for this tile.""" |
filename = prefix + '_{col:02d}_{row:02d}.{ext}'.format(
col=self.column, row=self.row, ext=format.lower().replace('jpeg', 'jpg'))
if not path:
return filename
return os.path.join(directory, filename) |
<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_columns_rows(filenames):
"""Derive number of columns and rows from filenames.""" |
tiles = []
for filename in filenames:
row, column = os.path.splitext(filename)[0][-5:].split('_')
tiles.append((int(row), int(column)))
rows = [pos[0] for pos in tiles]; columns = [pos[1] for pos in tiles]
num_rows = max(rows); num_columns = max(columns)
return (num_columns, num_row... |
<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_signed_range(se, expr):
""" Calculate the range of the expression with signed boundaries """ |
size = expr.size()
umin = umax = smin = smax = None
if not sat_zero(se, expr):
try:
umin = se.min(expr, extra_constraints=[claripy.Extract(size-1,size-1,expr) == 0])
umax = se.max(expr, extra_constraints=[claripy.Extract(size-1,size-1,expr) == 0])
return (umin, ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fn_check_full(fn):
"""Check for file existence Avoids race condition, but slower than os.path.exists. Parameters fn : str Input filename string. Returns ----... |
status = True
if not os.path.isfile(fn):
status = False
else:
try:
open(fn)
except IOError:
status = False
return status |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fn_getma(fn, bnum=1, return_ds=False):
"""Get masked array from input filename Parameters fn : str Input filename string bnum : int, optional Band number Ret... |
#Add check for filename existence
ds = fn_getds(fn)
out = ds_getma(ds, bnum=bnum)
if return_ds:
out = (out, ds)
return out |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def b_getma(b):
"""Get masked array from input GDAL Band Parameters b : gdal.Band Input GDAL Band Returns ------- np.ma.array Masked array containing raster valu... |
b_ndv = get_ndv_b(b)
#bma = np.ma.masked_equal(b.ReadAsArray(), b_ndv)
#This is more appropriate for float, handles precision issues
bma = np.ma.masked_values(b.ReadAsArray(), b_ndv)
return bma |
<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_sub_dim(src_ds, scale=None, maxdim=1024):
"""Compute dimensions of subsampled dataset Parameters ds : gdal.Dataset Input GDAL Datset scale : int, optiona... |
ns = src_ds.RasterXSize
nl = src_ds.RasterYSize
maxdim = float(maxdim)
if scale is None:
scale_ns = ns/maxdim
scale_nl = nl/maxdim
scale = max(scale_ns, scale_nl)
#Need to check to make sure scale is positive real
if scale > 1:
ns = int(round(ns/scale))
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ds_getma_sub(src_ds, bnum=1, scale=None, maxdim=1024., return_ds=False):
"""Load a subsampled array, rather than full resolution This is useful when working ... |
#print src_ds.GetFileList()[0]
b = src_ds.GetRasterBand(bnum)
b_ndv = get_ndv_b(b)
ns, nl, scale = get_sub_dim(src_ds, scale, maxdim)
#The buf_size parameters determine the final array dimensions
b_array = b.ReadAsArray(buf_xsize=ns, buf_ysize=nl)
bma = np.ma.masked_values(b_array, b_ndv)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def writeGTiff(a, dst_fn, src_ds=None, bnum=1, ndv=None, gt=None, proj=None, create=False, sparse=False):
"""Write input array to disk as GeoTiff Parameters a : ... |
#If input is not np.ma, this creates a new ma, which has default filL_value of 1E20
#Must manually override with ndv
#Also consumes a lot of memory
#Should bypass if input is bool
from pygeotools.lib.malib import checkma
a = checkma(a, fix=False)
#Want to preserve fill_value if already spe... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def writevrt(out_csv,srs='EPSG:4326',x='field_1',y='field_2'):
""" Write out a vrt to accompany a csv of points """ |
out_vrt = os.path.splitext(out_csv)[0]+'.vrt'
out_csv = os.path.split(out_csv)[-1]
f = open(out_vrt, 'w')
f.write('<OGRVRTDataSource>\n')
f.write(' <OGRVRTLayer name="%s">\n' % os.path.splitext(out_csv)[0])
f.write(' <SrcDataSource>%s</SrcDataSource>\n' % out_csv)
f.write(' ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def np2gdal_dtype(d):
""" Get GDAL RasterBand datatype that corresponds with NumPy datatype Input should be numpy array or numpy dtype """ |
dt_dict = gdal_array.codes
if isinstance(d, (np.ndarray, np.generic)):
d = d.dtype
#This creates dtype from another built-in type
#d = np.dtype(d)
if isinstance(d, np.dtype):
if d.name == 'int8':
gdal_dt = 1
elif d.name == 'bool':
#Write out a... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def gdal2np_dtype(b):
""" Get NumPy datatype that corresponds with GDAL RasterBand datatype Input can be filename, GDAL Dataset, GDAL RasterBand, or GDAL integer... |
dt_dict = gdal_array.codes
if isinstance(b, str):
b = gdal.Open(b)
if isinstance(b, gdal.Dataset):
b = b.GetRasterBand(1)
if isinstance(b, gdal.Band):
b = b.DataType
if isinstance(b, int):
np_dtype = dt_dict[b]
else:
np_dtype = None
print("Input m... |
<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_ndv_b(b):
"""Get NoData value for GDAL band. If NoDataValue is not set in the band, extract upper left and lower right pixel values. Otherwise assume NoD... |
b_ndv = b.GetNoDataValue()
if b_ndv is None:
#Check ul pixel for ndv
ns = b.XSize
nl = b.YSize
ul = float(b.ReadAsArray(0, 0, 1, 1))
#ur = float(b.ReadAsArray(ns-1, 0, 1, 1))
lr = float(b.ReadAsArray(ns-1, nl-1, 1, 1))
#ll = float(b.ReadAsArray(0, nl-1, ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cpu_count(logical=True):
"""Return system CPU count """ |
if logical:
from multiprocessing import cpu_count
ncpu=cpu_count()
else:
import psutil
ncpu=psutil.cpu_count(logical=False)
return ncpu |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getfile(url, outdir=None):
"""Function to fetch files using urllib Works with ftp """ |
fn = os.path.split(url)[-1]
if outdir is not None:
fn = os.path.join(outdir, fn)
if not os.path.exists(fn):
#Find appropriate urlretrieve for Python 2 and 3
try:
from urllib.request import urlretrieve
except ImportError:
from urllib import urlretrieve... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getfile2(url, auth=None, outdir=None):
"""Function to fetch files using requests Works with https authentication """ |
import requests
print("Retrieving: %s" % url)
fn = os.path.split(url)[-1]
if outdir is not None:
fn = os.path.join(outdir, fn)
if auth is not None:
r = requests.get(url, stream=True, auth=auth)
else:
r = requests.get(url, stream=True)
chunk_size = 1000000
with op... |
<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_auth():
"""Get authorization token for https """ |
import getpass
from requests.auth import HTTPDigestAuth
#This binds raw_input to input for Python 2
input_func = input
try:
input_func = raw_input
except NameError:
pass
uname = input_func("MODSCAG Username:")
pw = getpass.getpass("MODSCAG Password:")
auth = HTTPDige... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def readcsv(fn):
""" Wrapper to read arbitrary csv, check for header Needs some work to be more robust, quickly added for demcoreg sampling """ |
import csv
#Check first line for header
with open(fn, 'r') as f:
reader = csv.DictReader(f)
hdr = reader.fieldnames
#Assume there is a header on first line, check
skiprows = 1
if np.all(f.isdigit() for f in hdr):
hdr = None
skiprows = 0
#Check header for l... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def absrange_fltr(dem, rangelim):
"""Absolute range filter """ |
out = range_fltr(np.ma.abs(dem), *rangelim)
#Apply mask to original input
out = np.ma.array(dem, mask=np.ma.getmaskarray(out))
out.set_fill_value(dem.fill_value)
return out |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def gauss_fltr_astropy(dem, size=None, sigma=None, origmask=False, fill_interior=False):
"""Astropy gaussian filter properly handles convolution with NaN http://... |
#import astropy.nddata
import astropy.convolution
dem = malib.checkma(dem)
#Generate 2D gaussian kernel for input sigma and size
#Default size is 8*sigma in x and y directions
#kernel = astropy.nddata.make_kernel([size, size], sigma, 'gaussian')
#Size must be odd
if size is not None:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def gauss_fltr_pyramid(dem, size=None, full=False, origmask=False):
"""Pyaramidal downsampling approach for gaussian smoothing Avoids the need for large kernels,... |
dem = malib.checkma(dem)
levels = int(np.floor(np.log2(size)))
#print levels
dim = np.floor(np.array(dem.shape)/float(2**levels) + 1)*(2**levels)
#print dem.shape
#print dim
#Can do something with np.pad here
#np.pad(a_fp.filled(), 1, mode='constant', constant_values=(a_fp.fill_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 gauss_fltr_opencv(dem, size=3, sigma=1):
"""OpenCV Gaussian filter Still propagates NaN values """ |
import cv2
dem = malib.checkma(dem)
dem_cv = cv2.GaussianBlur(dem.filled(np.nan), (size, size), sigma)
out = np.ma.fix_invalid(dem_cv)
out.set_fill_value(dem.fill_value)
return out |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.