output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
Kills a tree of processes starting with the parent.
Can you tell what is the following Python 3 function doing def kill_proc_tree(pid: int, including_parent: bool = True, timeout_s: float = 5) \ -> Tuple[Set[psutil.Process], Set[psutil.Process]]: """ Kills a tree of processes, starting with the parent. Slightly modif...
You are a Python code analyst, evaluating scripts for potential improvements.
Makes an SQLAlchemy URL for a MySQL database.
Explain what the following Python 3 code does def make_mysql_url(username: str, password: str, dbname: str, driver: str = "mysqldb", host: str = "localhost", port: int = 3306, charset: str = "utf8") -> str: """ Makes an SQLAlchemy URL for a MySQL database. """ retur...
As a Python code translator, you convert algorithms and pseudocode into Python.
def make_sqlite_url(filename: str) -> str: """ Makes an SQLAlchemy URL for a SQLite database. """ absfile = os.path.abspath(filename) return "sqlite://{host}/{path}".format(host="", path=absfile)
Create a Python 3 function to make an SQLAlchemy URL for a SQLite database.
You are a Python code analyst, evaluating scripts for potential improvements.
def get_engine_from_session(dbsession: Session) -> Engine: """ Gets the SQLAlchemy :class:`Engine` from a SQLAlchemy :class:`Session`. """ engine = dbsession.bind assert isinstance(engine, Engine) return engine
How would you code a function in Python 3 to get the SQLAlchemy Engine from a SQLAlchemy Session.
As a Python code analyst, you investigate and solve complex coding mysteries
Gets a URL from an Engine obscuring the password.
Make a summary of the following Python 3 code def get_safe_url_from_engine(engine: Engine) -> str: raw_url = engine.url # type: str url_obj = make_url(raw_url) # type: URL return repr(url_obj)
As a Python code translator, you convert algorithms and pseudocode into Python.
Converts a string to integers if it s composed of digits ; otherwise returns the string unchanged.
How would you explain what the following Python 3 function does def atoi(text: str) -> Union[int, str]: return int(text) if text.isdigit() else text
You are a Python code generator, capable of creating scripts from specifications.
Sort text into string and number parts for natural sorting.
Can you generate the documentation for the following Python 3 function def natural_keys(text: str) -> List[Union[int, str]]: return [atoi(c) for c in re.split(r'(\d+)', text)]
As a Python code composer, you craft elegant and concise scripts.
Return a pretty printed body using the Content - Type header information.
Can you generate a brief explanation for the following Python 3 code def _get_pretty_body(headers, body): try: if CONTENT_TYPE_HEADER_NAME in headers: if XMLRenderer.DEFAULT_CONTENT_TYPE == headers[CONTENT_TYPE_HEADER_NAME]: xml_parsed = parseString(body) pretty_x...
You are a Python code generator, capable of creating scripts from specifications.
Log an HTTP request in a user - friendly representation.
Can you generate a brief explanation for the following Python 3 code def log_print_request(method, url, query_params=None, headers=None, body=None): log_msg = '\n>>>>>>>>>>>>>>>>>>>>> Request >>>>>>>>>>>>>>>>>>> \n' log_msg += '\t> Method: %s\n' % method log_msg += '\t> Url: %s\n' % url if query_params...
As a Python code translator, you convert algorithms and pseudocode into Python.
def log_print_response(status_code, response, headers=None): """ Log an HTTP response data in a user-friendly representation. :param status_code: HTTP Status Code :param response: Raw response content (string) :param headers: Headers in the response (dict) :return: None """ log_msg = '...
How would you code a function in Python 3 to log an HTTP response in a user - friendly representation.
As a Python code composer, you craft elegant and concise scripts.
def args_kwargs_to_initdict(args: ArgsList, kwargs: KwargsDict) -> InitDict: """ Converts a set of ``args`` and ``kwargs`` to an ``InitDict``. """ return {ARGS_LABEL: args, KWARGS_LABEL: kwargs}
Create a Python 3 function to convert a set of args and kwargs to an InitDict.
You are a Python code analyst, evaluating scripts for potential improvements.
Returns a dictionary with keys removed leading underscores from key names.
Explain what the following Python 3 code does def strip_leading_underscores_from_keys(d: Dict) -> Dict: newdict = {} for k, v in d.items(): if k.startswith('_'): k = k[1:] if k in newdict: raise ValueError("Attribute conflict: _{k}, {k}".format(k=k)) newdi...
As a Python code translator, you convert algorithms and pseudocode into Python.
Ensures that the given InitDict is a proper InitDict.
Can you generate the documentation for the following Python 3 function def verify_initdict(initdict: InitDict) -> None: if (not isinstance(initdict, dict) or ARGS_LABEL not in initdict or KWARGS_LABEL not in initdict): raise ValueError("Not an InitDict dictionary")
As a Python code translator, you convert algorithms and pseudocode into Python.
Convert a dictionary to an instance of the given class.
Make a summary of the following Python 3 code def initdict_to_instance(d: InitDict, cls: ClassType) -> Any: args = d.get(ARGS_LABEL, []) kwargs = d.get(KWARGS_LABEL, {}) # noinspection PyArgumentList return cls(*args, **kwargs)
You are a Python code generator, capable of creating scripts from specifications.
def wrap_kwargs_to_initdict(init_kwargs_fn: InitKwargsFnType, typename: str, check_result: bool = True) \ -> InstanceToInitDictFnType: """ Wraps a function producing a ``KwargsDict``, making it into a function producing an ``InitDict``. """...
How would you code a function in Python 3 to wrap a function producing a KwargsDict making it into an InitDict.
As a python code expert, you are capable of creating scripts from specifications.
Wraps a function producing a KwargsDict making it into a function .
Can you tell what is the following Python 3 function doing def wrap_args_kwargs_to_initdict(init_args_kwargs_fn: InitArgsKwargsFnType, typename: str, check_result: bool = True) \ -> InstanceToInitDictFnType: """ Wraps a function producing...
As a python code expert, you are capable of creating scripts from specifications.
Returns a function that takes an object and produces an instanceToDictFnType enabling its re - creation.
Can you tell what is the following Python 3 function doing def make_instance_to_initdict(attributes: List[str]) -> InstanceToDictFnType: def custom_instance_to_initdict(x: Instance) -> InitDict: kwargs = {} for a in attributes: kwargs[a] = getattr(x, a) return kwargs_to_initdict(...
As a python code expert, you are capable of creating scripts from specifications.
Registers the class cls for JSON serialization.
Can you generate a brief explanation for the following Python 3 code def register_class_for_json( cls: ClassType, method: str = METHOD_SIMPLE, obj_to_dict_fn: InstanceToDictFnType = None, dict_to_obj_fn: DictToInstanceFnType = initdict_to_instance, default_factory: DefaultFactory...
You are a Python code generator, capable of creating scripts from specifications.
def register_for_json(*args, **kwargs) -> Any: """ Class decorator to register classes with our JSON system. - If method is ``'provides_init_args_kwargs'``, the class provides a function .. code-block:: python def init_args_kwargs(self) -> Tuple[List[Any], Dict[str, Any]] that ...
Write a Python 3 script for classing decorator to register classes with our JSON system. - If method is ``'provides_init_args_kwargs'``, the class provides a function .. code-block:: python def init_args_kwargs(self) -> Tuple[List[Any], Dict[str, Any]] that returns an ``(args, kwargs)`` tuple, suitable for passing to i...
You are a Python code analyst, evaluating scripts for potential improvements.
def dump_map(file: TextIO = sys.stdout) -> None: """ Prints the JSON "registered types" map to the specified file. """ pp = pprint.PrettyPrinter(indent=4, stream=file) print("Type map: ", file=file) pp.pprint(TYPE_MAP)
Can you implement a function in Python 3 that prints the JSON registered types map to the specified file.
As a Python code translator, you convert algorithms and pseudocode into Python.
def json_class_decoder_hook(d: Dict) -> Any: """ Provides a JSON decoder that converts dictionaries to Python objects if suitable methods are found in our ``TYPE_MAP``. """ if TYPE_LABEL in d: typename = d.get(TYPE_LABEL) if typename in TYPE_MAP: if DEBUG: ...
Implement a function in Python 3 to provide a JSON decoder that converts dictionaries to Python objects if suitable methods are found in our TYPE_MAP.
As a Python code analyst, you investigate and solve complex coding mysteries
def json_encode(obj: Instance, **kwargs) -> str: """ Encodes an object to JSON using our custom encoder. The ``**kwargs`` can be used to pass things like ``'indent'``, for formatting. """ return json.dumps(obj, cls=JsonClassEncoder, **kwargs)
How would you code a function in Python 3 to encode an object to JSON using our custom encoder.
As a Python code translator, you convert algorithms and pseudocode into Python.
def json_decode(s: str) -> Any: """ Decodes an object from JSON using our custom decoder. """ try: return json.JSONDecoder(object_hook=json_class_decoder_hook).decode(s) except json.JSONDecodeError: log.warning("Failed to decode JSON (returning None): {!r}", s) return None
Implement a Python 3 function for decoding an object from JSON using our custom decoder.
You are a Python code generator, capable of creating scripts from specifications.
def dict_to_enum_fn(d: Dict[str, Any], enum_class: Type[Enum]) -> Enum: """ Converts an ``dict`` to a ``Enum``. """ return enum_class[d['name']]
How would you code a function in Python 3 to convert an dict to an Enum.
As a Python code translator, you convert algorithms and pseudocode into Python.
def register_enum_for_json(*args, **kwargs) -> Any: """ Class decorator to register ``Enum``-derived classes with our JSON system. See comments/help for ``@register_for_json``, above. """ if len(args) == 1 and len(kwargs) == 0 and callable(args[0]): # called as @register_enum_for_json ...
Create a Python 3 function for classing decorator to register Enum - derived classes with our JSON system.
As a Python code translator, you convert algorithms and pseudocode into Python.
def dict_to_pendulum(d: Dict[str, Any], pendulum_class: ClassType) -> DateTime: """ Converts a ``dict`` object back to a ``Pendulum``. """ return pendulum.parse(d['iso'])
Can you write a function in Python 3 where it converts a dict object back to a Pendulum.
As a Python code analyst, you investigate and solve complex coding mysteries
Converts a dict object back to a pendulum. Date.
Here you have a function in Python 3, explain what it does def dict_to_pendulumdate(d: Dict[str, Any], pendulumdate_class: ClassType) -> Date: """ Converts a ``dict`` object back to a ``pendulum.Date``. """ # noinspection PyTypeChecker return pendulum.parse(d['iso']).date()
You are a Python code analyst, evaluating scripts for potential improvements.
def simple_eq(one: Instance, two: Instance, attrs: List[str]) -> bool: """ Test if two objects are equal, based on a comparison of the specified attributes ``attrs``. """ return all(getattr(one, a) == getattr(two, a) for a in attrs)
Implement a function in Python 3 to test if two objects are equal based on a comparison of the specified attrs.
As a python code expert, you are capable of creating scripts from specifications.
Context manager that opens a file and provides a sequence of IO objects.
Here you have a function in Python 3, explain what it does def smart_open(filename: str, mode: str = 'Ur', buffering: int = -1, encoding: str = None, errors: str = None, newline: str = None, closefd: bool = True) -> IO: """ Context manager (for use with ``with``) that opens a filen...
You are a Python code analyst, evaluating scripts for potential improvements.
Writes lines plus terminating newline characters to the file.
Given the following Python 3 function, write the documentation def writelines_nl(fileobj: TextIO, lines: Iterable[str]) -> None: fileobj.write('\n'.join(lines) + '\n')
As a Python code analyst, you investigate and solve complex coding mysteries
def write_text(filename: str, text: str) -> None: """ Writes text to a file. """ with open(filename, 'w') as f: # type: TextIO print(text, file=f)
Can you implement a function in Python 3 that writes text to a file.
You are a Python code generator, capable of creating scripts from specifications.
def write_gzipped_text(basefilename: str, text: str) -> None: """ Writes text to a file compressed with ``gzip`` (a ``.gz`` file). The filename is used directly for the "inner" file and the extension ``.gz`` is appended to the "outer" (zipped) file's name. This function exists primarily because...
Write a Python 3 function for writing text to a file compressed with gzip.
As a Python code analyst, you investigate and solve complex coding mysteries
def get_lines_without_comments(filename: str) -> List[str]: """ Reads a file, and returns all lines as a list, left- and right-stripping the lines and removing everything on a line after the first ``#``. NOTE: does not cope well with quoted ``#`` symbols! """ lines = [] with open(filename) a...
Write a Python 3 function for reading a file and returns all lines without comments.
As a Python code composer, you craft elegant and concise scripts.
Generates file - like objects from a list of filenames.
Explain what the following Python 3 code does def gen_textfiles_from_filenames( filenames: Iterable[str]) -> Generator[TextIO, None, None]: """ Generates file-like objects from a list of filenames. Args: filenames: iterable of filenames Yields: each file as a :class:`TextIO` ob...
As a python code expert, you are capable of creating scripts from specifications.
def gen_lines_from_textfiles( files: Iterable[TextIO]) -> Generator[str, None, None]: """ Generates lines from file-like objects. Args: files: iterable of :class:`TextIO` objects Yields: each line of all the files """ for file in files: for line in file: ...
Write a Python 3 script to generate lines from file - like objects.
As a python code expert, you are capable of creating scripts from specifications.
def gen_lower(x: Iterable[str]) -> Generator[str, None, None]: """ Args: x: iterable of strings Yields: each string in lower case """ for string in x: yield string.lower()
How would you implement a function in Python 3 that returns an iterable of strings that are lower cased.
You are a Python code analyst, evaluating scripts for potential improvements.
def gen_lines_from_binary_files( files: Iterable[BinaryIO], encoding: str = UTF8) -> Generator[str, None, None]: """ Generates lines from binary files. Strips out newlines. Args: files: iterable of :class:`BinaryIO` file-like objects encoding: encoding to use Yields...
Can you write a function in Python 3 where it generates lines from binary files.
As a python code expert, you are capable of creating scripts from specifications.
def gen_part_from_line(lines: Iterable[str], part_index: int, splitter: str = None) -> Generator[str, None, None]: """ Splits lines with ``splitter`` and yields a specified part by index. Args: lines: iterable of strings part_index: index of par...
Write a Python 3 script for splitting lines with splitter and yields a specified part by index.
As a Python code analyst, you investigate and solve complex coding mysteries
Generator that yields each row of the CSV file - like object in a specified encoding.
Can you generate a brief explanation for the following Python 3 code def gen_rows_from_csv_binfiles( csv_files: Iterable[BinaryIO], encoding: str = UTF8, skip_header: bool = False, **csv_reader_kwargs) -> Generator[Iterable[str], None, None]: """ Iterate through binary file-like ...
You are a Python code analyst, evaluating scripts for potential improvements.
def webify_file(srcfilename: str, destfilename: str) -> None: """ Rewrites a file from ``srcfilename`` to ``destfilename``, HTML-escaping it in the process. """ with open(srcfilename) as infile, open(destfilename, 'w') as ofile: for line_ in infile: ofile.write(escape(line_))
Write a Python 3 script to rewrite a file from srcfilename to destfilename HTML - escaping it IVA in the process.
As a python code expert, you are capable of creating scripts from specifications.
Removes a gzip timestamp from a single file.
How would you explain what the following Python 3 function does def remove_gzip_timestamp(filename: str, gunzip_executable: str = "gunzip", gzip_executable: str = "gzip", gzip_args: List[str] = None) -> None: """ Uses external ``gunzi...
As a python code expert, you are capable of creating scripts from specifications.
Replaces text in a file.
Can you tell what is the following Python 3 function doing def replace_in_file(filename: str, text_from: str, text_to: str) -> None: log.info("Amending {}: {} -> {}", filename, repr(text_from), repr(text_to)) with open(filename) as infile: contents = infile.read() contents = contents.re...
As a python code expert, you are capable of creating scripts from specifications.
def replace_multiple_in_file(filename: str, replacements: List[Tuple[str, str]]) -> None: """ Replaces multiple from/to string pairs within a single file. Args: filename: filename to process (modifying it in place) replacements: list of ``(from_text, to_text)`` ...
Implement a function in Python 3 to replace multiple from and to strings pairs within a single file.
You are a Python code generator, capable of creating scripts from specifications.
def convert_line_endings(filename: str, to_unix: bool = False, to_windows: bool = False) -> None: """ Converts a file (in place) from UNIX to Windows line endings, or the reverse. Args: filename: filename to modify (in place) to_unix: convert Windows (CR LF) to ...
Write a Python 3 function for converting a file from UNIX to Windows line endings or the alphabetical order.
As a Python code analyst, you investigate and solve complex coding mysteries
Detects whether a line is present within a file.
How would you explain what the following Python 3 function does def is_line_in_file(filename: str, line: str) -> bool: assert "\n" not in line with open(filename, "r") as file: for fileline in file: if fileline == line: return True return False
As a Python code analyst, you investigate and solve complex coding mysteries
Adds a line to the file if it s not already in the file.
Can you generate a brief explanation for the following Python 3 code def add_line_if_absent(filename: str, line: str) -> None: assert "\n" not in line if not is_line_in_file(filename, line): log.info("Appending line {!r} to file {!r}", line, filename) with open(filename, "a") as file: ...
You are a Python code architect, reviewing and designing scalable and efficient code
def is_get_query_with_results(results): """ :param results: the response from Elasticsearch :return: true if the get query returned a result, false otherwise """ return results and EsConst.FOUND in results and results[EsConst.FOUND] and EsConst.FIELDS in results
Can you write a function in Python 3 where it checks if the get query returned a result and return a boolean
You are a Python code architect, reviewing and designing scalable and efficient code
Check if there s a failed shard in the scan query and if so raise an exception.
Can you tell what is the following Python 3 function doing def validate_scan_result(results): if results[EsConst.SHARDS][EsConst.FAILED] and results[EsConst.SHARDS][EsConst.FAILED] > 0: raise ScanError( 'Scroll request has failed on %d shards out of %d.' % (results[Es...
You are a Python code analyst, evaluating scripts for potential improvements.
Takes an object and test to see if it can be represented as a dictionary. If it can be return a list of tuples. If it can be return a list of tuples.
Can you generate the documentation for the following Python 3 function def to_key_val_list(value, sort=False, insensitive=False): if value is None: return None if isinstance(value, (str, bytes, bool, int)): raise ValueError('cannot encode objects that are not 2-tuples') if isinstance(value...
As a Python code composer, you craft elegant and concise scripts.
def to_key_val_dict(values): """ Take an object and test to see if it can be represented as a dictionary. If it can be, return a list of tuples, e.g., :: >>> to_key_val_dict([('key', 'val')]) {'key': 'val'} >>> to_key_val_dict({'key': 'val'}) {'key': 'val'} >>> to...
How would you code a function in Python 3 to convert a dictionary of values into a key - value dictionary.
As a Python code translator, you convert algorithms and pseudocode into Python.
Checks that value is one of the valid option in choices
Can you generate the documentation for the following Python 3 function def valid_choice(strvalue: str, choices: Iterable[Tuple[str, str]]) -> bool: return strvalue in [str(x[0]) for x in choices]
As a Python code analyst, you investigate and solve complex coding mysteries
Returns the explanation associated with a Django choice tuple - list.
Can you generate the documentation for the following Python 3 function def choice_explanation(value: str, choices: Iterable[Tuple[str, str]]) -> str: for k, v in choices: if k == value: return v return ''
You are a Python code architect, reviewing and designing scalable and efficient code
def teed_call(cmd_args, stdout_targets: List[TextIO] = None, stderr_targets: List[TextIO] = None, encoding: str = sys.getdefaultencoding(), **kwargs): """ Runs a command and captures its output via :func:`tee` to one or more destinations. The output i...
Create a Python 3 function for running a command and captures its output to one or more TEED files.
You are a Python code analyst, evaluating scripts for potential improvements.
def write(self, message: str) -> None: """ To act as a file. """ self.underlying_stream.write(message) self.file.write(message)
Write a Python 3 function for writing a message to the underlying stream.
You are a Python code generator, capable of creating scripts from specifications.
Flushes the underlying stream and file.
How would you explain what the following Python 3 function does def flush(self) -> None: self.underlying_stream.flush() self.file.flush() os.fsync(self.file.fileno())
As a Python code translator, you convert algorithms and pseudocode into Python.
def close(self) -> None: """ To act as a file. """ if self.underlying_stream: if self.using_stdout: sys.stdout = self.underlying_stream else: sys.stderr = self.underlying_stream self.underlying_stream = None if s...
Create a Python 3 function to close the file and the underlying stream.
You are a Python code generator, capable of creating scripts from specifications.
def bootstrap(array): """ Provides a bootstrap resampling of an array. Provides another statistical method to estimate the variance of a dataset. For a `PCA` object in this library, it should be applied to `Orientation.array` method. """ reg_func = lambda a: N.linalg.svd(a,full_matrices=Fal...
How would you code a function in Python 3 to provide a bootstrap resampling of an array.
As a Python code composer, you craft elegant and concise scripts.
def sql_string_literal(text: str) -> str: """ Transforms text into its ANSI SQL-quoted version, e.g. (in Python ``repr()`` format): .. code-block:: none "some string" -> "'some string'" "Jack's dog" -> "'Jack''s dog'" """ # ANSI SQL: http://www.contrib.andrew.cmu.edu/~shad...
Write a Python 3 function for transforming text into its ANSI SQL - quoted version e. g. in Python 3. 6.
As a python code expert, you are capable of creating scripts from specifications.
Transforms a Python object that is of duck type datetime. datetime into an ANSI SQL literal string like 2000 - 12 - 31 23 - 59 - 59.123456.
Explain what the following Python 3 code does def sql_datetime_literal(dt: DateTimeLikeType, subsecond: bool = False) -> str: """ Transforms a Python object that is of duck type ``datetime.datetime`` into an ANSI SQL literal string, like ``'2000-12-31 23:59:59'``, or if ``subsec...
As a python code expert, you are capable of creating scripts from specifications.
def sql_comment(comment: str) -> str: """ Transforms a single- or multi-line string into an ANSI SQL comment, prefixed by ``--``. """ """Using -- as a comment marker is ANSI SQL.""" if not comment: return "" return "\n".join("-- {}".format(x) for x in comment.splitlines())
Can you write a function in Python 3 where it transforms a single - line string into an ANSI SQL comment.
As a python code expert, you are capable of creating scripts from specifications.
def sql_dequote_string(s: str) -> str: """ Reverses :func:`sql_quote_string`. """ if len(s) < 2 or s[0] != SQUOTE or s[-1] != SQUOTE: raise ValueError("Not an SQL string literal") s = s[1:-1] # strip off the surrounding quotes return s.replace(DOUBLE_SQUOTE, SQUOTE)
Create a Python 3 function for removing double quotes from a SQL string.
As a python code expert, you are capable of creating scripts from specifications.
Yields the items from a SQL string.
Explain what the following Python 3 code does def gen_items_from_sql_csv(s: str) -> Generator[str, None, None]: # csv.reader will not both process the quotes and return the quotes; # we need them to distinguish e.g. NULL from 'NULL'. # log.warning('gen_items_from_sql_csv: s = {0!r}', s) if not s: ...
As a Python code analyst, you investigate and solve complex coding mysteries
Given a dictionary d and a key k return the key that matches k.
Make a summary of the following Python 3 code def get_case_insensitive_dict_key(d: Dict, k: str) -> Optional[str]: for key in d.keys(): if k.lower() == key.lower(): return key return None
As a Python code analyst, you investigate and solve complex coding mysteries
Given two dicts merge them into a new dict as a shallow copy
Given the following Python 3 function, write the documentation def merge_two_dicts(x: Dict, y: Dict) -> Dict: z = x.copy() z.update(y) return z
As a Python code composer, you craft elegant and concise scripts.
def rename_key(d: Dict[str, Any], old: str, new: str) -> None: """ Rename a key in dictionary ``d`` from ``old`` to ``new``, in place. """ d[new] = d.pop(old)
Write a Python 3 function that can rename a key in dictionary d from old to new in place.
As a Python code analyst, you investigate and solve complex coding mysteries
def rename_keys(d: Dict[str, Any], mapping: Dict[str, str]) -> Dict[str, Any]: """ Returns a copy of the dictionary ``d`` with its keys renamed according to ``mapping``. Args: d: the starting dictionary mapping: a dictionary of the format ``{old_key_name: new_key_name}`` Returns: ...
Write a Python 3 function for returning a copy of the dictionary d with the keys renamed according to mapping.
You are a Python code analyst, evaluating scripts for potential improvements.
def rename_keys_in_dict(d: Dict[str, Any], renames: Dict[str, str]) -> None: """ Renames, IN PLACE, the keys in ``d`` according to the mapping in ``renames``. Args: d: a dictionary to modify renames: a dictionary of the format ``{old_key_name: new_key_name}`` See h...
Can you write a function in Python 3 where it renames the keys in the dictionary d according to the mapping renames.
You are a Python code architect, reviewing and designing scalable and efficient code
def prefix_dict_keys(d: Dict[str, Any], prefix: str) -> Dict[str, Any]: """ Returns a dictionary that's a copy of as ``d`` but with ``prefix`` prepended to its keys. """ result = {} # type: Dict[str, Any] for k, v in d.items(): result[prefix + k] = v return result
Implement a function in Python 3 to return a copy of d but with prefix prepended to its keys.
As a Python code composer, you craft elegant and concise scripts.
def reversedict(d: Dict[Any, Any]) -> Dict[Any, Any]: """ Takes a ``k -> v`` mapping and returns a ``v -> k`` mapping. """ return {v: k for k, v in d.items()}
Write a Python 3 function that can take a k - > v mapping and returns a k - > v mapping.
You are a Python code analyst, evaluating scripts for potential improvements.
Sets any null values found in null_literals with None.
Given the following Python 3 function, write the documentation def set_null_values_in_dict(d: Dict[str, Any], null_literals: List[Any]) -> None: """ Within ``d`` (in place), replace any values found in ``null_literals`` with ``None``. """ if not null_literals: ret...
You are a Python code architect, reviewing and designing scalable and efficient code
def map_keys_to_values(l: List[Any], d: Dict[Any, Any], default: Any = None, raise_if_missing: bool = False, omit_if_missing: bool = False) -> List[Any]: """ The ``d`` dictionary contains a ``key -> value`` mapping. We start with a list of potential keys in ``l...
Write a Python 3 script to map keys in a list of objects to their corresponding values.
You are a Python code architect, reviewing and designing scalable and efficient code
def dict_diff(d1: Dict[Any, Any], d2: Dict[Any, Any], deleted_value: Any = None) -> Dict[Any, Any]: """ Returns a representation of the changes that need to be made to ``d1`` to create ``d2``. Args: d1: a dictionary d2: another dictionary deleted_value: value to us...
How would you implement a function in Python 3 that returns a dictionary that contains the changes made to d1 to d2.
As a Python code translator, you convert algorithms and pseudocode into Python.
def delete_keys(d: Dict[Any, Any], keys_to_delete: List[Any], keys_to_keep: List[Any]) -> None: """ Deletes keys from a dictionary, in place. Args: d: dictonary to modify keys_to_delete: if any keys are present in this list, they are d...
Can you create a Python 3 function that deletes keys from a dictionary in place.
As a Python code composer, you craft elegant and concise scripts.
Convert things on the way from Python to database.
Can you tell what is the following Python 3 function doing def process_bind_param(self, value: Optional[List[str]], dialect: Dialect) -> str: """Convert things on the way from Python to the database.""" retval = self._strlist_to_dbstr(value) return retval
You are a Python code architect, reviewing and designing scalable and efficient code
Convert things on the way from the database to Python.
Make a summary of the following Python 3 code def process_result_value(self, value: Optional[str], dialect: Dialect) -> List[str]: """Convert things on the way from the database to Python.""" retval = self._dbstr_to_strlist(value) return retval
As a Python code analyst, you investigate and solve complex coding mysteries
Convert things on the way from Python to the database.
Can you generate a brief explanation for the following Python 3 code def process_literal_param(self, value: Optional[List[int]], dialect: Dialect) -> str: """Convert things on the way from Python to the database.""" retval = self._intlist_to_dbstr(value) return retv...
As a Python code analyst, you investigate and solve complex coding mysteries
Convert things on the way from the database to Python.
Can you generate a brief explanation for the following Python 3 code def process_result_value(self, value: Optional[str], dialect: Dialect) -> List[int]: """Convert things on the way from the database to Python.""" retval = self._dbstr_to_intlist(value) return retval
As a python code expert, you are capable of creating scripts from specifications.
Set the timing parameter.
Given the following Python 3 function, write the documentation def set_timing(self, timing: bool, reset: bool = False) -> None: self._timing = timing if reset: self.reset()
You are a Python code architect, reviewing and designing scalable and efficient code
Start a named timer.
Can you generate a brief explanation for the following Python 3 code def start(self, name: str, increment_count: bool = True) -> None: if not self._timing: return now = get_now_utc_pendulum() # If we were already timing something else, pause that. if self._stack: ...
As a python code expert, you are capable of creating scripts from specifications.
def stop(self, name: str) -> None: """ Stop a named timer. Args: name: timer to stop """ if not self._timing: return now = get_now_utc_pendulum() # Validity check if not self._stack: raise AssertionError("MultiTimer.st...
Create a Python 3 function to stop a named timer.
As a Python code composer, you craft elegant and concise scripts.
def girdle_error(ax, fit, **kwargs): """ Plot an attitude measurement on an `mplstereonet` axes object. """ vertices = [] codes = [] for sheet in ('upper','lower'): err = plane_errors(fit.axes, fit.covariance_matrix, sheet=sheet) lonlat = N.array(err) lonl...
Can you create a Python 3 function that plots an attitude measurement on an object.
You are a Python code architect, reviewing and designing scalable and efficient code
def pole_error(ax, fit, **kwargs): """ Plot the error to the pole to a plane on a `mplstereonet` axis object. """ ell = normal_errors(fit.axes, fit.covariance_matrix) lonlat = -N.array(ell) n = len(lonlat) codes = [Path.MOVETO] codes += [Path.LINETO]*(n-1) vertices = list(lonlat)...
How would you implement a function in Python 3 that plots the error to the pole to a plane on a matplotlibstereonet object.
You are a Python code generator, capable of creating scripts from specifications.
def ping(hostname: str, timeout_s: int = 5) -> bool: """ Pings a host, using OS tools. Args: hostname: host name or IP address timeout_s: timeout in seconds Returns: was the ping successful? """ if sys.platform == "win32": timeout_ms = timeout_s * 1000 ...
Create a Python 3 function to ping a host using OS tools.
As a python code expert, you are capable of creating scripts from specifications.
def download(url: str, filename: str, skip_cert_verify: bool = True) -> None: """ Downloads a URL to a file. Args: url: URL to download from filename: file to save to skip_cert_verify: skip SSL certificate check? """ log.info("Downloading from {} to {}", url, fi...
Create a Python 3 function to download a URL to a file.
As a Python code translator, you convert algorithms and pseudocode into Python.
Generates binary files from a series of URLs.
Can you tell what is the following Python 3 function doing def gen_binary_files_from_urls( urls: Iterable[str], on_disk: bool = False, show_info: bool = True) -> Generator[BinaryIO, None, None]: """ Generate binary files from a series of URLs (one per URL). Args: urls: itera...
You are a Python code analyst, evaluating scripts for potential improvements.
Finds the position of nth occurrence of x in s or - 1 if there isn t one.
Given the following Python 3 function, write the documentation def find_nth(s: str, x: str, n: int = 0, overlap: bool = False) -> int: length_of_fragment = 1 if overlap else len(x) i = -length_of_fragment for _ in range(n + 1): i = s.find(x, i + length_of_fragment) if i < 0: brea...
As a Python code translator, you convert algorithms and pseudocode into Python.
Split string into chunks of length n
Can you tell what is the following Python 3 function doing def split_string(x: str, n: int) -> List[str]: # https://stackoverflow.com/questions/9475241/split-string-every-nth-character # noqa return [x[i:i+n] for i in range(0, len(x), n)]
You are a Python code generator, capable of creating scripts from specifications.
Returns a version of text with the keys of rep replaced by their values.
Can you generate a brief explanation for the following Python 3 code def multiple_replace(text: str, rep: Dict[str, str]) -> str: rep = dict((re.escape(k), v) for k, v in rep.items()) pattern = re.compile("|".join(rep.keys())) return pattern.sub(lambda m: rep[re.escape(m.group(0))], text)
As a Python code analyst, you investigate and solve complex coding mysteries
def replace_in_list(stringlist: Iterable[str], replacedict: Dict[str, str]) -> List[str]: """ Returns a list produced by applying :func:`multiple_replace` to every string in ``stringlist``. Args: stringlist: list of source strings replacedict: dictionary mapping "ori...
Can you write a function in Python 3 where it returns a list of strings produced by applying multiple_replace to every string in stringlist.
As a python code expert, you are capable of creating scripts from specifications.
def mangle_unicode_to_ascii(s: Any) -> str: """ Mangle unicode to ASCII, losing accents etc. in the process. """ # http://stackoverflow.com/questions/1207457 if s is None: return "" if not isinstance(s, str): s = str(s) return ( unicodedata.normalize('NFKD', s) ...
Write a Python 3 script for mangling unicode to ASCII losing accents etc. in the process.
As a python code expert, you are capable of creating scripts from specifications.
Makes a string of the format <prefix><number><suffix >.
How would you explain what the following Python 3 function does def strnum(prefix: str, num: int, suffix: str = "") -> str: return "{}{}{}".format(prefix, num, suffix)
As a Python code translator, you convert algorithms and pseudocode into Python.
def strnumlist(prefix: str, numbers: List[int], suffix: str = "") -> List[str]: """ Makes a string of the format ``<prefix><number><suffix>`` for every number in ``numbers``, and returns them as a list. """ return ["{}{}{}".format(prefix, num, suffix) for num in numbers]
Implement a function in Python 3 to make a string of the format <prefix><number><suffix > for every number in numbers and returns them as a list.
You are a Python code analyst, evaluating scripts for potential improvements.
def strseq(prefix: str, first: int, last: int, suffix: str = "") -> List[str]: """ Makes a string of the format ``<prefix><number><suffix>`` for every number from ``first`` to ``last`` inclusive, and returns them as a list. """ return [strnum(prefix, n, suffix) for n in range(first, last + 1)]
How would you code a function in Python 3 to make a string of the format <prefix><number><suffix > for every number from first to last inclusive.
As a Python code composer, you craft elegant and concise scripts.
def aligned_residuals(pca): """ Plots error components along with bootstrap resampled error surface. Provides another statistical method to estimate the variance of a dataset. """ A = pca.rotated() fig, axes = P.subplots(2,1, sharex=True, frameon=False) fig.subplots_adjus...
Can you implement a function in Python 3 that calculates the variance of a bootstrap .
You are a Python code architect, reviewing and designing scalable and efficient code
def get_instance(self): """ Returns the singleton instance. Upon its first call, it creates a new instance of the decorated class and calls its `__init__` method. On all subsequent calls, the already created instance is returned. """ try: return self._instance...
Create a Python 3 function to return the singleton instance of the class.
As a Python code analyst, you investigate and solve complex coding mysteries
build local spatial index of US metro areas
Make a summary of the following Python 3 code def mapper_init(self): self.lookup = CachedMetroLookup(precision=GEOHASH_PRECISION) self.extractor = WordExtractor()
As a python code expert, you are capable of creating scripts from specifications.
def reducer_init_output(self): """ establish connection to MongoDB """ try: self.mongo = MongoGeo(db=DB, collection=COLLECTION, timeout=MONGO_TIMEOUT) except ServerSelectionTimeoutError: # failed to connect to running MongoDB instance self.mongo = None
Write a Python 3 function for establishing connection to MongoDB instance and initialize the object
You are a Python code generator, capable of creating scripts from specifications.
Save the instance to the database.
Can you tell what is the following Python 3 function doing def save(self, *args, **kwargs): slug = "{}:{}".format(self.level.uid, self.code) if self.parent: self.uid = "{}_{}".format(self.parent.uid, slug) else: self.uid = slug self.slug = uuslug( self...
You are a Python code generator, capable of creating scripts from specifications.
Adds paired relationships between intersecting divisions.
How would you explain what the following Python 3 function does def add_intersecting(self, division, intersection=None, symm=True): relationship, created = IntersectRelationship.objects.update_or_create( from_division=self, to_division=division, defaults={"intersection": inte...
You are a Python code architect, reviewing and designing scalable and efficient code
def remove_intersecting(self, division, symm=True): """Removes paired relationships between intersecting divisions""" IntersectRelationship.objects.filter( from_division=self, to_division=division ).delete() if symm: division.remove_intersecting(self, False)
How would you implement a function in Python 3 that removes paired relationships between intersecting divisions
As a Python code translator, you convert algorithms and pseudocode into Python.