output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
def is_sqlatype_text_of_length_at_least( coltype: Union[TypeEngine, VisitableType], min_length: int = 1000) -> bool: """ Is the SQLAlchemy column type a string type that's at least the specified length? """ coltype = _coltype_to_typeengine(coltype) if not isinstance(coltype, sqlt...
Write a Python 3 function for being the SQLAlchemy column type a string type that s at least the specified min_length?
As a Python code translator, you convert algorithms and pseudocode into Python.
def is_sqlatype_text_over_one_char( coltype: Union[TypeEngine, VisitableType]) -> bool: """ Is the SQLAlchemy column type a string type that's more than one character long? """ coltype = _coltype_to_typeengine(coltype) return is_sqlatype_text_of_length_at_least(coltype, 2)
Implement a function in Python 3 to am the SQLAlchemy column type a string type that s more than one character?
As a Python code composer, you craft elegant and concise scripts.
Returns True if the SQLAlchemy column type is a FULLTEXT column type.
Make a summary of the following Python 3 code def does_sqlatype_merit_fulltext_index( coltype: Union[TypeEngine, VisitableType], min_length: int = 1000) -> bool: """ Is the SQLAlchemy column type a type that might merit a ``FULLTEXT`` index (meaning a string type of at least ``min_length``)?...
As a Python code composer, you craft elegant and concise scripts.
def does_sqlatype_require_index_len( coltype: Union[TypeEngine, VisitableType]) -> bool: """ Is the SQLAlchemy column type one that requires its indexes to have a length specified? (MySQL, at least, requires index length to be specified for ``BLOB`` and ``TEXT`` columns: http://dev.mysq...
Can you create a Python 3 function that returns True if the SQLAlchemy column type does not require an index length.
You are a Python code generator, capable of creating scripts from specifications.
def column_types_equal(a_coltype: TypeEngine, b_coltype: TypeEngine) -> bool: """ Checks that two SQLAlchemy column types are equal (by comparing ``str()`` versions of them). See http://stackoverflow.com/questions/34787794/sqlalchemy-column-type-comparison. IMPERFECT. """ # noqa ...
Can you create a Python 3 function that checks that two SQLAlchemy column types are equal.
As a Python code analyst, you investigate and solve complex coding mysteries
Check if two SQLAlchemy columns are equal?
How would you explain what the following Python 3 function does def columns_equal(a: Column, b: Column) -> bool: return ( a.name == b.name and column_types_equal(a.type, b.type) and a.nullable == b.nullable )
You are a Python code generator, capable of creating scripts from specifications.
Returns True if all columns in list a equal to their counterparts in list b.
Explain what the following Python 3 code does def column_lists_equal(a: List[Column], b: List[Column]) -> bool: n = len(a) if len(b) != n: return False for i in range(n): if not columns_equal(a[i], b[i]): log.debug("Mismatch: {!r} != {!r}", a[i], b[i]) return False ...
As a python code expert, you are capable of creating scripts from specifications.
def indexes_equal(a: Index, b: Index) -> bool: """ Are two indexes equal? Checks by comparing ``str()`` versions of them. (AM UNSURE IF THIS IS ENOUGH.) """ return str(a) == str(b)
Can you implement a function in Python 3 that is two indexes equal? Checks by comparing str versions of them.
As a Python code translator, you convert algorithms and pseudocode into Python.
def index_lists_equal(a: List[Index], b: List[Index]) -> bool: """ Are all indexes in list ``a`` equal to their counterparts in list ``b``, as per :func:`indexes_equal`? """ n = len(a) if len(b) != n: return False for i in range(n): if not indexes_equal(a[i], b[i]): ...
Write a Python 3 function that can test if two lists are equal.
You are a Python code analyst, evaluating scripts for potential improvements.
Convert any string to a bytearray.
Can you tell what is the following Python 3 function doing def to_bytes(data: Any) -> bytearray: if isinstance(data, int): return bytearray([data]) return bytearray(data, encoding='latin-1')
As a python code expert, you are capable of creating scripts from specifications.
def signed_to_twos_comp(val: int, n_bits: int) -> int: """ Convert a signed integer to its "two's complement" representation. Args: val: signed integer n_bits: number of bits (which must reflect a whole number of bytes) Returns: unsigned integer: two's complement version "...
Create a Python 3 function to convert a signed integer to its two s complement representation.
As a python code expert, you are capable of creating scripts from specifications.
def bytes_to_long(bytesdata: bytes) -> int: """ Converts an 8-byte sequence to a long integer. Args: bytesdata: 8 consecutive bytes, as a ``bytes`` object, in little-endian format (least significant byte [LSB] first) Returns: integer """ assert len(bytesdata) == 8 ...
Write a Python 3 function for converting an 8 - byte sequence to a long integer.
You are a Python code analyst, evaluating scripts for potential improvements.
def pymmh3_hash128_x64(key: Union[bytes, bytearray], seed: int) -> int: """ Implements 128-bit murmur3 hash for x64, as per ``pymmh3``, with some bugfixes. Args: key: data to hash seed: seed Returns: integer hash """ def fmix(k): k ^= k >> 33 k = (k...
Implement a Python 3 function for implementing 128 - bit murmur3 hash for x64.
As a Python code translator, you convert algorithms and pseudocode into Python.
def pymmh3_hash128_x86(key: Union[bytes, bytearray], seed: int) -> int: """ Implements 128-bit murmur3 hash for x86, as per ``pymmh3``, with some bugfixes. Args: key: data to hash seed: seed Returns: integer hash """ def fmix(h): h ^= h >> 16 h = (h...
Implement a Python 3 function for implementing 128 - bit murmur3 hash for x86.
As a Python code composer, you craft elegant and concise scripts.
Implements 128bit murmur3 hash as per pymmh3.
Can you tell what is the following Python 3 function doing def pymmh3_hash128(key: Union[bytes, bytearray], seed: int = 0, x64arch: bool = True) -> int: """ Implements 128bit murmur3 hash, as per ``pymmh3``. Args: key: data to hash seed: seed x6...
As a Python code composer, you craft elegant and concise scripts.
def pymmh3_hash64(key: Union[bytes, bytearray], seed: int = 0, x64arch: bool = True) -> Tuple[int, int]: """ Implements 64bit murmur3 hash, as per ``pymmh3``. Returns a tuple. Args: key: data to hash seed: seed x64arch: is a 64-bit architecture av...
How would you implement a function in Python 3 that implements 64bit murmur3 hash as per pymmh3. Returns a tuple of integers signed_val1 signed_val2.
As a Python code composer, you craft elegant and concise scripts.
Compare the pure Python implementation of 32 - bit murmur3 against the MurmurHash3 C - based module.
Explain what the following Python 3 code does def compare_python_to_reference_murmur3_32(data: Any, seed: int = 0) -> None: assert mmh3, "Need mmh3 module" c_data = to_str(data) c_signed = mmh3.hash(c_data, seed=seed) # 32 bit py_data = to_bytes(c_data) py_unsigned = murmur3_x86_32(py_data, seed=se...
As a Python code translator, you convert algorithms and pseudocode into Python.
Compare the pure Python implementation of 64 - bit murmur3 against the MurmurHash3 C - based module.
Make a summary of the following Python 3 code def compare_python_to_reference_murmur3_64(data: Any, seed: int = 0) -> None: assert mmh3, "Need mmh3 module" c_data = to_str(data) c_signed_low, c_signed_high = mmh3.hash64(c_data, seed=seed, x64arch=IS_64_BIT) ...
As a Python code analyst, you investigate and solve complex coding mysteries
def hash32(data: Any, seed=0) -> int: """ Non-cryptographic, deterministic, fast hash. Args: data: data to hash seed: seed Returns: signed 32-bit integer """ with MultiTimerContext(timer, TIMING_HASH): c_data = to_str(data) if mmh3: return mm...
Write a Python 3 function for hashing the data with the specified seed.
You are a Python code architect, reviewing and designing scalable and efficient code
Hash the data with the seed and return the signed 64 - bit integer.
Explain what the following Python 3 code does def hash64(data: Any, seed: int = 0) -> int: # ------------------------------------------------------------------------- # MurmurHash3 # ------------------------------------------------------------------------- c_data = to_str(data) if mmh3: c_si...
As a Python code analyst, you investigate and solve complex coding mysteries
def main() -> None: """ Command-line validation checks. """ _ = """ print(twos_comp_to_signed(0, n_bits=32)) # 0 print(twos_comp_to_signed(2 ** 31 - 1, n_bits=32)) # 2147483647 print(twos_comp_to_signed(2 ** 31, n_bits=32)) # -2147483648 == -(2 ** 31) print(twos_comp_to_signed(2 ** 32...
Can you implement a function in Python 3 that commands - line validation checks.
You are a Python code generator, capable of creating scripts from specifications.
Returns the hex digest of a HMAC - encoded version of the input.
Explain what the following Python 3 code does def hash(self, raw: Any) -> str: with MultiTimerContext(timer, TIMING_HASH): raw_bytes = str(raw).encode('utf-8') hmac_obj = hmac.new(key=self.key_bytes, msg=raw_bytes, digestmod=self.digestmod) ret...
As a Python code analyst, you investigate and solve complex coding mysteries
Returns the mean of a list of numbers.
Can you generate a brief explanation for the following Python 3 code def mean(values: Sequence[Union[int, float, None]]) -> Optional[float]: total = 0.0 # starting with "0.0" causes automatic conversion to float n = 0 for x in values: if x is not None: total += x n += 1 ...
As a Python code analyst, you investigate and solve complex coding mysteries
r Returns the logit of the input probability p
Given the following Python 3 function, write the documentation def safe_logit(p: Union[float, int]) -> Optional[float]: if p > 1 or p < 0: return None # can't take log of negative number if p == 1: return float("inf") if p == 0: return float("-inf") return math.log(p / (1 - p))
As a Python code analyst, you investigate and solve complex coding mysteries
Normal round to a number of decimal places.
Here you have a function in Python 3, explain what it does def normal_round_float(x: float, dp: int = 0) -> float: if not math.isfinite(x): return x factor = pow(10, dp) x = x * factor if x >= 0: x = math.floor(x + 0.5) else: x = math.ceil(x - 0.5) x = x / factor retu...
As a Python code analyst, you investigate and solve complex coding mysteries
Returns an integer from 0 to x.
How would you explain what the following Python 3 function does def normal_round_int(x: float) -> int: if not math.isfinite(x): raise ValueError("Input to normal_round_int() is not finite") if x >= 0: # noinspection PyTypeChecker return math.floor(x + 0.5) else: # noinspectio...
You are a Python code analyst, evaluating scripts for potential improvements.
def cmdargs(mysqldump: str, username: str, password: str, database: str, verbose: bool, with_drop_create_database: bool, max_allowed_packet: str, hide_password: bool = False) -> List[str]: """ Returns command arguments for a ``m...
Can you create a Python 3 function that returns a list of command - line arguments for a mysqldump call.
You are a Python code generator, capable of creating scripts from specifications.
def get_dialect(mixed: Union[SQLCompiler, Engine, Dialect]) -> Dialect: """ Finds the SQLAlchemy dialect in use. Args: mixed: an SQLAlchemy :class:`SQLCompiler`, :class:`Engine`, or :class:`Dialect` object Returns: the SQLAlchemy :class:`Dialect` being used """ if isinstan...
Write a Python 3 script to return the SQLAlchemy dialect that is used by the given object.
As a Python code composer, you craft elegant and concise scripts.
Returns the name of the SQLAlchemy dialect in use.
Make a summary of the following Python 3 code def get_dialect_name(mixed: Union[SQLCompiler, Engine, Dialect]) -> str: dialect = get_dialect(mixed) # noinspection PyUnresolvedReferences return dialect.name
You are a Python code analyst, evaluating scripts for potential improvements.
Returns the SQLAlchemy identifier preparer for the given SQLAlchemy object.
Can you generate a brief explanation for the following Python 3 code def get_preparer(mixed: Union[SQLCompiler, Engine, Dialect]) -> IdentifierPreparer: """ Returns the SQLAlchemy :class:`IdentifierPreparer` in use for the dialect being used. Args: mixed: an SQLAlc...
You are a Python code architect, reviewing and designing scalable and efficient code
Converts an SQL identifier to a quoted version via the SQL dialect in attery.
Can you tell what is the following Python 3 function doing def quote_identifier(identifier: str, mixed: Union[SQLCompiler, Engine, Dialect]) -> str: """ Converts an SQL identifier to a quoted version, via the SQL dialect in use. Args: identifier: the identifier to be quoted...
You are a Python code generator, capable of creating scripts from specifications.
Download the ANTLR v4 tool jar.
Can you tell what is the following Python 3 function doing def install(force=False, lazy=False): if exists(antlr_jar_path): if lazy: return if not force: raise OSError(errno.EEXIST, 'file already exists', antlr_jar_path) tool_url = config['tool_url'] ssl_context = s...
As a python code expert, you are capable of creating scripts from specifications.
Escape a single tab - separated value for TSV format.
Explain what the following Python 3 code does def tsv_escape(x: Any) -> str: if x is None: return "" x = str(x) return x.replace("\t", "\\t").replace("\n", "\\n")
You are a Python code generator, capable of creating scripts from specifications.
Make a TSV row from a list of values.
Can you generate a brief explanation for the following Python 3 code def make_tsv_row(values: List[Any]) -> str: return "\t".join([tsv_escape(x) for x in values]) + "\n"
As a Python code translator, you convert algorithms and pseudocode into Python.
Converts a consistent list of dictionaries mapping fieldnames to values make a TSV file.
Here you have a function in Python 3, explain what it does def dictlist_to_tsv(dictlist: List[Dict[str, Any]]) -> str: if not dictlist: return "" fieldnames = dictlist[0].keys() tsv = "\t".join([tsv_escape(f) for f in fieldnames]) + "\n" for d in dictlist: tsv += "\t".join([tsv_escape(v)...
As a Python code composer, you craft elegant and concise scripts.
r Converts a TSV line into a dictionary.
How would you explain what the following Python 3 function does def tsv_pairs_to_dict(line: str, key_lower: bool = True) -> Dict[str, str]: items = line.split("\t") d = {} # type: Dict[str, str] for chunk in chunks(items, 2): if len(chunk) < 2: log.warning("Bad chunk, not of length 2: {...
You are a Python code analyst, evaluating scripts for potential improvements.
Imports all submodules of a module recursively including subpackages.
Can you tell what is the following Python 3 function doing def import_submodules(package: Union[str, ModuleType], base_package_for_relative_import: str = None, recursive: bool = True) -> Dict[str, ModuleType]: """ Import all submodules of a module, recursively, includ...
You are a Python code analyst, evaluating scripts for potential improvements.
Tests if a module is a C extension.
How would you explain what the following Python 3 function does def is_c_extension(module: ModuleType) -> bool: assert inspect.ismodule(module), '"{}" not a module.'.format(module) # If this module was loaded by a PEP 302-compliant CPython-specific loader # loading only C extensions, this module is a C ext...
As a Python code translator, you convert algorithms and pseudocode into Python.
Returns True if the given module object contains a C extension.
Here you have a function in Python 3, explain what it does def contains_c_extension(module: ModuleType, import_all_submodules: bool = True, include_external_imports: bool = False, seen: List[ModuleType] = None) -> bool: """ Extends :func...
You are a Python code architect, reviewing and designing scalable and efficient code
def which_with_envpath(executable: str, env: Dict[str, str]) -> str: """ Performs a :func:`shutil.which` command using the PATH from the specified environment. Reason: when you use ``run([executable, ...], env)`` and therefore ``subprocess.run([executable, ...], env=env)``, the PATH that's searched...
Write a Python 3 script to perform a :func:`shutil.which` command using the PATH from the specified environment. Reason: when you use ``run([executable, ...], env)`` and therefore ``subprocess.run([executable, ...], env=env)``, the PATH that's searched for ``executable`` is the parent's, not the new child's -- so you h...
As a Python code analyst, you investigate and solve complex coding mysteries
def require_executable(executable: str) -> None: """ If ``executable`` is not found by :func:`shutil.which`, raise :exc:`FileNotFoundError`. """ if shutil.which(executable): return errmsg = "Missing command (must be on the PATH): " + executable log.critical(errmsg) raise FileNotF...
Create a Python 3 function for requiring that the given executable is available on the PATH.
You are a Python code generator, capable of creating scripts from specifications.
def mkdir_p(path: str) -> None: """ Makes a directory, and any intermediate (parent) directories if required. This is the UNIX ``mkdir -p DIRECTORY`` command; of course, we use :func:`os.makedirs` instead, for portability. """ log.debug("mkdir -p " + path) os.makedirs(path, exist_ok=True)
Create a Python 3 function to make a directory and any intermediate directories if required.
You are a Python code generator, capable of creating scripts from specifications.
Decorator to preserve the current working directory in calls to the decorated function.
Can you generate the documentation for the following Python 3 function def preserve_cwd(func: Callable) -> Callable: # http://stackoverflow.com/questions/169070/python-how-do-i-write-a-decorator-that-restores-the-cwd # noqa def decorator(*args_, **kwargs) -> Any: cwd = os.getcwd() result = func...
You are a Python code architect, reviewing and designing scalable and efficient code
Copies files whose filenames match the glob src into the directory dest.
Can you tell what is the following Python 3 function doing def copyglob(src: str, dest: str, allow_nothing: bool = False, allow_nonfiles: bool = False) -> None: """ Copies files whose filenames match the glob src" into the directory "dest". Raises an error if no files are copied, unless allow_n...
As a Python code analyst, you investigate and solve complex coding mysteries
Copies a directory src_dir into dest_parent.
Given the following Python 3 function, write the documentation def copy_tree_root(src_dir: str, dest_parent: str) -> None: dirname = os.path.basename(os.path.normpath(src_dir)) dest_dir = os.path.join(dest_parent, dirname) shutil.copytree(src_dir, dest_dir)
As a Python code translator, you convert algorithms and pseudocode into Python.
Recursively copy the contents of srcdir to destdir.
Given the following Python 3 function, write the documentation def copy_tree_contents(srcdir: str, destdir: str, destroy: bool = False) -> None: """ Recursive copy. Unlike :func:`copy_tree_root`, :func:`copy_tree_contents` works as follows. With the file structure: .. code-block:...
You are a Python code architect, reviewing and designing scalable and efficient code
Deletes all files whose filename matches the glob pattern.
Explain what the following Python 3 code does def rmglob(pattern: str) -> None: for f in glob.glob(pattern): os.remove(f)
You are a Python code architect, reviewing and designing scalable and efficient code
Delete all files in path that match pattern.
Can you tell what is the following Python 3 function doing def purge(path: str, pattern: str) -> None: for f in find(pattern, path): log.info("Deleting {}", f) os.remove(f)
You are a Python code analyst, evaluating scripts for potential improvements.
def delete_files_within_dir(directory: str, filenames: List[str]) -> None: """ Delete files within ``directory`` whose filename *exactly* matches one of ``filenames``. """ for dirpath, dirnames, fnames in os.walk(directory): for f in fnames: if f in filenames: ful...
Create a Python 3 function for deleting files within a directory.
As a python code expert, you are capable of creating scripts from specifications.
Error handler for shutil. rmtree.
How would you explain what the following Python 3 function does def shutil_rmtree_onerror(func: Callable[[str], None], path: str, exc_info: EXC_INFO_TYPE) -> None: """ Error handler for ``shutil.rmtree``. If the error is due to an access error (read only ...
As a Python code analyst, you investigate and solve complex coding mysteries
Deletes a directory tree.
Can you generate a brief explanation for the following Python 3 code def rmtree(directory: str) -> None: log.debug("Deleting directory {!r}", directory) shutil.rmtree(directory, onerror=shutil_rmtree_onerror)
You are a Python code architect, reviewing and designing scalable and efficient code
Performs a recursive chown on the given path.
Explain what the following Python 3 code does def chown_r(path: str, user: str, group: str) -> None: for root, dirs, files in os.walk(path): for x in dirs: shutil.chown(os.path.join(root, x), user, group) for x in files: shutil.chown(os.path.join(root, x), user, group)
As a Python code translator, you convert algorithms and pseudocode into Python.
Find files in path whose filenames match pattern.
How would you explain what the following Python 3 function does def find(pattern: str, path: str) -> List[str]: result = [] for root, dirs, files in os.walk(path): for name in files: if fnmatch.fnmatch(name, pattern): result.append(os.path.join(root, name)) return result
As a Python code translator, you convert algorithms and pseudocode into Python.
Find first file in path whose filename matches pattern.
How would you explain what the following Python 3 function does def find_first(pattern: str, path: str) -> str: try: return find(pattern, path)[0] except IndexError: log.critical('''Couldn't find "{}" in "{}"''', pattern, path) raise
As a python code expert, you are capable of creating scripts from specifications.
Generates filenames of archive from a starting list of files and directories.
Can you generate a brief explanation for the following Python 3 code def gen_filenames(starting_filenames: List[str], recursive: bool) -> Generator[str, None, None]: """ From a starting list of files and/or directories, generates filenames of all files in the list, and (if ``recursive`` is...
You are a Python code generator, capable of creating scripts from specifications.
def exists_locked(filepath: str) -> Tuple[bool, bool]: """ Checks if a file is locked by opening it in append mode. (If no exception is thrown in that situation, then the file is not locked.) Args: filepath: file to check Returns: tuple: ``(exists, locked)`` See https://www.ca...
Implement a Python 3 function for checking if a file is locked by opening it in append mode.
As a Python code composer, you craft elegant and concise scripts.
def relative_filename_within_dir(filename: str, directory: str) -> str: """ Starting with a (typically absolute) ``filename``, returns the part of the filename that is relative to the directory ``directory``. If the file is *not* within the directory, returns an empty string. """ filename = os.p...
Can you implement a function in Python 3 that returns the part of the filename that is relative to the directory directory.
As a python code expert, you are capable of creating scripts from specifications.
Gets errors from HTTP response
Can you generate a brief explanation for the following Python 3 code def _get_errors(self): errors = self.json.get('data').get('failures') if errors: logger.error(errors) return errors
As a Python code translator, you convert algorithms and pseudocode into Python.
Generates the final page sequence from the starting number of sheets.
How would you explain what the following Python 3 function does def page_sequence(n_sheets: int, one_based: bool = True) -> List[int]: n_pages = calc_n_virtual_pages(n_sheets) assert n_pages % 4 == 0 half_n_pages = n_pages // 2 firsthalf = list(range(half_n_pages)) secondhalf = list(reversed(range(h...
As a python code expert, you are capable of creating scripts from specifications.
Ensures that the external tool is available on the PATH.
Can you generate the documentation for the following Python 3 function def require(executable: str, explanation: str = "") -> None: assert shutil.which(executable), "Need {!r} on the PATH.{}".format( executable, "\n" + explanation if explanation else "")
As a Python code analyst, you investigate and solve complex coding mysteries
Run an external command + / - return the results.
Here you have a function in Python 3, explain what it does def run(args: List[str], get_output: bool = False, encoding: str = sys.getdefaultencoding()) -> Tuple[str, str]: """ Run an external command +/- return the results. Returns a ``(stdout, stderr)`` tuple (both are blank strings if the ...
As a Python code composer, you craft elegant and concise scripts.
Get the number of pages in a PDF file.
Can you generate the documentation for the following Python 3 function def get_page_count(filename: str) -> int: log.debug("Getting page count for {!r}", filename) require(PDFTK, HELP_MISSING_PDFTK) stdout, _ = run([PDFTK, filename, "dump_data"], get_output=True) regex = re.compile(r"^NumberOfPages: (\d...
As a Python code translator, you convert algorithms and pseudocode into Python.
def make_blank_pdf(filename: str, paper: str = "A4") -> None: """ NOT USED. Makes a blank single-page PDF, using ImageMagick's ``convert``. """ # https://unix.stackexchange.com/questions/277892/how-do-i-create-a-blank-pdf-from-the-command-line # noqa require(CONVERT, HELP_MISSING_IMAGEMAGICK) ...
Create a Python 3 function to make a blank PDF from a single page PDF.
You are a Python code generator, capable of creating scripts from specifications.
Slice each page of the original to one real page per PDF page. Return the output filename.
Explain what the following Python 3 code does def slice_pdf(input_filename: str, output_filename: str, slice_horiz: int, slice_vert: int) -> str: """ Slice each page of the original, to convert to "one real page per PDF page". Return the output filename. """ if slice_horiz == 1 and sli...
As a python code expert, you are capable of creating scripts from specifications.
Creates a 2x1 booklet from a PDF file.
Make a summary of the following Python 3 code def booklet_nup_pdf(input_filename: str, output_filename: str, latex_paper_size: str = LATEX_PAPER_SIZE_A4) -> str: """ Takes a PDF (e.g. A4) and makes a 2x1 booklet (e.g. 2xA5 per A4). The booklet can be folded like a book and the final page...
You are a Python code architect, reviewing and designing scalable and efficient code
Rotates even - numbered pages 180 degrees.
Can you tell what is the following Python 3 function doing def rotate_even_pages_180(input_filename: str, output_filename: str) -> str: log.info("Rotating even-numbered pages 180 degrees for long-edge " "duplex printing") log.debug("... {!r} -> {!r}", input_filename, output_filename) require(PD...
You are a Python code analyst, evaluating scripts for potential improvements.
Convert a PDF file to a useful booklet PDF file.
Explain what the following Python 3 code does def convert_to_foldable(input_filename: str, output_filename: str, slice_horiz: int, slice_vert: int, overwrite: bool = False, longedge: bool = False, ...
You are a Python code generator, capable of creating scripts from specifications.
Asks MySQL for its variables and status.
Explain what the following Python 3 code does def get_mysql_vars(mysql: str, host: str, port: int, user: str) -> Dict[str, str]: """ Asks MySQL for its variables and status. Args: mysql: ``mysql`` executable filename host: host name ...
As a Python code analyst, you investigate and solve complex coding mysteries
def val_mb(valstr: Union[int, str]) -> str: """ Converts a value in bytes (in string format) to megabytes. """ try: return "{:.3f}".format(int(valstr) / (1024 * 1024)) except (TypeError, ValueError): return '?'
Write a Python 3 script to convert a value in bytes to megabytes.
As a Python code analyst, you investigate and solve complex coding mysteries
Adds a row to table for varname in megabytes.
Can you generate the documentation for the following Python 3 function def add_var_mb(table: PrettyTable, vardict: Dict[str, str], varname: str) -> None: """ Adds a row to ``table`` for ``varname``, in megabytes. """ valstr = vardict.get(varname, None) table.add_row([va...
As a python code expert, you are capable of creating scripts from specifications.
def main(): """ Command-line processor. See ``--help`` for details. """ main_only_quicksetup_rootlogger(level=logging.DEBUG) parser = argparse.ArgumentParser() parser.add_argument( "--mysql", default="mysql", help="MySQL program (default=mysql)") parser.add_argument( ...
Can you implement a function in Python 3 that commands - line processor for the formula.
As a python code expert, you are capable of creating scripts from specifications.
def report_hit_filename(zipfilename: str, contentsfilename: str, show_inner_file: bool) -> None: """ For "hits": prints either the ``.zip`` filename, or the ``.zip`` filename and the inner filename. Args: zipfilename: filename of the ``.zip`` file contentsfilenam...
Write a Python 3 script to print either the. zip filename or the. zip filename of the inner file.
As a Python code composer, you craft elegant and concise scripts.
Prints a line from a file with the. zip filename and optionally also the inner filename.
How would you explain what the following Python 3 function does def report_line(zipfilename: str, contentsfilename: str, line: str, show_inner_file: bool) -> None: """ Prints a line from a file, with the ``.zip`` filename and optionally also the inner filename. Args: zipfilename...
You are a Python code analyst, evaluating scripts for potential improvements.
Parse a zip file into a set of items.
Can you generate the documentation for the following Python 3 function def parse_zip(zipfilename: str, regex: Pattern, invert_match: bool, files_with_matches: bool, files_without_match: bool, grep_inner_file_name: bool, show_inner_file:...
As a Python code analyst, you investigate and solve complex coding mysteries
def drug_timelines( drug_events_df: DataFrame, event_lasts_for: datetime.timedelta, patient_colname: str = DEFAULT_PATIENT_COLNAME, event_datetime_colname: str = DEFAULT_DRUG_EVENT_DATETIME_COLNAME) \ -> Dict[Any, IntervalList]: """ Takes a set of drug event start ...
Can you implement a function in Python 3 that returns a dictionary of all the timelines that are amalgamated for each patient.
You are a Python code architect, reviewing and designing scalable and efficient code
def cumulative_time_on_drug( drug_events_df: DataFrame, query_times_df: DataFrame, event_lasts_for_timedelta: datetime.timedelta = None, event_lasts_for_quantity: float = None, event_lasts_for_units: str = None, patient_colname: str = DEFAULT_PATIENT_COLNAME, ...
Write a Python 3 script to return a DataFrame containing the cumulative time of the drug events and the time of the last event in the query.
As a python code expert, you are capable of creating scripts from specifications.
def find_element_by_xpath(self, xpath): """ Finds an element by xpath. :param xpath: The xpath locator of the element to find. :return: ElemLxml See lxml xpath expressions `here <http://lxml.de/xpathxslt.html#xpath>`_ """ elems = self.find_elements_by_xp...
Write a Python 3 function that can find an element by xpath.
You are a Python code generator, capable of creating scripts from specifications.
def find_elements_by_xpath(self, xpath): """ Finds multiple elements by xpath. :param xpath: The xpath locator of the elements to be found. :return: list of ElemLxml See lxml xpath expressions `here <http://lxml.de/xpathxslt.html#xpath>`_ """ from sdklib...
Can you implement a function in Python 3 that finds multiple elements by xpath.
As a python code expert, you are capable of creating scripts from specifications.
Finds an element by xpath.
How would you explain what the following Python 3 function does def find_element_by_xpath(self, xpath): from sdklib.html.elem import Elem5lib return Elem5lib(self.html_obj.find(self._convert_xpath(xpath)))
You are a Python code architect, reviewing and designing scalable and efficient code
Finds multiple elements by xpath.
Explain what the following Python 3 code does def find_elements_by_xpath(self, xpath): from sdklib.html.elem import Elem5lib return [Elem5lib(e) for e in self.html_obj.findall(self._convert_xpath(xpath))]
As a Python code composer, you craft elegant and concise scripts.
def http_response_body_should_be_this_json(context): """ Parameters: .. code-block:: json { "param1": "value1", "param2": "value2", "param3": { "param31": "value31" } } """ body_params =...
Write a Python 3 script for checking that the HTTP response body is the same as the JSON.
You are a Python code generator, capable of creating scripts from specifications.
Queue a job in Rhumba
How would you explain what the following Python 3 function does def queue(self, queue, message, params={}, uids=[]): d = { 'id': uuid.uuid1().get_hex(), 'version': 1, 'message': message, 'params': params } ser = json.dumps(d) if ...
As a Python code composer, you craft elegant and concise scripts.
Returns a dict of cluster nodes and their status information
Given the following Python 3 function, write the documentation def clusterStatus(self): servers = yield self.getClusterServers() d = { 'workers': {}, 'crons': {}, 'queues': {} } now = time.time() reverse_map = {} for sname in server...
As a python code expert, you are capable of creating scripts from specifications.
Returns the extra HTML needed to render a Deform form.
Given the following Python 3 function, write the documentation def get_head_form_html(req: "Request", forms: List[Form]) -> str: # https://docs.pylonsproject.org/projects/deform/en/latest/widget.html#widget-requirements js_resources = [] # type: List[str] css_resources = [] # type: List[str] for form ...
You are a Python code generator, capable of creating scripts from specifications.
def debug_validator(validator: ValidatorType) -> ValidatorType: """ Use as a wrapper around a validator, e.g. .. code-block:: python self.validator = debug_validator(OneOf(["some", "values"])) If you do this, the log will show the thinking of the validator (what it's trying to validate, a...
Create a Python 3 function for using as a wrapper around a validator, e.g. .. code-block:: python self.validator = debug_validator(OneOf(["some", "values"])) If you do this, the log will show the thinking of the validator (what it's trying to validate, and whether it accepted or rejected the value).
As a python code expert, you are capable of creating scripts from specifications.
Yields all the fields of a Deform.
Make a summary of the following Python 3 code def gen_fields(field: Field) -> Generator[Field, None, None]: yield field for c in field.children: for f in gen_fields(c): yield f
As a Python code composer, you craft elegant and concise scripts.
Validates the form. Args: controls: an iterable of ``(key, value)`` tuples subcontrol: Returns: a Colander ``appstruct`` Raises: ValidationFailure: on failure
Can you generate the documentation for the following Python 3 function def validate(self, controls: Iterable[Tuple[str, str]], subcontrol: str = None) -> Any: """ Validates the form. Args: controls: an iterable of ``(key, value)`` tuples ...
You are a Python code analyst, evaluating scripts for potential improvements.
Return a list of dicts with pstats print result after filtering or exclude filenames sort index and limit.
Can you tell what is the following Python 3 function doing def get_pstats_print2list(fnames, filter_fnames=None, exclude_fnames=None, sort=None, sort_reverse=None, limit=None): """Print stats with a filter or exclude filenames, sort index and limit. :param list fnames: cProfile standar...
As a Python code composer, you craft elegant and concise scripts.
Print a list of pstats dicts formatted by the given format
Given the following Python 3 function, write the documentation def print_pstats_list(pstats, pformat=None): if not pstats: return False if pformat is None: pformat = ("{method:<40s} {factor:>16s} {cumtime:>10s} " "{calls:>10s} {rcalls:>10s} {tottime:>10s} " ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Merge metrics in the internal _metrics dict to the internal _metrics list and delete the internal _metrics dict
Can you generate a brief explanation for the following Python 3 code def merge_metrics(self): self.metrics.extend(self._metrics.values()) del self._metrics
As a Python code composer, you craft elegant and concise scripts.
def add_attribute(self, name, value): """ :param name: Name of the attribute :type name: string :param value: Value of the attribute :type value: string """ self.attributes.append(Attribute(name, value))
Write a Python 3 script to add an attribute to the internal list of the attribute list.
You are a Python code architect, reviewing and designing scalable and efficient code
Adds a tag to the list of tags.
Make a summary of the following Python 3 code def add_tag(self, name, value): self.tags.append(Tag(name, value))
As a Python code composer, you craft elegant and concise scripts.
Adds a sample to the internal data structure.
Make a summary of the following Python 3 code def add_sample(self, metricId, timestamp, value, metricType=None, host=None, sparseDataStrategy='None', unit='', tags=None...
As a Python code composer, you craft elegant and concise scripts.
def pairwise(iterable): """Pair each element with its neighbors. Arguments --------- iterable : iterable Returns ------- The generator produces a tuple containing a pairing of each element with its neighbor. """ iterable = iter(iterable) left = next(iterable) for right ...
Can you create a Python 3 function that returns a generator that yields a pair of each element with its neighbors.
As a Python code analyst, you investigate and solve complex coding mysteries
def partition(pred, iterable): """Partition an iterable. Arguments --------- pred : function A function that takes an element of the iterable and returns a boolen indicating to which partition it belongs iterable : iterable Returns ------- A two-tuple ...
Write a Python 3 function that can partition an iterable into two lists where the elements on which the predicate indicated True are partitioned.
As a Python code analyst, you investigate and solve complex coding mysteries
def powerset(iterable, *, reverse=False): """Return the powerset. Arguments --------- iterable : iterable reverse : boolean Indicates whether the powerset should be returned descending by size Returns ------- A generator producing each element of the powe...
How would you code a function in Python 3 to return the powerset of the given iterable.
As a python code expert, you are capable of creating scripts from specifications.
Collect data into a multi - map.
Can you tell what is the following Python 3 function doing def multi_map(key, iterable, *, default_dict=False): result = collections.defaultdict(list) for rec in iterable: result[key(rec)].append(rec) return result if default_dict else dict(result)
As a Python code translator, you convert algorithms and pseudocode into Python.
def split(pred, iterable, *, trailing=True): """Split the iterable. Arguments ---------- pred : function A function that accepts an element retrieved from the iterable and returns a boolean indicating if it is the element on which to split iterable :...
Write a Python 3 function that can split the iterable into a list of items.
You are a Python code architect, reviewing and designing scalable and efficient code
Returns a generator that yields the specified number of elements from the iterable in chunks of specified length.
Explain what the following Python 3 code does def chunk(iterable, length): if length < 0: return () iterable = iter(iterable) result = tuple(islice(iterable, length)) while result: yield result result = tuple(islice(iterable, length))
You are a Python code generator, capable of creating scripts from specifications.
def divide_sizes(count, n): # pylint: disable=invalid-name """Evenly divide a count. Arguments --------- count : integer The number to be evenly divided n : integer The number of buckets in which to divide the number Returns ------- A list of int...
Write a Python 3 function that can divide a count by n.
As a Python code translator, you convert algorithms and pseudocode into Python.