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 summarize(df,preview_rows = 8, display_max_cols = None,display_width = None, output_path = None, output_safe = True,to_folder = False): """ Prints information about the DataFrame to a file or to the prompt. Parameters df - DataFrame The DataFrame to summarize preview_rows - int, default 5 Amount of rows to preview from the head and tail of the DataFrame display_max_cols - int, default None Maximum amount of columns to display. If set to None, all columns will be displayed. If set to 0, only as many as fit in the screen's width will be displayed display_width - int, default None Width of output. Can be width of file or width of console for printing. Set to None for pandas to detect it from console. output_path - path-like, default None If not None, this will be used as the path of the output file, and this function will print to a file instead of to the prompt output_safe - boolean, default True If True and output_file is not None, this function will not overwrite any existing files. output_csv: boolean, default False If True, will output to a directory with name of output_path with all data in csv format. WARNING: If set to true, this function will overwrite existing files in the directory with the following names: ['Preview.csv','Describe.csv','Info.csv','Percentile Details.csv', 'Missing Values Summary.csv','Potential Outliers.csv','Correlation Matrix.csv'] """
assert type(df) is pd.DataFrame # Reformat displays initial_settings = pd_settings(display_max_cols, None, display_width) # --------Values of data----------- df_preview = _io.preview(df,preview_rows) df_desc_num, df_desc_cat = detailed_desc(df) percent_values = stats.percentiles(df) potential_outliers = stats.df_outliers(df).dropna(axis = 1,how = 'all') potential_outliers = potential_outliers if _utils.rows(potential_outliers) else None corr_values = regstats.corr_matrix(df) # ----------Build lists------------ title_list = \ ['Preview','Describe (Numerical)','Describe (Categorical)','Percentile Details', 'Potential Outliers','Correlation Matrix'] info_list = \ [df_preview,df_desc_num, df_desc_cat,percent_values, potential_outliers,corr_values] error_list = [None,'No numerical data.','All numerical data.','No numerical data.', 'No potential outliers.','No categorical, bool, or numerical data.'] # ----------Build output------------ output = '' for title, value,error_text in zip(title_list,info_list,error_list): if value is None: value = "{} skipped: {}".format(title,error_text) if str(value).endswith('\n'): value = value[:-1] output+='{}\n{}\n\n'.format(_io.title_line(title),value) # ----------Send to file/print to console------------ if output_path is None: # Potentially could change this to allow for output_safe to work with directories print(output) else: if not to_folder: print('Outputting to file...') _io.output_to_file(output,output_path,output_safe) else: print('Outputting to folder...') if not os.path.exists(output_path): os.mkdir(output_path) for title, value,error_text in zip(title_list,info_list,error_list): if value is None: print("{} skipped: {}".format(title,error_text)) else: file_dir = os.path.join(output_path,"{}.csv".format(title)) if type(value) is pd.DataFrame: # Eventually add a check to see if file exists value.to_csv(file_dir) else: _io.output_to_file(value,file_dir,False) # Change to output_safe when directory output_safe is implemented print('Done!') # Reset display settings pd_settings(*initial_settings)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def timed_pipe(generator, seconds=3): ''' This is a time limited pipeline. If you have a infinite pipeline and want it to stop yielding after a certain amount of time, use this! ''' # grab the highest precision timer # when it started start = ts() # when it will stop end = start + seconds # iterate over the pipeline for i in generator: # if there is still time if ts() < end: # yield the next item yield i # otherwise else: # stop break
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def destruct(particles, index): """Fermion annihilation operator in matrix representation for a indexed particle in a bounded N-particles fermion fock space"""
mat = np.zeros((2**particles, 2**particles)) flipper = 2**index for i in range(2**particles): ispin = btest(i, index) if ispin == 1: mat[i ^ flipper, i] = phase(i, index) return csr_matrix(mat)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def json_unicode_to_utf8(data): """Change all strings in a JSON structure to UTF-8."""
if isinstance(data, unicode): return data.encode('utf-8') elif isinstance(data, dict): newdict = {} for key in data: newdict[json_unicode_to_utf8( key)] = json_unicode_to_utf8(data[key]) return newdict elif isinstance(data, list): return [json_unicode_to_utf8(elem) for elem in data] else: return data
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def json_decode_file(filename): """ Parses a textfile using json to build a python object representation """
seq = open(filename).read() # The JSON standard has no comments syntax. We have to remove them # before feeding python's JSON parser seq = json_remove_comments(seq) # Parse all the unicode stuff to utf-8 return json_unicode_to_utf8(json.loads(seq))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _post_init(self): """A post init trigger"""
try: return self.postinit() except Exception as exc: return self._onerror(Result.from_exception(exc, uuid=self.uuid))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _postrun(self, result): """ To execute after exection :param kser.result.Result result: Execution result :return: Execution result :rtype: kser.result.Result """
logger.debug( "{}.PostRun: {}[{}]".format( self.__class__.__name__, self.__class__.path, self.uuid ), extra=dict( kmsg=Message( self.uuid, entrypoint=self.__class__.path, params=self.params, metadata=self.metadata ).dump() ) ) return self.postrun(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 execute(self, result=None): """ Execution 'wrapper' to make sure that it return a result :return: Execution result :rtype: kser.result.Result """
try: return self.unsafe_execute(result=result) except Exception as exc: return self._onerror(Result.from_exception(exc, uuid=self.uuid))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_Message(self, result=None): """ Entrypoint -> Message :param kser.result.Result result: Execution result :return: Kafka message :rtype kser.schemas.Message """
return Message( uuid=self.uuid, entrypoint=self.__class__.path, params=self.params, result=result if result else self.result, metadata=self.metadata )
<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_Message(cls, kmsg): """ Message -> Entrypoint :param kser.schemas.Message kmsg: Kafka message :return: a entrypoint :rtype kser.entry.Entrypoint """
return cls( uuid=kmsg.uuid, params=kmsg.params, result=kmsg.result, metadata=kmsg.metadata )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def save_as(self, filename=None): """ Dumps object contents into file on disk. Args: filename (optional): defaults to self.filename. If passed, self.filename will be updated to filename. """
if filename is None: filename = self.filename if filename is None: filename = self.default_filename if filename is None: raise RuntimeError("Class '{}' has no default filename".format(self.__class__.__name__)) self._do_save_as(filename) self.filename = 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 load(self, filename=None): """Loads file and registers filename as attribute."""
assert not self.__flag_loaded, "File can be loaded only once" if filename is None: filename = self.default_filename assert filename is not None, \ "{0!s} class has no default filename".format(self.__class__.__name__) # Convention: trying to open empty file is an error, # because it could be of (almost) any type. size = os.path.getsize(filename) if size == 0: raise RuntimeError("Empty file: '{0!s}'".format(filename)) self._test_magic(filename) self._do_load(filename) self.filename = filename self.__flag_loaded = 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_default(self): """ Initializes object with its default values Tries to load self.default_filename from default data directory. For safety, filename is reset to None so that it doesn't point to the original file. """
import f311 if self.default_filename is None: raise RuntimeError("Class '{}' has no default filename".format(self.__class__.__name__)) fullpath = f311.get_default_data_path(self.default_filename, class_=self.__class__) self.load(fullpath) self.filename = 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 availability(self, availability): """Sets the availability of this Product. :param availability: The availability of this Product. :type: str """
allowed_values = ["available", "comingSoon", "retired"] if availability is not None and availability not in allowed_values: raise ValueError( "Invalid value for `availability` ({0}), must be one of {1}" .format(availability, allowed_values) ) self._availability = availability
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def stock_status(self, stock_status): """Sets the stock_status of this Product. :param stock_status: The stock_status of this Product. :type: str """
allowed_values = ["available", "alert", "unavailable"] if stock_status is not None and stock_status not in allowed_values: raise ValueError( "Invalid value for `stock_status` ({0}), must be one of {1}" .format(stock_status, allowed_values) ) self._stock_status = stock_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 asserts(input_value, rule, message=''): """ this function allows you to write asserts in generators since there are moments where you actually want the program to halt when certain values are seen. """
assert callable(rule) or type(rule)==bool, 'asserts needs rule to be a callable function or a test boolean' assert isinstance(message, str), 'asserts needs message to be a string' # if the message is empty and rule is callable, fill message with rule's source code if len(message)==0 and callable(rule): try: s = getsource(rule).splitlines()[0].strip() except: s = repr(rule).strip() message = 'illegal input of {} breaks - {}'.format(input_value, s) if callable(rule): # if rule is a function, run the function and assign it to rule rule = rule(input_value) # now, assert the rule and return the input value assert rule, message return input_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 print(*a): """ print just one that returns what you give it instead of None """
try: _print(*a) return a[0] if len(a) == 1 else a except: _print(*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 pattern2re(pattern): """Makes a unicode regular expression from a pattern. Returns ``(start, full_re, int_re)`` where: * `start` is either empty or the subdirectory in which to start searching, * `full_re` is a regular expression object that matches the requested files, i.e. a translation of the pattern * `int_re` is either None of a regular expression object that matches the requested paths or their ancestors (i.e. if a path doesn't match `int_re`, no path under it will match `full_re`) This uses extended patterns, where: * a slash '/' always represents the path separator * a backslash '\' escapes other special characters * an initial slash '/' anchors the match at the beginning of the (relative) path * a trailing '/' suffix is removed * an asterisk '*' matches a sequence of any length (including 0) of any characters (except the path separator) * a '?' matches exactly one character (except the path separator) * '[abc]' matches characters 'a', 'b' or 'c' * two asterisks '**' matches one or more path components (might match '/' characters) """
pattern_segs = filter(None, pattern.split('/')) # This anchors the first component either at the start of the string or at # the start of a path component if not pattern: return '', re.compile(''), None elif '/' in pattern: full_regex = '^' # Start at beginning of path int_regex = [] int_regex_done = False start_dir = [] start_dir_done = False else: full_regex = '(?:^|/)' # Skip any number of full components int_regex = None int_regex_done = True start_dir = [] start_dir_done = True # Handles each component for pnum, pat in enumerate(pattern_segs): comp = patterncomp2re(pat) # The first component is already anchored if pnum > 0: full_regex += '/' full_regex += comp if not int_regex_done: if pat == '**': int_regex_done = True else: int_regex.append(comp) if not start_dir_done and no_special_chars.match(pat): start_dir.append(pat) else: start_dir_done = True full_regex = re.compile(full_regex.rstrip('/') + '$') if int_regex is not None: n = len(int_regex) int_regex_s = '' for i, c in enumerate(reversed(int_regex)): if i == n - 1: # Last iteration (first component) int_regex_s = '^(?:%s%s)?' % (c, int_regex_s) elif int_regex_s: int_regex_s = '(?:/%s%s)?' % (c, int_regex_s) else: # First iteration (last component) int_regex_s = '(?:/%s)?' % c int_regex = re.compile(int_regex_s + '$') start_dir = '/'.join(start_dir) return start_dir, full_regex, int_regex
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _to_backend(self, p): """Converts something to the correct path representation. If given a Path, this will simply unpack it, if it's the correct type. If given the correct backend, it will return that. If given bytes for unicode of unicode for bytes, it will encode/decode with a reasonable encoding. Note that these operations can raise UnicodeError! """
if isinstance(p, self._cmp_base): return p.path elif isinstance(p, self._backend): return p elif self._backend is unicode and isinstance(p, bytes): return p.decode(self._encoding) elif self._backend is bytes and isinstance(p, unicode): return p.encode(self._encoding, 'surrogateescape' if PY3 else 'strict') else: raise TypeError("Can't construct a %s from %r" % ( self.__class__.__name__, type(p)))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parent(self): """The parent directory of this path. """
p = self._lib.dirname(self.path) p = self.__class__(p) return p
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unicodename(self): """The name of this path as unicode. """
n = self._lib.basename(self.path) if self._backend is unicode: return n else: return n.decode(self._encoding, '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 rel_path_to(self, dest): """Builds a relative path leading from this one to the given `dest`. Note that these paths might be both relative, in which case they'll be assumed to start from the same directory. """
dest = self.__class__(dest) orig_list = self.norm_case()._components() dest_list = dest._components() i = -1 for i, (orig_part, dest_part) in enumerate(zip(orig_list, dest_list)): if orig_part != self._normcase(dest_part): up = ['..'] * (len(orig_list) - i) return self.__class__(*(up + dest_list[i:])) if len(orig_list) <= len(dest_list): if len(dest_list) > i + 1: return self.__class__(*dest_list[i + 1:]) else: return self.__class__('') else: up = ['..'] * (len(orig_list) - i - 1) return self.__class__(*up)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def lies_under(self, prefix): """Indicates if the `prefix` is a parent of this path. """
orig_list = self.norm_case()._components() pref_list = self.__class__(prefix).norm_case()._components() return (len(orig_list) >= len(pref_list) and orig_list[:len(pref_list)] == pref_list)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tempfile(cls, suffix='', prefix=None, dir=None, text=False): """Returns a new temporary file. The return value is a pair (fd, path) where fd is the file descriptor returned by :func:`os.open`, and path is a :class:`~rpaths.Path` to it. :param suffix: If specified, the file name will end with that suffix, otherwise there will be no suffix. :param prefix: Is specified, the file name will begin with that prefix, otherwise a default prefix is used. :param dir: If specified, the file will be created in that directory, otherwise a default directory is used. :param text: If true, the file is opened in text mode. Else (the default) the file is opened in binary mode. On some operating systems, this makes no difference. The file is readable and writable only by the creating user ID. If the operating system uses permission bits to indicate whether a file is executable, the file is executable by no one. The file descriptor is not inherited by children of this process. The caller is responsible for deleting the file when done with it. """
if prefix is None: prefix = tempfile.template if dir is not None: # Note that this is not safe on Python 2 # There is no work around, apart from not using the tempfile module dir = str(Path(dir)) fd, filename = tempfile.mkstemp(suffix, prefix, dir, text) return fd, cls(filename).absolute()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tempdir(cls, suffix='', prefix=None, dir=None): """Returns a new temporary directory. Arguments are as for :meth:`~rpaths.Path.tempfile`, except that the `text` argument is not accepted. The directory is readable, writable, and searchable only by the creating user. The caller is responsible for deleting the directory when done with it. """
if prefix is None: prefix = tempfile.template if dir is not None: # Note that this is not safe on Python 2 # There is no work around, apart from not using the tempfile module dir = str(Path(dir)) dirname = tempfile.mkdtemp(suffix, prefix, dir) return cls(dirname).absolute()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rel_path_to(self, dest): """Builds a relative path leading from this one to another. Note that these paths might be both relative, in which case they'll be assumed to be considered starting from the same directory. Contrary to :class:`~rpaths.AbstractPath`'s version, this will also work if one path is relative and the other absolute. """
return super(Path, self.absolute()).rel_path_to(Path(dest).absolute())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def listdir(self, pattern=None): """Returns a list of all the files in this directory. The special entries ``'.'`` and ``'..'`` will not be returned. :param pattern: A pattern to match directory entries against. :type pattern: NoneType | Callable | Pattern | unicode | bytes """
files = [self / self.__class__(p) for p in os.listdir(self.path)] if pattern is None: pass elif callable(pattern): files = filter(pattern, files) else: if isinstance(pattern, backend_types): if isinstance(pattern, bytes): pattern = pattern.decode(self._encoding, 'replace') start, full_re, _int_re = pattern2re(pattern) elif isinstance(pattern, Pattern): start, full_re = pattern.start_dir, pattern.full_regex else: raise TypeError("listdir() expects pattern to be a callable, " "a regular expression or a string pattern, " "got %r" % type(pattern)) # If pattern contains slashes (other than first and last chars), # listdir() will never match anything if start: return [] files = [f for f in files if full_re.search(f.unicodename)] return files
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def recursedir(self, pattern=None, top_down=True, follow_links=False, handle_errors=None): """Recursively lists all files under this directory. :param pattern: An extended patterns, where: * a slash '/' always represents the path separator * a backslash '\' escapes other special characters * an initial slash '/' anchors the match at the beginning of the (relative) path * a trailing '/' suffix is removed * an asterisk '*' matches a sequence of any length (including 0) of any characters (except the path separator) * a '?' matches exactly one character (except the path separator) * '[abc]' matches characters 'a', 'b' or 'c' * two asterisks '**' matches one or more path components (might match '/' characters) :type pattern: NoneType | Callable | Pattern | unicode | bytes :param follow_links: If False, symbolic links will not be followed (the default). Else, they will be followed, but directories reached through different names will *not* be listed multiple times. :param handle_errors: Can be set to a callback that will be called when an error is encountered while accessing the filesystem (such as a permission issue). If set to None (the default), exceptions will be propagated. """
if not self.is_dir(): raise ValueError("recursedir() called on non-directory %s" % self) start = '' int_pattern = None if pattern is None: pattern = lambda p: True elif callable(pattern): pass else: if isinstance(pattern, backend_types): if isinstance(pattern, bytes): pattern = pattern.decode(self._encoding, 'replace') start, full_re, int_re = pattern2re(pattern) elif isinstance(pattern, Pattern): start, full_re, int_re = \ pattern.start_dir, pattern.full_regex, pattern.int_regex else: raise TypeError("recursedir() expects pattern to be a " "callable, a regular expression or a string " "pattern, got %r" % type(pattern)) if self._lib.sep != '/': pattern = lambda p: full_re.search( unicode(p).replace(self._lib.sep, '/')) if int_re is not None: int_pattern = lambda p: int_re.search( unicode(p).replace(self._lib.sep, '/')) else: pattern = lambda p: full_re.search(unicode(p)) if int_re is not None: int_pattern = lambda p: int_re.search(unicode(p)) if not start: path = self else: path = self / start if not path.exists(): return [] elif not path.is_dir(): return [path] return path._recursedir(pattern=pattern, int_pattern=int_pattern, top_down=top_down, seen=set(), path=self.__class__(start), follow_links=follow_links, handle_errors=handle_errors)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mkdir(self, name=None, parents=False, mode=0o777): """Creates that directory, or a directory under this one. ``path.mkdir(name)`` is a shortcut for ``(path/name).mkdir()``. :param name: Path component to append to this path before creating the directory. :param parents: If True, missing directories leading to the path will be created too, recursively. If False (the default), the parent of that path needs to exist already. :param mode: Permissions associated with the directory on creation, without race conditions. """
if name is not None: return (self / name).mkdir(parents=parents, mode=mode) if self.exists(): return if parents: os.makedirs(self.path, mode) else: os.mkdir(self.path, mode) return 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 rmdir(self, parents=False): """Removes this directory, provided it is empty. Use :func:`~rpaths.Path.rmtree` if it might still contain files. :param parents: If set to True, it will also destroy every empty directory above it until an error is encountered. """
if parents: os.removedirs(self.path) else: os.rmdir(self.path)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rename(self, new, parents=False): """Renames this path to the given new location. :param new: New path where to move this one. :param parents: If set to True, it will create the parent directories of the target if they don't exist. """
if parents: os.renames(self.path, self._to_backend(new)) else: os.rename(self.path, self._to_backend(new))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def copyfile(self, target): """Copies this file to the given `target` location. """
shutil.copyfile(self.path, self._to_backend(target))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def copymode(self, target): """Copies the mode of this file on the `target` file. The owner is not copied. """
shutil.copymode(self.path, self._to_backend(target))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def copystat(self, target): """Copies the permissions, times and flags from this to the `target`. The owner is not copied. """
shutil.copystat(self.path, self._to_backend(target))
<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(self, target): """Copies this file the `target`, which might be a directory. The permissions are copied. """
shutil.copy(self.path, self._to_backend(target))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def copytree(self, target, symlinks=False): """Recursively copies this directory to the `target` location. The permissions and times are copied (like :meth:`~rpaths.Path.copystat`). If the optional `symlinks` flag is true, symbolic links in the source tree result in symbolic links in the destination tree; if it is false, the contents of the files pointed to by symbolic links are copied. """
shutil.copytree(self.path, self._to_backend(target), symlinks)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def move(self, target): """Recursively moves a file or directory to the given target location. """
shutil.move(self.path, self._to_backend(target))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def open(self, mode='r', name=None, **kwargs): """Opens this file, or a file under this directory. ``path.open(mode, name)`` is a shortcut for ``(path/name).open(mode)``. Note that this uses :func:`io.open()` which behaves differently from :func:`open()` on Python 2; see the appropriate documentation. :param name: Path component to append to this path before opening the file. """
if name is not None: return io.open((self / name).path, mode=mode, **kwargs) else: return io.open(self.path, mode=mode, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rewrite(self, mode='r', name=None, temp=None, tempext='~', **kwargs): r"""Replaces this file with new content. This context manager gives you two file objects, (r, w), where r is readable and has the current content of the file, and w is writable and will replace the file at the end of the context (unless an exception is raised, in which case it is rolled back). Keyword arguments will be used for both files, unless they are prefixed with ``read_`` or ``write_``. For instance:: with Path('test.txt').rewrite(read_newline='\n', write_newline='\r\n') as (r, w): w.write(r.read()) :param name: Path component to append to this path before opening the file. :param temp: Temporary file name to write, and then move over this one. By default it's this filename with a ``~`` suffix. :param tempext: Extension to add to this file to get the temporary file to write then move over this one. Defaults to ``~``. """
if name is not None: pathr = self / name else: pathr = self for m in 'war+': mode = mode.replace(m, '') # Build options common_kwargs = {} readable_kwargs = {} writable_kwargs = {} for key, value in kwargs.items(): if key.startswith('read_'): readable_kwargs[key[5:]] = value elif key.startswith('write_'): writable_kwargs[key[6:]] = value else: common_kwargs[key] = value readable_kwargs = dict_union(common_kwargs, readable_kwargs) writable_kwargs = dict_union(common_kwargs, writable_kwargs) with pathr.open('r' + mode, **readable_kwargs) as readable: if temp is not None: pathw = Path(temp) else: pathw = pathr + tempext try: pathw.remove() except OSError: pass writable = pathw.open('w' + mode, **writable_kwargs) try: yield readable, writable except Exception: # Problem, delete writable writable.close() pathw.remove() raise else: writable.close() # Alright, replace pathr.copymode(pathw) pathr.remove() pathw.rename(pathr)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def matches(self, path): """Tests if the given path matches the pattern. Note that the unicode translation of the patch is matched, so replacement characters might have been added. """
path = self._prepare_path(path) return self.full_regex.search(path) 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 may_contain_matches(self, path): """Tests whether it's possible for paths under the given one to match. If this method returns None, no path under the given one will match the pattern. """
path = self._prepare_path(path) return self.int_regex.search(path) 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 tgcanrecruit(self, region=None): """Whether the nation will receive a recruitment telegram. Useful in conjunction with the Telegrams API. Parameters region : str Name of the region you are recruiting for. Returns ------- an :class:`ApiQuery` of bool """
params = {'from': normalize(region)} if region is not None else {} @api_query('tgcanrecruit', **params) async def result(_, root): return bool(int(root.find('TGCANRECRUIT').text)) return result(self)
<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 govt(self, root): """Nation's government expenditure, as percentages. Returns ------- an :class:`ApiQuery` of :class:`collections.OrderedDict` with \ keys of str and values of float Keys being, in order: ``Administration``, ``Defense``, ``Education``, ``Environment``, ``Healthcare``, ``Industry``, ``International Aid``, ``Law & Order``, ``Public Transport``, ``Social Policy``, ``Spirituality``, and ``Welfare``. """
elem = root.find('GOVT') result = OrderedDict() result['Administration'] = float(elem.find('ADMINISTRATION').text) result['Defense'] = float(elem.find('DEFENCE').text) # match the web UI result['Education'] = float(elem.find('EDUCATION').text) result['Environment'] = float(elem.find('ENVIRONMENT').text) result['Healthcare'] = float(elem.find('HEALTHCARE').text) result['Industry'] = float(elem.find('COMMERCE').text) # Don't ask result['International Aid'] = float(elem.find('INTERNATIONALAID').text) result['Law & Order'] = float(elem.find('LAWANDORDER').text) result['Public Transport'] = float(elem.find('PUBLICTRANSPORT').text) result['Social Policy'] = float(elem.find('SOCIALEQUALITY').text) # Shh result['Spirituality'] = float(elem.find('SPIRITUALITY').text) result['Welfare'] = float(elem.find('WELFARE').text) 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: async def sectors(self, root): """Components of the nation's economy, as percentages. Returns ------- an :class:`ApiQuery` of :class:`collections.OrderedDict` with \ keys of str and values of float Keys being, in order: ``Black Market (estimated)``, ``Government``, ``Private Industry``, and ``State-Owned Industry``. """
elem = root.find('SECTORS') result = OrderedDict() result['Black Market (estimated)'] = float(elem.find('BLACKMARKET').text) result['Government'] = float(elem.find('GOVERNMENT').text) result['Private Industry'] = float(elem.find('INDUSTRY').text) result['State-Owned Industry'] = float(elem.find('PUBLIC').text) 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: async def deaths(self, root): """Causes of death in the nation, as percentages. Returns ------- an :class:`ApiQuery` of dict with keys of str and values of float """
return { elem.get('type'): float(elem.text) for elem in root.find('DEATHS') }
<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 endorsements(self, root): """Regional neighbours endorsing the nation. Returns ------- an :class:`ApiQuery` of a list of :class:`Nation` """
text = root.find('ENDORSEMENTS').text return [Nation(name) for name in text.split(',')] if text else []
<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 description(self): """Nation's full description, as seen on its in-game page. Returns ------- an awaitable of str """
resp = await self._call_web(f'nation={self.id}') return html.unescape( re.search( '<div class="nationsummary">(.+?)<p class="nationranktext">', resp.text, flags=re.DOTALL ) .group(1) .replace('\n', '') .replace('</p>', '') .replace('<p>', '\n\n') .strip() )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def accept(self): """Accept the option. Returns ------- an awaitable of :class:`IssueResult` """
return self._issue._nation._accept_issue(self._issue.id, self._id)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pip_upgrade_all(line): """Attempt to upgrade all packages"""
from pip import get_installed_distributions user = set(d.project_name for d in get_installed_distributions(user_only=True)) all = set(d.project_name for d in get_installed_distributions()) for dist in all - user: do_pip(["install", "--upgrade", dist]) for dist in user: do_pip(["install", "--upgrade", "--user", dist])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def enc_name_descr(name, descr, color=a99.COLOR_DESCR): """Encodes html given name and description."""
return enc_name(name, color)+"<br>"+descr
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def style_checkboxes(widget): """ Iterates over widget children to change checkboxes stylesheet. The default rendering of checkboxes does not allow to tell a focused one from an unfocused one. """
ww = widget.findChildren(QCheckBox) for w in ww: w.setStyleSheet("QCheckBox:focus {border: 1px solid #000000;}")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reset_table_widget(t, rowCount, colCount): """Clears and resizes a table widget."""
t.reset() t.horizontalHeader().reset() t.clear() t.sortItems(-1) t.setRowCount(rowCount) t.setColumnCount(colCount)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def place_center(window, width=None, height=None): """Places window in the center of the screen."""
screenGeometry = QApplication.desktop().screenGeometry() w, h = window.width(), window.height() if width is not None or height is not None: w = width if width is not None else w h = height if height is not None else h window.setGeometry(0, 0, w, h) x = (screenGeometry.width() - w) / 2 y = (screenGeometry.height() - h) / 2 window.move(x, y)
<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_QApplication(args=[]): """Returns the QApplication instance, creating it is does not yet exist."""
global _qapp if _qapp is None: QCoreApplication.setAttribute(Qt.AA_X11InitThreads) _qapp = QApplication(args) return _qapp
<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_frame(): """Returns a QFrame formatted in a particular way"""
ret = QFrame() ret.setLineWidth(1) ret.setMidLineWidth(0) ret.setFrameShadow(QFrame.Sunken) ret.setFrameShape(QFrame.Box) return ret
<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_signal(self, signal): """Adds "input" signal to connected signals. Internally connects the signal to a control slot."""
self.__signals.append(signal) if self.__connected: # Connects signal if the current state is "connected" self.__connect_signal(signal)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def disconnect_all(self): """Disconnects all signals and slots. If already in "disconnected" state, ignores the call. """
if not self.__connected: return # assert self.__connected, "disconnect_all() already in \"disconnected\" state" self.__disconnecting = True try: for signal in self.__signals: signal.disconnect(self.__signalReceived) if self.__slot is not None: self.__sigDelayed.disconnect(self.__slot) self.__connected = False finally: self.__disconnecting = 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 __signalReceived(self, *args): """Received signal. Cancel previous timer and store args to be forwarded later."""
if self.__disconnecting: return with self.__lock: self.__args = args if self.__rateLimit == 0: self.__timer.stop() self.__timer.start((self.__delay * 1000) + 1) else: now = time.time() if self.__lastFlushTime is None: leakTime = 0 else: lastFlush = self.__lastFlushTime leakTime = max(0, (lastFlush + (1.0 / self.__rateLimit)) - now) self.__timer.stop() # Note: original was min() below. timeout = (max(leakTime, self.__delay) * 1000) + 1 self.__timer.start(timeout)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __flush(self): """If there is a signal queued up, send it now."""
if self.__args is None or self.__disconnecting: return False #self.emit(self.signal, *self.args) self.__sigDelayed.emit(self.__args) self.__args = None self.__timer.stop() self.__lastFlushTime = time.time() return 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 clean_indicators(indicators): """Remove any extra details from indicators."""
output = list() for indicator in indicators: strip = ['http://', 'https://'] for item in strip: indicator = indicator.replace(item, '') indicator = indicator.strip('.').strip() parts = indicator.split('/') if len(parts) > 0: indicator = parts.pop(0) output.append(indicator) output = list(set(output)) return output
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def hash_values(values, alg="md5"): """Hash a list of values."""
import hashlib if alg not in ['md5', 'sha1', 'sha256']: raise Exception("Invalid hashing algorithm!") hasher = getattr(hashlib, alg) if type(values) == str: output = hasher(values).hexdigest() elif type(values) == list: output = list() for item in values: output.append(hasher(item).hexdigest()) return output
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check_whitelist(values): """Check the indicators against known whitelists."""
import os import tldextract whitelisted = list() for name in ['alexa.txt', 'cisco.txt']: config_path = os.path.expanduser('~/.config/blockade') file_path = os.path.join(config_path, name) whitelisted += [x.strip() for x in open(file_path, 'r').readlines()] output = list() for item in values: ext = tldextract.extract(item) if ext.registered_domain in whitelisted: continue output.append(item) return output
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cache_items(values): """Cache indicators that were successfully sent to avoid dups."""
import os config_path = os.path.expanduser('~/.config/blockade') file_path = os.path.join(config_path, 'cache.txt') if not os.path.isfile(file_path): file(file_path, 'w').close() written = [x.strip() for x in open(file_path, 'r').readlines()] handle = open(file_path, 'a') for item in values: # Because of the option to submit in clear or hashed, we need to make # sure we're not re-hashing before adding. if is_hashed(item): hashed = item else: hashed = hash_values(item) if hashed in written: continue handle.write(hashed + "\n") handle.close() return 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 prune_cached(values): """Remove the items that have already been cached."""
import os config_path = os.path.expanduser('~/.config/blockade') file_path = os.path.join(config_path, 'cache.txt') if not os.path.isfile(file_path): return values cached = [x.strip() for x in open(file_path, 'r').readlines()] output = list() for item in values: hashed = hash_values(item) if hashed in cached: continue output.append(item) return output
<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_logger(name): """Get a logging instance we can use."""
import logging import sys logger = logging.getLogger(name) logger.setLevel(logging.DEBUG) shandler = logging.StreamHandler(sys.stdout) fmt = "" fmt += '\033[1;32m%(levelname)-5s %(module)s:%(funcName)s():' fmt += '%(lineno)d %(asctime)s\033[0m| %(message)s' fmtr = logging.Formatter(fmt) shandler.setFormatter(fmtr) logger.addHandler(shandler) return logger
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def process_whitelists(): """Download approved top 1M lists."""
import csv import grequests import os import StringIO import zipfile mapping = { 'http://s3.amazonaws.com/alexa-static/top-1m.csv.zip': { 'name': 'alexa.txt' }, 'http://s3-us-west-1.amazonaws.com/umbrella-static/top-1m.csv.zip': { 'name': 'cisco.txt' } } rs = (grequests.get(u) for u in mapping.keys()) responses = grequests.map(rs) for r in responses: data = zipfile.ZipFile(StringIO.StringIO(r.content)).read('top-1m.csv') stream = StringIO.StringIO(data) reader = csv.reader(stream, delimiter=',', quoting=csv.QUOTE_MINIMAL) items = [row[1].strip() for row in reader] stream.close() config_path = os.path.expanduser('~/.config/blockade') file_path = os.path.join(config_path, mapping[r.url]['name']) handle = open(file_path, 'w') for item in items: if item.count('.') == 0: continue handle.write(item + "\n") handle.close() return 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 mode(self, mode): """Sets the mode of this BraintreeGateway. :param mode: The mode of this BraintreeGateway. :type: str """
allowed_values = ["test", "live"] if mode is not None and mode not in allowed_values: raise ValueError( "Invalid value for `mode` ({0}), must be one of {1}" .format(mode, allowed_values) ) self._mode = mode
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def diagnose(df,preview_rows = 2, display_max_cols = 0,display_width = None): """ Prints information about the DataFrame pertinent to data cleaning. Parameters df - DataFrame The DataFrame to summarize preview_rows - int, default 5 Amount of rows to preview from the head and tail of the DataFrame display_max_cols - int, default None Maximum amount of columns to display. If set to None, all columns will be displayed. If set to 0, only as many as fit in the screen's width will be displayed display_width - int, default None Width of output. Can be width of file or width of console for printing. Set to None for pandas to detect it from console. """
assert type(df) is pd.DataFrame # Diagnose problems with the data formats that can be addressed in cleaning # Get initial display settings initial_max_cols = pd.get_option('display.max_columns') initial_max_rows = pd.get_option('display.max_rows') initial_width = pd.get_option('display.width') # Reformat displays pd.set_option('display.max_columns', display_max_cols) pd.set_option('display.max_rows',None) if display_width is not None: pd.set_option('display.width',display_width) # --------Values of data----------- df_preview = _io.preview(df,preview_rows) df_info = _io.get_info(df,verbose = True, max_cols = display_max_cols, memory_usage = 'deep',null_counts = True) dtypes = stats.dtypes_summary(df).apply(_io.format_row,args = [_utils.rows(df)],axis = 1) potential_outliers = stats.df_outliers(df).dropna(axis = 1,how = 'all') potential_outliers = potential_outliers if _utils.rows(potential_outliers) \ else None # ----------Build lists------------ title_list = \ ['Preview','Info', 'Data Types Summary','Potential Outliers'] info_list = \ [df_preview,df_info, dtypes,potential_outliers] error_list = [None,None, None,'No potential outliers.'] # ----------Build output------------ output = '' for title, value,error_text in zip(title_list,info_list,error_list): if value is None: value = "{} skipped: {}".format(title,error_text) if str(value).endswith('\n'): value = value[:-1] output+='{}\n{}\n\n'.format(_io.title_line(title),value) # ----------Send to file/print to console------------ # Potentially could change this to allow for output_safe to work with directories print(output) # Reset display settings pd.set_option('display.max_columns', initial_max_cols) pd.set_option('display.max_rows', initial_max_rows) pd.set_option('display.width', initial_width)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cut_spectrum(sp, l0, lf): """ Cuts spectrum given a wavelength interval, leaving origina intact Args: sp: Spectrum instance l0: initial wavelength lf: final wavelength Returns: Spectrum: cut spectrum """
if l0 >= lf: raise ValueError("l0 must be lower than lf") idx0 = np.argmin(np.abs(sp.x - l0)) idx1 = np.argmin(np.abs(sp.x - lf)) out = copy.deepcopy(sp) out.x = out.x[idx0:idx1] out.y = out.y[idx0:idx1] 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 skip_first(pipe, items=1): ''' this is an alias for skip to parallel the dedicated skip_last function to provide a little more readability to the code. the action of actually skipping does not occur until the first iteration is done ''' pipe = iter(pipe) for i in skip(pipe, items): yield i
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find(self, query=None, **kwargs): """ You can pass in the appropriate model object from the queries module, or a dictionary with the keys and values for the query, or a set of key=value parameters. """
url = self.getUrl() if query is not None: if isinstance(query, queries.SlickQuery): url = url + "?" + urlencode(query.to_dict()) elif isinstance(query, dict): url = url + "?" + urlencode(query) elif len(kwargs) > 0: url = url + "?" + urlencode(kwargs) # hopefully when we discover what problems exist in slick to require this, we can take the loop out for retry in range(3): try: self.logger.debug("Making request to slick at url %s", url) r = requests.get(url) self.logger.debug("Request returned status code %d", r.status_code) if r.status_code is 200: retval = [] objects = r.json() for dct in objects: retval.append(self.model.from_dict(dct)) return retval else: self.logger.error("Slick returned an error when trying to access %s: status code %s" % (url, str(r.status_code))) self.logger.error("Slick response: ", pprint.pformat(r)) except BaseException as error: self.logger.warn("Received exception while connecting to slick at %s", url, exc_info=sys.exc_info()) raise SlickCommunicationError( "Tried 3 times to request data from slick at url %s without a successful status code.", url)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def findOne(self, query=None, mode=FindOneMode.FIRST, **kwargs): """ Perform a find, with the same options present, but only return a maximum of one result. If find returns an empty array, then None is returned. If there are multiple results from find, the one returned depends on the mode parameter. If mode is FindOneMode.FIRST, then the first result is returned. If the mode is FindOneMode.LAST, then the last is returned. If the mode is FindOneMode.ERROR, then a SlickCommunicationError is raised. """
results = self.find(query, **kwargs) if len(results) is 0: return None elif len(results) is 1 or mode == FindOneMode.FIRST: return results[0] elif mode == FindOneMode.LAST: return results[-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 lookup_cc_partner(nu_pid): """Lookup the charge current partner Takes as an input neutrino nu_pid is a PDG code, then returns the charged lepton partner. So 12 (nu_e) returns 11. Keeps sign """
neutrino_type = math.fabs(nu_pid) assert neutrino_type in [12, 14, 16] cc_partner = neutrino_type - 1 # get e, mu, tau cc_partner = math.copysign( cc_partner, nu_pid) # make sure matter/antimatter cc_partner = int(cc_partner) # convert to int return cc_partner
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def block_comment(solver, start, end): '''embedable block comment''' text, pos = solver.parse_state length = len(text) startlen = len(start) endlen = len(end) if pos==length: return if not text[pos:].startswith(start): return level = 1 p = pos+1 while p<length: if text[p:].startswith(end): level -= 1 p += endlen if level==0: break elif text[p:].startswith(start): level += 1 p += startlen else: p += 1 else: return solver.parse_state = text, p yield cont, text[pos:p] solver.parse_state = text, 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 pip_install(*args): ''' Run pip install ... Explicitly ignores user's config. ''' pip_cmd = os.path.join(os.path.dirname(sys.executable), 'pip') with set_env('PIP_CONFIG_FILE', os.devnull): cmd = [pip_cmd, 'install'] + list(args) print_command(cmd) subprocess.call(cmd, stdout=sys.stdout, stderr=sys.stderr)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def indent_text(text, nb_tabs=0, tab_str=" ", linebreak_input="\n", linebreak_output="\n", wrap=False): r"""Add tabs to each line of text. :param text: the text to indent :param nb_tabs: number of tabs to add :param tab_str: type of tab (could be, for example "\t", default: 2 spaces :param linebreak_input: linebreak on input :param linebreak_output: linebreak on output :param wrap: wethever to apply smart text wrapping. (by means of wrap_text_in_a_box) :return: indented text as string """
if not wrap: lines = text.split(linebreak_input) tabs = nb_tabs * tab_str output = "" for line in lines: output += tabs + line + linebreak_output return output else: return wrap_text_in_a_box(body=text, style='no_border', tab_str=tab_str, tab_num=nb_tabs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def wait_for_user(msg=""): """ Print MSG and a confirmation prompt. Waiting for user's confirmation, unless silent '--yes-i-know' command line option was used, in which case the function returns immediately without printing anything. """
if '--yes-i-know' in sys.argv: return print(msg) try: answer = raw_input("Please confirm by typing 'Yes, I know!': ") except KeyboardInterrupt: print() answer = '' if answer != 'Yes, I know!': sys.stderr.write("ERROR: Aborted.\n") sys.exit(1) 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 guess_minimum_encoding(text, charsets=('ascii', 'latin1', 'utf8')): """Try to guess the minimum charset that is able to represent. Try to guess the minimum charset that is able to represent the given text using the provided charsets. text is supposed to be encoded in utf8. Returns (encoded_text, charset) where charset is the first charset in the sequence being able to encode text. Returns (text_in_utf8, 'utf8') in case no charset is able to encode text. @note: If the input text is not in strict UTF-8, then replace any non-UTF-8 chars inside it. """
text_in_unicode = text.decode('utf8', 'replace') for charset in charsets: try: return (text_in_unicode.encode(charset), charset) except (UnicodeEncodeError, UnicodeDecodeError): pass return (text_in_unicode.encode('utf8'), 'utf8')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def encode_for_xml(text, wash=False, xml_version='1.0', quote=False): """Encode special characters in a text so that it would be XML-compliant. :param text: text to encode :return: an encoded text """
text = text.replace('&', '&amp;') text = text.replace('<', '&lt;') if quote: text = text.replace('"', '&quot;') if wash: text = wash_for_xml(text, xml_version=xml_version) return text
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def wash_for_xml(text, xml_version='1.0'): """Remove any character which isn't a allowed characters for XML. The allowed characters depends on the version of XML. - XML 1.0: <http://www.w3.org/TR/REC-xml/#charsets> - XML 1.1: <http://www.w3.org/TR/xml11/#charsets> :param text: input string to wash. :param xml_version: version of the XML for which we wash the input. Value for this parameter can be '1.0' or '1.1' """
if xml_version == '1.0': return RE_ALLOWED_XML_1_0_CHARS.sub( '', unicode(text, 'utf-8')).encode('utf-8') else: return RE_ALLOWED_XML_1_1_CHARS.sub( '', unicode(text, 'utf-8')).encode('utf-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 wash_for_utf8(text, correct=True): """Return UTF-8 encoded binary string with incorrect characters washed away. :param text: input string to wash (can be either a binary or Unicode string) :param correct: whether to correct bad characters or throw exception """
if isinstance(text, unicode): return text.encode('utf-8') errors = "ignore" if correct else "strict" return text.decode("utf-8", errors).encode("utf-8", errors)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def nice_number(number, thousands_separator=',', max_ndigits_after_dot=None): """Return nicely printed number NUMBER in language LN. Return nicely printed number NUMBER in language LN using given THOUSANDS_SEPARATOR character. If max_ndigits_after_dot is specified and the number is float, the number is rounded by taking in consideration up to max_ndigits_after_dot digit after the dot. This version does not pay attention to locale. See tmpl_nice_number_via_locale(). """
if isinstance(number, float): if max_ndigits_after_dot is not None: number = round(number, max_ndigits_after_dot) int_part, frac_part = str(number).split('.') return '%s.%s' % (nice_number(int(int_part), thousands_separator), frac_part) else: chars_in = list(str(number)) number = len(chars_in) chars_out = [] for i in range(0, number): if i % 3 == 0 and i != 0: chars_out.append(thousands_separator) chars_out.append(chars_in[number - i - 1]) chars_out.reverse() return ''.join(chars_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 nice_size(size): """Nice size. :param size: the size. :type size: int :return: a nicely printed size. :rtype: string """
unit = 'B' if size > 1024: size /= 1024.0 unit = 'KB' if size > 1024: size /= 1024.0 unit = 'MB' if size > 1024: size /= 1024.0 unit = 'GB' return '%s %s' % (nice_number(size, max_ndigits_after_dot=2), unit)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remove_line_breaks(text): """Remove line breaks from input. Including unicode 'line separator', 'paragraph separator', and 'next line' characters. """
return unicode(text, 'utf-8').replace('\f', '').replace('\n', '') \ .replace('\r', '').replace(u'\xe2\x80\xa8', '') \ .replace(u'\xe2\x80\xa9', '').replace(u'\xc2\x85', '') \ .encode('utf-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 decode_to_unicode(text, default_encoding='utf-8'): """Decode input text into Unicode representation. Decode input text into Unicode representation by first using the default encoding utf-8. If the operation fails, it detects the type of encoding used in the given text. For optimal result, it is recommended that the 'chardet' module is installed. NOTE: Beware that this might be slow for *very* large strings. If chardet detection fails, it will try to decode the string using the basic detection function guess_minimum_encoding(). Also, bear in mind that it is impossible to detect the correct encoding at all times, other then taking educated guesses. With that said, this function will always return some decoded Unicode string, however the data returned may not be the same as original data in some cases. :param text: the text to decode :type text: string :param default_encoding: the character encoding to use. Optional. :type default_encoding: string :return: input text as Unicode :rtype: string """
if not text: return "" try: return text.decode(default_encoding) except (UnicodeError, LookupError): pass detected_encoding = None if CHARDET_AVAILABLE: # We can use chardet to perform detection res = chardet.detect(text) if res['confidence'] >= 0.8: detected_encoding = res['encoding'] if detected_encoding is None: # No chardet detection, try to make a basic guess dummy, detected_encoding = guess_minimum_encoding(text) return text.decode(detected_encoding)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_unicode(text): """Convert to unicode."""
if isinstance(text, unicode): return text if isinstance(text, six.string_types): return decode_to_unicode(text) return unicode(text)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def translate_latex2unicode(text, kb_file=None): """Translate latex text to unicode. This function will take given text, presumably containing LaTeX symbols, and attempts to translate it to Unicode using the given or default KB translation table located under CFG_ETCDIR/bibconvert/KB/latex-to-unicode.kb. The translated Unicode string will then be returned. If the translation table and compiled regular expression object is not previously generated in the current session, they will be. :param text: a text presumably containing LaTeX symbols. :type text: string :param kb_file: full path to file containing latex2unicode translations. Defaults to CFG_ETCDIR/bibconvert/KB/latex-to-unicode.kb :type kb_file: string :return: Unicode representation of translated text :rtype: unicode """
if kb_file is None: kb_file = get_kb_filename() # First decode input text to Unicode try: text = decode_to_unicode(text) except UnicodeDecodeError: text = unicode(wash_for_utf8(text)) # Load translation table, if required if CFG_LATEX_UNICODE_TRANSLATION_CONST == {}: _load_latex2unicode_constants(kb_file) # Find all matches and replace text for match in CFG_LATEX_UNICODE_TRANSLATION_CONST['regexp_obj'] \ .finditer(text): # If LaTeX style markers {, } and $ are before or after the # matching text, it will replace those as well text = re.sub("[\{\$]?%s[\}\$]?" % (re.escape(match.group()),), CFG_LATEX_UNICODE_TRANSLATION_CONST[ 'table'][match.group()], text) # Return Unicode representation of translated text return text
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _load_latex2unicode_constants(kb_file=None): """Load LaTeX2Unicode translation table dictionary. Load LaTeX2Unicode translation table dictionary and regular expression object from KB to a global dictionary. :param kb_file: full path to file containing latex2unicode translations. Defaults to CFG_ETCDIR/bibconvert/KB/latex-to-unicode.kb :type kb_file: string :return: dict of type: {'regexp_obj': regexp match object, 'table': dict of LaTeX -> Unicode mappings} :rtype: dict """
if kb_file is None: kb_file = get_kb_filename() try: data = open(kb_file) except IOError: # File not found or similar sys.stderr.write( "\nCould not open LaTeX to Unicode KB file. " "Aborting translation.\n") return CFG_LATEX_UNICODE_TRANSLATION_CONST latex_symbols = [] translation_table = {} for line in data: # The file has form of latex|--|utf-8. First decode to Unicode. line = line.decode('utf-8') mapping = line.split('|--|') translation_table[mapping[0].rstrip('\n')] = mapping[1].rstrip('\n') latex_symbols.append(re.escape(mapping[0].rstrip('\n'))) data.close() CFG_LATEX_UNICODE_TRANSLATION_CONST[ 'regexp_obj'] = re.compile("|".join(latex_symbols)) CFG_LATEX_UNICODE_TRANSLATION_CONST['table'] = translation_table
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def translate_to_ascii(values): r"""Transliterate the string into ascii representation. Transliterate the string contents of the given sequence into ascii representation. Returns a sequence with the modified values if the module 'unidecode' is available. Otherwise it will fall back to the inferior strip_accents function. For example: H\xc3\xb6hne becomes Hohne. Note: Passed strings are returned as a list. :param values: sequence of strings to transform :type values: sequence :return: sequence with values transformed to ascii :rtype: sequence """
if not values and not isinstance(values, str): return values if isinstance(values, str): values = [values] for index, value in enumerate(values): if not value: continue unicode_text = decode_to_unicode(value) if u"[?]" in unicode_text: decoded_text = [] for unicode_char in unicode_text: decoded_char = unidecode(unicode_char) # Skip unrecognized characters if decoded_char != "[?]": decoded_text.append(decoded_char) ascii_text = ''.join(decoded_text).encode('ascii') else: ascii_text = unidecode(unicode_text).replace( u"[?]", u"").encode('ascii') values[index] = ascii_text return values
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def xml_entities_to_utf8(text, skip=('lt', 'gt', 'amp')): """Translate HTML or XML character references to UTF-8. Removes HTML or XML character references and entities from a text string and replaces them with their UTF-8 representation, if possible. :param text: The HTML (or XML) source text. :type text: string :param skip: list of entity names to skip when transforming. :type skip: iterable :return: The plain text, as a Unicode string, if necessary. @author: Based on http://effbot.org/zone/re-sub.htm#unescape-html """
def fixup(m): text = m.group(0) if text[:2] == "&#": # character reference try: if text[:3] == "&#x": return unichr(int(text[3:-1], 16)).encode("utf-8") else: return unichr(int(text[2:-1])).encode("utf-8") except ValueError: pass else: # named entity if text[1:-1] not in skip: try: text = unichr( html_entities.name2codepoint[text[1:-1]]) \ .encode("utf-8") except KeyError: pass return text # leave as is return re.sub("&#?\w+;", fixup, text)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def strip_accents(x): u"""Strip accents in the input phrase X. Strip accents in the input phrase X (assumed in UTF-8) by replacing accented characters with their unaccented cousins (e.g. é by e). :param x: the input phrase to strip. :type x: string :return: Return such a stripped X. """
x = re_latex_lowercase_a.sub("a", x) x = re_latex_lowercase_ae.sub("ae", x) x = re_latex_lowercase_oe.sub("oe", x) x = re_latex_lowercase_e.sub("e", x) x = re_latex_lowercase_i.sub("i", x) x = re_latex_lowercase_o.sub("o", x) x = re_latex_lowercase_u.sub("u", x) x = re_latex_lowercase_y.sub("x", x) x = re_latex_lowercase_c.sub("c", x) x = re_latex_lowercase_n.sub("n", x) x = re_latex_uppercase_a.sub("A", x) x = re_latex_uppercase_ae.sub("AE", x) x = re_latex_uppercase_oe.sub("OE", x) x = re_latex_uppercase_e.sub("E", x) x = re_latex_uppercase_i.sub("I", x) x = re_latex_uppercase_o.sub("O", x) x = re_latex_uppercase_u.sub("U", x) x = re_latex_uppercase_y.sub("Y", x) x = re_latex_uppercase_c.sub("C", x) x = re_latex_uppercase_n.sub("N", x) # convert input into Unicode string: try: y = unicode(x, "utf-8") except Exception: return x # something went wrong, probably the input wasn't UTF-8 # asciify Latin-1 lowercase characters: y = re_unicode_lowercase_a.sub("a", y) y = re_unicode_lowercase_ae.sub("ae", y) y = re_unicode_lowercase_oe.sub("oe", y) y = re_unicode_lowercase_e.sub("e", y) y = re_unicode_lowercase_i.sub("i", y) y = re_unicode_lowercase_o.sub("o", y) y = re_unicode_lowercase_u.sub("u", y) y = re_unicode_lowercase_y.sub("y", y) y = re_unicode_lowercase_c.sub("c", y) y = re_unicode_lowercase_n.sub("n", y) y = re_unicode_lowercase_ss.sub("ss", y) # asciify Latin-1 uppercase characters: y = re_unicode_uppercase_a.sub("A", y) y = re_unicode_uppercase_ae.sub("AE", y) y = re_unicode_uppercase_oe.sub("OE", y) y = re_unicode_uppercase_e.sub("E", y) y = re_unicode_uppercase_i.sub("I", y) y = re_unicode_uppercase_o.sub("O", y) y = re_unicode_uppercase_u.sub("U", y) y = re_unicode_uppercase_y.sub("Y", y) y = re_unicode_uppercase_c.sub("C", y) y = re_unicode_uppercase_n.sub("N", y) # return UTF-8 representation of the Unicode string: return y.encode("utf-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 show_diff(original, modified, prefix='', suffix='', prefix_unchanged=' ', suffix_unchanged='', prefix_removed='-', suffix_removed='', prefix_added='+', suffix_added=''): """Return the diff view between original and modified strings. Function checks both arguments line by line and returns a string with a: - prefix_unchanged when line is common to both sequences - prefix_removed when line is unique to sequence 1 - prefix_added when line is unique to sequence 2 and a corresponding suffix in each line :param original: base string :param modified: changed string :param prefix: prefix of the output string :param suffix: suffix of the output string :param prefix_unchanged: prefix of the unchanged line :param suffix_unchanged: suffix of the unchanged line :param prefix_removed: prefix of the removed line :param suffix_removed: suffix of the removed line :param prefix_added: prefix of the added line :param suffix_added: suffix of the added line :return: string with the comparison of the records :rtype: string """
import difflib differ = difflib.Differ() result = [prefix] for line in differ.compare(modified.splitlines(), original.splitlines()): if line[0] == ' ': # Mark as unchanged result.append( prefix_unchanged + line[2:].strip() + suffix_unchanged) elif line[0] == '-': # Mark as removed result.append(prefix_removed + line[2:].strip() + suffix_removed) elif line[0] == '+': # Mark as added/modified result.append(prefix_added + line[2:].strip() + suffix_added) result.append(suffix) return '\n'.join(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 escape_latex(text): r"""Escape characters of given text. This function takes the given text and escapes characters that have a special meaning in LaTeX: # $ % ^ & _ { } ~ \ """
text = unicode(text.decode('utf-8')) CHARS = { '&': r'\&', '%': r'\%', '$': r'\$', '#': r'\#', '_': r'\_', '{': r'\{', '}': r'\}', '~': r'\~{}', '^': r'\^{}', '\\': r'\textbackslash{}', } escaped = "".join([CHARS.get(char, char) for char in text]) return escaped.encode('utf-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 _copy_attr(self, module, varname, cls, attrname=None): """ Copies attribute from module object to self. Raises if object not of expected class Args: module: module object varname: variable name cls: expected class of variable attrname: attribute name of self. Falls back to varname """
if not hasattr(module, varname): raise RuntimeError("Variable '{}' not found".format(varname)) obj = getattr(module, varname) if not isinstance(obj, cls): raise RuntimeError( "Expecting fobj to be a {}, not a '{}'".format(cls.__name__, obj.__class__.__name__)) if attrname is None: attrname = varname setattr(self, attrname, obj)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __check_to_permit(self, entry_type, entry_filename): """Applying the filter rules."""
rules = self.__filter_rules[entry_type] # Should explicitly include? for pattern in rules[fss.constants.FILTER_INCLUDE]: if fnmatch.fnmatch(entry_filename, pattern): _LOGGER_FILTER.debug("Entry explicitly INCLUDED: [%s] [%s] " "[%s]", entry_type, pattern, entry_filename) return True # Should explicitly exclude? for pattern in rules[fss.constants.FILTER_EXCLUDE]: if fnmatch.fnmatch(entry_filename, pattern): _LOGGER_FILTER.debug("Entry explicitly EXCLUDED: [%s] [%s] " "[%s]", entry_type, pattern, entry_filename) return False # Implicitly include. _LOGGER_FILTER.debug("Entry IMPLICITLY included: [%s] [%s]", entry_type, entry_filename) return 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 census(self, *scales): """Current World Census data. By default returns data on today's featured World Census scale, use arguments to get results on specific scales. In order to request data on all scales at once you can do ``x.census(*range(81))``. Parameters scales : int World Census scales, integers between 0 and 85 inclusive. Returns ------- an :class:`ApiQuery` of a list of :class:`CensusScaleCurrent` """
params = {'mode': 'score+rank+rrank+prank+prrank'} if scales: params['scale'] = '+'.join(str(x) for x in scales) @api_query('census', **params) async def result(_, root): return [ CensusScaleCurrent(scale_elem) for scale_elem in root.find('CENSUS') ] return result(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 censushistory(self, *scales): """Historical World Census data. Was split into its own method for the sake of simplicity. By default returns data on today's featured World Census scale, use arguments to get results on specific scales. In order to request data on all scales at once you can do ``x.censushistory(*range(81))``. Returns data for the entire length of history NationStates stores. There is no way to override that. Parameters scales : int World Census scales, integers between 0 and 85 inclusive. Returns ------- an :class:`ApiQuery` of a list of :class:`CensusScaleHistory` """
params = {'mode': 'history'} if scales: params['scale'] = '+'.join(str(x) for x in scales) @api_query('census', **params) async def result(_, root): return [ CensusScaleHistory(scale_elem) for scale_elem in root.find('CENSUS') ] return result(self)
<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 censusranks(self, scale): """Iterate through nations ranked on the World Census scale. If the ranks change while you interate over them, they may be inconsistent. Parameters scale : int A World Census scale, an integer between 0 and 85 inclusive. Returns ------- asynchronous iterator of :class:`CensusRank` """
order = count(1) for offset in count(1, 20): census_ranks = await self._get_censusranks( scale=scale, start=offset) for census_rank in census_ranks: assert census_rank.rank == next(order) yield census_rank if len(census_ranks) < 20: break
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def loads(astring): """Decompress and deserialize string into Python object via marshal."""
try: return marshal.loads(zlib.decompress(astring)) except zlib.error as e: raise SerializerError( 'Cannot decompress object ("{}")'.format(str(e)) ) except Exception as e: # marshal module does not provide a proper Exception model raise SerializerError( 'Cannot restore object ("{}")'.format(str(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 loads(astring): """Decompress and deserialize string into Python object via pickle."""
try: return pickle.loads(zlib.decompress(astring)) except zlib.error as e: raise SerializerError( 'Cannot decompress object ("{}")'.format(str(e)) ) except pickle.UnpicklingError as e: raise SerializerError( 'Cannot restore object ("{}")'.format(str(e)) )