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: cmdlist.append('-v') cmdlist.extend(['<', util.shell_quote(os.path.abspath(archive))]) return (cmdlist, {'cwd': outdir, 'shell': 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 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') cmdlist.extend([">", util.shell_quote(archive)]) return (cmdlist, {'shell': 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 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) data = gzipfile.read(READ_SIZE_BYTES) except Exception as err: msg = "error extracting %s to %s: %s" % (archive, targetname, err) raise util.PatoolError(msg) 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 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) while data: gzipfile.write(data) data = srcfile.read(READ_SIZE_BYTES) except Exception as err: msg = "error creating %s: %s" % (archive, err) raise util.PatoolError(msg) 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 _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(data) data = lzmafile.read(READ_SIZE_BYTES) except Exception as err: msg = "error extracting %s to %s: %s" % (archive, targetname, err) raise util.PatoolError(msg) 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 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: data = srcfile.read(READ_SIZE_BYTES) while data: lzmafile.write(data) data = srcfile.read(READ_SIZE_BYTES) except Exception as err: msg = "error creating %s: %s" % (archive, err) raise util.PatoolError(msg) 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 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_secure() and not allow_non_ssl: return HttpResponseRedirect( request.build_absolute_uri().replace('http://', 'https://')) return view_func(request, *args, **kwargs) return _checkssl 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 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)) 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 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 with advanced optional parameters To attach non-file content (e.g. content not saved on disk), use files_manually parameter and provide list of 3 element tuples, e.g. [('design.png', img_data, 'image/png'),] which will be passed to email.attach(). """
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, bcc, cc=cc) if html: email.content_subtype = "html" if files: for file in files: email.attach_file(file) if files_manually: for filename, content, mimetype in files_manually: email.attach(filename, content, mimetype) if reply_to: email.extra_headers = {'Reply-To': reply_to} email.send() except Exception as e: # TODO: Raise error again so that more information is included in the logs? logging.error('Error sending message [{0}] from {1} to {2} {3}'.format( subject, from_email, recipient_emails, 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 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[needed_metas] # nope: compute, memoize and return needed conflict-solving meta elif not needed_metas: # wee, a trivial case, happy us meta = type elif len(needed_metas) == 1: # another trivial case meta = needed_metas[0] # check for recursion, can happen i.e. for Zope ExtensionClasses elif needed_metas == bases: raise TypeError("Incompatible root metatypes", needed_metas) else: # gotta work ... metaname = '_' + ''.join([m.__name__ for m in needed_metas]) meta = classmaker()(metaname, needed_metas, {}) memoized_metaclasses_map[needed_metas] = meta return meta
<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): pass except: logging.critical("Error in watching pubsub get message: \n%s" % traceback.format_exc()) 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 from_edgerc(rcinput, section='default'): """Returns an EdgeGridAuth object from the configuration from the given section of the given edgerc file. :param filename: path to the edgerc file :param section: the section to use (this is the [bracketed] part of the edgerc, default is 'default') """
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_token=rc.get(section, 'access_token'), headers_to_sign=rc.getlist(section, 'headers_to_sign'), max_body=rc.getint(section, 'max_body') )
<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'] = self.__raw['0']['time'] return 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 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: result[i[0]] = str(i[1]).decode('utf-8') except ValueError: if i[0] == 'UPDATE': self.last_update = str(i[1]).decode('utf-8') else: pass return 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 __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]?') for i in csv_data: if check_words.match(i[2]): try: result[i[2]].append(i[0].decode('utf-8')) except (ValueError, KeyError): try: result[i[2]] = [i[0].decode('utf-8')] except KeyError: pass return 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 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']: # 判對是否為法定開市 return True else: if time.weekday() <= 4: # 判斷是否為平常日開市 return True else: 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 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 plugin, will cause the decorated test to be retried until min_passes successes are achieved out of up to max_runs test runs. :param max_runs: The maximum number of times the decorated test will be run. :type max_runs: `int` :param min_passes: The minimum number of times the test must pass to be a success. :type min_passes: `int` :param rerun_filter: Filter function to decide whether a test should be rerun if it fails. Function signature is as follows: (err, name, test, plugin) -> should_rerun - err (`tuple` of `class`, :class:`Exception`, `traceback`): Information about the test failure (from sys.exc_info()) - name (`unicode`): The test name - test (:class:`nose.case.Test` or :class:`Function`): The test that has raised an error - plugin (:class:`FlakyNosePlugin` or :class:`FlakyPytestPlugin`): The flaky plugin. Has a :prop:`stream` that can be written to in order to add to the Flaky Report. :type rerun_filter: `callable` :return: A wrapper function that includes attributes describing the flaky test. :rtype: `callable` """
# 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 = default_flaky_attributes(max_runs, min_passes, rerun_filter) def wrapper(wrapped_object): for name, value in attrib.items(): setattr(wrapped_object, name, value) return wrapped_object return wrapper(wrapped) if wrapped is not None else 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 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) parser.add_option_group(group)
<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 a multiprocess-list backed StringIO proxy; otherwise, use the default stream. :param multiprocess: Whether or not this test run is configured for multiprocessing. :type multiprocess: `bool` :return: The stream to use for storing the flaky report. :rtype: :class:`StringIO` or :class:`MultiprocessingStringIO` """
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._flaky_report = options.flaky_report self._flaky_success_report = options.flaky_success_report self._force_flaky = options.force_flaky self._max_runs = options.max_runs self._min_passes = options.min_passes
<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 error to the nose test result. :param test: The test that has raised an error :type test: :class:`nose.case.Test` :param err: Information about the test failure (from sys.exc_info()) :type err: `tuple` of `class`, :class:`Exception`, `traceback` :return: True, if the test will be rerun; False, if nose should handle it. :rtype: `bool` """
# 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 nose test result. :param test: The test that has raised an error :type test: :class:`nose.case.Test` :param err: Information about the test failure (from sys.exc_info()) :type err: `tuple` of `class`, :class:`Exception`, `traceback` :return: True, if the test will be rerun; False, if nose should handle it. :rtype: `bool` """
# 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 not yet been achieved; retry if necessary. Returning True from this method keeps the test runner from reporting the test as a success; this way we can retry and only report as a success if we have achieved the required number of successes. :param test: The test that has succeeded :type test: :class:`nose.case.Test` :return: True, if the test will be rerun; False, if nose should handle it. :rtype: `bool` """
# 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_reported.add(test_id) # If this test hasn't already been reported as successful, then do it now if not will_handle and test_id in self._tests_that_reran and test_id not in self._tests_that_have_been_reported: self._nose_result.addSuccess(test) return will_handle 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 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: The value of the FlakyNames.MAX_RUNS attribute to use. :type max_runs: `int` :param min_passes: The value of the FlakyNames.MIN_PASSES attribute to use. :type min_passes: `int` :param rerun_filter: Filter function to decide whether a test should be rerun if it fails. :type rerun_filter: `callable` :return: Default flaky attributes to set on a flaky test. :rtype: `dict` """
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: max_runs, FlakyNames.MIN_PASSES: min_passes, FlakyNames.CURRENT_RUNS: 0, FlakyNames.CURRENT_PASSES: 0, FlakyNames.RERUN_FILTER: FilterWrapper(rerun_filter or _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 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: varies :rtype: `unicode` """
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 that the test has failed twice. :param err: Information about the test failure (from sys.exc_info()) :type err: `tuple` of `class`, :class:`Exception`, `traceback` :param flaky: Dictionary of flaky attributes :type flaky: `dict` of `unicode` to varies :param name: The test name :type name: `unicode` """
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: Information about the test failure (from sys.exc_info()) :type err: `tuple` of `class`, :class:`Exception`, `traceback` :param flaky: Dictionary of flaky attributes :type flaky: `dict` of `unicode` to varies :param name: The test name :type name: `unicode` """
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 test runner. Its argspec should equal that of argparse.add_option. :type add_option: `callable` """
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-report', action='store_false', dest='flaky_success_report', default=True, help="Suppress reporting flaky test successes" "in the report at the end of the " "run detailing flaky test results.", )
<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 option to the test runner. Its argspec should equal that of argparse.add_option. :type add_option: `callable` """
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="store", dest="max_runs", type=int, default=2, help="If --force-flaky is specified, we will run each test at " "most this many times (unless the test has its own flaky " "decorator)." ) add_option( '--min-passes', action="store", dest="min_passes", type=int, default=1, help="If --force-flaky is specified, we will run each test at " "least this many times (unless the test has its own flaky " "decorator)." )
<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 report can be written. :type stream: `file` """
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 stderr stream as a byte string, whereas # Python 3 will write to the stream as text. Only encode into a byte # string if the write tries to encode it first and raises a # UnicodeEncodeError. try: stream.write(value) except UnicodeEncodeError: stream.write(value.encode('utf-8', 'replace')) stream.write('\n===End Flaky Test Report===\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 _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 prepared to run :type test: :class:`nose.case.Test` """
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(test_callable, attr, None) if attr_on_callable is not None: cls._set_flaky_attribute(test, attr, attr_on_callable) elif value is not None: cls._set_flaky_attribute(test, attr, 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 _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 which to set the attribute :type test_item: `callable` or :class:`nose.case.Test` or :class:`Function` :param flaky_attribute: The name of the attribute to set :type flaky_attribute: `unicode` """
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 :type test: :class:`nose.case.Test` or :class:`Function` :return: :rtype: `bool` """
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 flaky related attributes. :type test_item: `callable` or :class:`nose.case.Test` or :class:`Function` :return: :rtype: `dict` of `unicode` to varies """
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 connection 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 _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(url, filename)) urlretrieve(url, filename) dataset_listing[name] = '_data/{0}'.format(data.filename) with open(filepath('local_datasets.json'), 'w') as f: json.dump(dataset_listing, f, indent=2, sort_keys=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 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 dataset locally. If False or if the dataset is not available locally, then load the data from an external URL. """
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)) new_filename = os.path.join(chromedriver_dir, get_chromedriver_filename()) self.copy_file(chromedriver_filename, new_filename) else: chromedriver_bin = get_chromedriver_filename() chromedriver_filename = os.path.join(chromedriver_dir, chromedriver_bin) if not os.path.isfile(chromedriver_filename): print("\nDownloading Chromedriver...\n") if not os.path.isdir(chromedriver_dir): os.mkdir(chromedriver_dir) url = get_chromedriver_url() try: response = urlopen(url) if response.getcode() != 200: raise URLError('Not Found') except URLError: raise RuntimeError('Failed to download chromedriver archive: {}'.format(url)) archive = BytesIO(response.read()) with zipfile.ZipFile(archive) as zip_file: zip_file.extract(chromedriver_bin, chromedriver_dir) else: print("\nChromedriver already installed at {}...\n".format(chromedriver_filename)) if not os.access(chromedriver_filename, os.X_OK): os.chmod(chromedriver_filename, 0o744) build_py.run(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 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_CLOSE, exc), self) except Exception: log.exception("Exception in close handler.")
<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 certificate, as a byte string. :returns: A loaded :class:`TrustedCertEntry` instance, ready to be placed in a keystore. """
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) return tke
<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 :param list certs: An list of certificates, as byte strings. The first one should be the one belonging to the private key, the others the chain (in correct order). :param str key: A byte string containing the private key in the format specified in the key_format parameter (default pkcs8). :param str key_format: The format of the provided private key. Valid options are pkcs8 or rsa_raw. Defaults to pkcs8. :returns: A loaded :class:`PrivateKeyEntry` instance, ready to be placed in a keystore. :raises UnsupportedKeyFormatException: If the key format is unsupported. """
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 alias = alias.lower(), cert_chain = cert_chain) if key_format == 'pkcs8': private_key_info = decoder.decode(key, asn1Spec=rfc5208.PrivateKeyInfo())[0] pke._algorithm_oid = private_key_info['privateKeyAlgorithm']['algorithm'].asTuple() pke.pkey = private_key_info['privateKey'].asOctets() pke.pkey_pkcs8 = key elif key_format == 'rsa_raw': pke._algorithm_oid = RSA_ENCRYPTION_OID # We must encode it to pkcs8 private_key_info = rfc5208.PrivateKeyInfo() private_key_info.setComponentByName('version','v1') a = AlgorithmIdentifier() a.setComponentByName('algorithm', pke._algorithm_oid) a.setComponentByName('parameters', '\x05\x00') private_key_info.setComponentByName('privateKeyAlgorithm', a) private_key_info.setComponentByName('privateKey', key) pke.pkey_pkcs8 = encoder.encode(private_key_info, ifNotEmpty=True) pke.pkey = key else: raise UnsupportedKeyFormatException("Key Format '%s' is not supported" % key_format) return pke
<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 going to be used later. Has no effect if the entry is already encrypted. :param str key_password: The password to encrypt the entry with. """
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 = rfc5208.EncryptedPrivateKeyInfo() epki.setComponentByName('encryptionAlgorithm',a) epki.setComponentByName('encryptedData', encrypted_private_key) self._encrypted = encoder.encode(epki) self._pkey = None self._pkey_pkcs8 = None self._algorithm_oid = 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 new(cls, alias, sealed_obj, algorithm, key, key_size): """ Helper function to create a new SecretKeyEntry. :returns: A loaded :class:`SecretKeyEntry` instance, ready to be placed in a keystore. """
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 options are jks or jceks. :param list store_entries: Existing entries that should be added to the keystore. :returns: A loaded :class:`KeyStore` instance, with the specified entries. :raises DuplicateAliasException: If some of the entries have the same alias. :raises UnsupportedKeyStoreTypeException: If the keystore is of an unsupported type :raises UnsupportedKeyStoreEntryTypeException: If some of the keystore entries are unsupported (in this keystore type) """
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 UnsupportedKeystoreEntryTypeException("Entries must be a KeyStore Entry") if store_type != 'jceks' and isinstance(entry, SecretKeyEntry): raise UnsupportedKeystoreEntryTypeException('Secret Key only allowed in JCEKS keystores') alias = entry.alias if alias in entries: raise DuplicateAliasException("Found duplicate alias '%s'" % alias) entries[alias] = entry return cls(store_type, entries)
<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 encrypted with the same password as the keystore. :param str store_password: Password for the created keystore (and for any unencrypted keys) :returns: A byte string representation of the keystore. :raises UnsupportedKeystoreTypeException: If the keystore is of an unsupported type :raises UnsupportedKeystoreEntryTypeException: If the keystore contains an unsupported entry type """
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") keystore += b4.pack(2) # version 2 keystore += b4.pack(len(self.entries)) for alias, item in self.entries.items(): if isinstance(item, TrustedCertEntry): keystore += self._write_trusted_cert(alias, item) elif isinstance(item, PrivateKeyEntry): keystore += self._write_private_key(alias, item, store_password) elif isinstance(item, SecretKeyEntry): if self.store_type != 'jceks': raise UnsupportedKeystoreEntryTypeException('Secret Key only allowed in JCEKS keystores') raise NotImplementedError("Saving of Secret Keys not implemented") else: raise UnsupportedKeystoreEntryTypeException("Unknown entry type in keystore") hash_fn = hashlib.sha1 store_password_utf16 = store_password.encode('utf-16be') hash = hash_fn(store_password_utf16 + SIGNATURE_WHITENING + keystore).digest() keystore += hash return keystore
<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 given class name. """
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 bytes(iv + data + check)
<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 left-padded with 0 bits to form a multiple of 8. """
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] result.append(byte) return bytes(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 _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 BksKeyEntry."""
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_format, key_algorithm, key_enc, store_type=store_type) return entry, pos
<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 (num_columns, num_rows) """
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 for {}).'.format(TILE_LIMIT, number_tiles))
<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_LIMIT, col)) if row < 2 : raise ValueError('Number of rows must be between 2 and {} (you \ asked for {}).'.format(SPLIT_LIMIT, 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 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 of the image to split. number_tiles (int): The number of tiles required. Kwargs: save (bool): Whether or not to save tiles to disk. Returns: Tuple of :class:`Tile` instances. """
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) columns = col rows = row extras = (columns * rows) - number_tiles tile_w, tile_h = int(floor(im_w / columns)), int(floor(im_h / rows)) tiles = [] number = 1 for pos_y in range(0, im_h - rows, tile_h): # -rows for rounding error. for pos_x in range(0, im_w - columns, tile_w): # as above. area = (pos_x, pos_y, pos_x + tile_w, pos_y + tile_h) image = im.crop(area) position = (int(floor(pos_x / tile_w)) + 1, int(floor(pos_y / tile_h)) + 1) coords = (pos_x, pos_y) tile = Tile(image, number, position, coords) tiles.append(tile) number += 1 if save: save_tiles(tiles, prefix=get_basename(filename), directory=os.path.dirname(filename)) return tuple(tiles)
<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_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_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, umax) except: pass try: smin = -(1 << size) + se.min(expr, extra_constraints=[claripy.Extract(size-1,size-1,expr) == 1]) smax = -(1 << size) + se.max(expr, extra_constraints=[claripy.Extract(size-1,size-1,expr) == 1]) return (smin, smax) except: pass return None else: try: umax = se.max(expr, extra_constraints=[claripy.Extract(size-1,size-1,expr) == 0]) smin = 0 try: smin = -(1 << size) + se.min(expr, extra_constraints=[claripy.Extract(size-1,size-1,expr) == 1]) except: pass return (smin, umax) except: pass 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 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 file exists, False otherwise. """
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 Returns ------- np.ma.array Masked array containing raster values """
#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 values """
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, optional Scaling factor maxdim : int, optional Maximum dimension along either axis, in pixels Returns ------- ns Numper of samples in subsampled output nl Numper of lines in subsampled output scale Final scaling factor """
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)) nl = int(round(nl/scale)) return ns, nl, 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 with large rasters Uses buf_xsize and buf_ysize options from GDAL ReadAsArray method. Parameters ds : gdal.Dataset Input GDAL Datset bnum : int, optional Band number scale : int, optional Scaling factor maxdim : int, optional Maximum dimension along either axis, in pixels Returns ------- np.ma.array Masked array containing raster values """
#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) out = bma if return_ds: dtype = src_ds.GetRasterBand(1).DataType src_ds_sub = gdal.GetDriverByName('MEM').Create('', ns, nl, 1, dtype) gt = np.array(src_ds.GetGeoTransform()) gt[[1,5]] = gt[[1,5]]*scale src_ds_sub.SetGeoTransform(list(gt)) src_ds_sub.SetProjection(src_ds.GetProjection()) b = src_ds_sub.GetRasterBand(1) b.WriteArray(bma) b.SetNoDataValue(b_ndv) out = (bma, src_ds_sub) 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 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 : np.array or np.ma.array Input array dst_fn : str Output filename src_ds: GDAL Dataset, optional Source Dataset to use for creating copy bnum : int, optional Output band ndv : float, optional Output NoData Value gt : list, optional Output GeoTransform proj : str, optional Output Projection (OGC WKT or PROJ.4 format) create : bool, optional Create new dataset sparse : bool, optional Output should be created with sparse options """
#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 specified if ndv is not None: a.set_fill_value(ndv) driver = gtif_drv #Currently only support writing singleband rasters #if a.ndim > 2: # np_nbands = a.shape[2] # if src_ds.RasterCount np_nbands: # for bnum in np_nbands: nbands = 1 np_dt = a.dtype.name if src_ds is not None: #If this is a fn, get a ds #Note: this saves a lot of unnecessary iolib.fn_getds calls if isinstance(src_ds, str): src_ds = fn_getds(src_ds) #if isinstance(src_ds, gdal.Dataset): src_dt = gdal.GetDataTypeName(src_ds.GetRasterBand(bnum).DataType) src_gt = src_ds.GetGeoTransform() #This is WKT src_proj = src_ds.GetProjection() #src_srs = osr.SpatialReference() #src_srs.ImportFromWkt(src_ds.GetProjectionRef()) #Probably a cleaner way to handle this if gt is None: gt = src_gt if proj is None: proj = src_proj #Need to create a new copy of the default options opt = list(gdal_opt) #Note: packbits is better for sparse data if sparse: opt.remove('COMPRESS=LZW') opt.append('COMPRESS=PACKBITS') #Not sure if VW can handle sparse tif #opt.append('SPARSE_OK=TRUE') #Use predictor=3 for floating point data if 'float' in np_dt.lower() and 'COMPRESS=LZW' in opt: opt.append('PREDICTOR=3') #If input ma is same as src_ds, write out array using CreateCopy from existing dataset #if not create and (src_ds is not None) and ((a.shape[0] == src_ds.RasterYSize) and (a.shape[1] == src_ds.RasterXSize) and (np_dt.lower() == src_dt.lower())): #Should compare srs.IsSame(src_srs) if not create and (src_ds is not None) and ((a.shape[0] == src_ds.RasterYSize) and (a.shape[1] == src_ds.RasterXSize) and (np_dt.lower() == src_dt.lower())) and (src_gt == gt) and (src_proj == proj): #Note: third option is strict flag, set to false dst_ds = driver.CreateCopy(dst_fn, src_ds, 0, options=opt) #Otherwise, use Create else: a_dtype = a.dtype gdal_dtype = np2gdal_dtype(a_dtype) if a_dtype.name == 'bool': #Set ndv to 0 a.fill_value = False opt.remove('COMPRESS=LZW') opt.append('COMPRESS=DEFLATE') #opt.append('NBITS=1') #Create(fn, nx, ny, nbands, dtype, opt) dst_ds = driver.Create(dst_fn, a.shape[1], a.shape[0], nbands, gdal_dtype, options=opt) #Note: Need GeoMA here to make this work, or accept gt as argument #Could also do ds creation in calling script if gt is not None: dst_ds.SetGeoTransform(gt) if proj is not None: dst_ds.SetProjection(proj) dst_ds.GetRasterBand(bnum).WriteArray(a.filled()) dst_ds.GetRasterBand(bnum).SetNoDataValue(float(a.fill_value)) dst_ds = 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 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(' <GeometryType>wkbPoint</GeometryType>\n') f.write(' <LayerSRS>%s</LayerSRS>\n' % srs) f.write(' <GeometryField encoding="PointFromColumns" x="%s" y="%s"/>\n' % (x, y)) f.write(' </OGRVRTLayer>\n') f.write('</OGRVRTDataSource>\n') f.close()
<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 as Byte gdal_dt = 1 else: gdal_dt = list(dt_dict.keys())[list(dt_dict.values()).index(d)] else: print("Input must be NumPy array or NumPy dtype") gdal_dt = None return gdal_dt
<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 dtype """
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 must be GDAL Dataset or RasterBand object") return np_dtype
<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 NoDataValue is 0. Parameters b : GDALRasterBand object This is the input band. Returns ------- b_ndv : float NoData value """
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, 1, 1)) #Probably better to use 3/4 corner criterion #if ul == ur == lr == ll: if np.isnan(ul) or ul == lr: b_ndv = ul else: #Assume ndv is 0 b_ndv = 0 elif np.isnan(b_ndv): b_dt = gdal.GetDataTypeName(b.DataType) if 'Float' in b_dt: b_ndv = np.nan else: b_ndv = 0 return 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 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 print("Retrieving: %s" % url) #Add progress bar urlretrieve(url, fn) return 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 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 open(fn, 'wb') as fd: for chunk in r.iter_content(chunk_size): fd.write(chunk)
<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 = HTTPDigestAuth(uname, pw) #wget -A'h8v4*snow_fraction.tif' --user=uname --password=pw return auth
<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 lat/lon/z or x/y/z tags #Should probably do genfromtxt here if header exists and dtype of cols is variable pts = np.loadtxt(fn, delimiter=',', skiprows=skiprows, dtype=None) return pts
<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://stackoverflow.com/questions/23832852/by-which-measures-should-i-set-the-size-of-my-gaussian-filter-in-matlab width1 = 3; sigma1 = (width1-1) / 6; Specify width for smallest feature of interest and determine sigma appropriately sigma is width of 1 std in pixels (not multiplier) scipy and astropy both use cutoff of 4*sigma on either side of kernel - 99.994% 3*sigma on either side of kernel - 99.7% If sigma is specified, filter width will be a multiple of 8 times sigma Alternatively, specify filter size, then compute sigma: sigma = (size - 1) / 8. If size is < the required width for 6-8 sigma, need to use different mode to create kernel mode 'oversample' and 'center' are essentially identical for sigma 1, but very different for sigma 0.3 The sigma/size calculations below should work for non-integer sigma """
#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: size = int(np.floor(size/2)*2 + 1) size = max(size, 3) #Truncate the filter at this many standard deviations. Default is 4.0 truncate = 3.0 if size is not None and sigma is None: sigma = (size - 1) / (2*truncate) elif size is None and sigma is not None: #Round up to nearest odd int size = int(np.ceil((sigma * (2*truncate) + 1)/2)*2 - 1) elif size is None and sigma is None: #Use default parameters sigma = 1 size = int(np.ceil((sigma * (2*truncate) + 1)/2)*2 - 1) size = max(size, 3) kernel = astropy.convolution.Gaussian2DKernel(sigma, x_size=size, y_size=size, mode='oversample') print("Applying gaussian smoothing filter with size %i and sigma %0.3f (sum %0.3f)" % \ (size, sigma, kernel.array.sum())) #This will fill holes #np.nan is float #dem_filt_gauss = astropy.nddata.convolve(dem.astype(float).filled(np.nan), kernel, boundary='fill', fill_value=np.nan) #dem_filt_gauss = astropy.convolution.convolve(dem.astype(float).filled(np.nan), kernel, boundary='fill', fill_value=np.nan) #Added normalization to ensure filtered values are not brightened/darkened if kernelsum != 1 dem_filt_gauss = astropy.convolution.convolve(dem.astype(float).filled(np.nan), kernel, boundary='fill', fill_value=np.nan, normalize_kernel=True) #This will preserve original ndv pixels, applying original mask after filtering if origmask: print("Applying original mask") #Allow filling of interior holes, but use original outer edge if fill_interior: mask = malib.maskfill(dem) else: mask = dem.mask dem_filt_gauss = np.ma.array(dem_filt_gauss, mask=mask, fill_value=dem.fill_value) out = np.ma.fix_invalid(dem_filt_gauss, copy=False, fill_value=dem.fill_value) out.set_fill_value(dem.fill_value.astype(dem.dtype)) return out.astype(dem.dtype)
<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, very fast Needs testing """
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,)) dem2 = np.full(dim, dem.fill_value) offset = (dim - np.array(dem.shape))/2.0 #print offset #dem2[0:dem.shape[0],0:dem.shape[1]] = dem.data dem2[offset[0]:dem.shape[0]+offset[0],offset[1]:dem.shape[1]+offset[1]] = dem.data dem2 = np.ma.masked_equal(dem2, dem.fill_value) #dem2 = dem for n in range(levels): print(dem2.shape) dim = (np.floor(np.array(dem2.shape)/2.0 + 1)*2).astype(int) #dem2 = gauss_fltr_astropy(dem2, size=5, origmask=origmask) #dem2 = gauss_fltr_astropy(dem2, size=5) dem2 = gauss_fltr_astropy(dem2, size=5) #Note: Should use zoom with same bilinear interpolation here for consistency #However, this doesn't respect nan #dem2 = zoom(dem2, 0.5, order=1, prefilter=False, cval=dem.fill_value) dem2 = dem2[::2,::2] if full: print("Resizing to original input dimensions") from scipy.ndimage import zoom for n in range(levels): print(dem2.shape) #Note: order 1 is bilinear dem2 = zoom(dem2, 2, order=1, prefilter=False, cval=dem.fill_value) #dem2 = zoom(dem2, 2**levels, order=1, prefilter=False, cval=dem2.fill_value) print(dem2.shape) #This was for power of 2 offset #offset = (2**levels)/2 #print offset #dem2 = dem2[offset:dem.shape[0]+offset,offset:dem.shape[1]+offset] #Use original offset dem2 = dem2[offset[0]:dem.shape[0]+offset[0],offset[1]:dem.shape[1]+offset[1]] if origmask: print("Applying original mask") #Allow filling of interior holes, but use original outer edge maskfill = malib.maskfill(dem) #dem2 = np.ma.array(dem2, mask=np.ma.getmaskarray(dem)) dem2 = np.ma.array(dem2, mask=maskfill, fill_value=dem.fill_value) return dem2
<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