output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
Internal function to make a : func:`repr` - style representation of an object. | Given the following Python 3 function, write the documentation
def repr_result(obj: Any, elements: List[str],
with_addr: bool = False, joiner: str = COMMA_SPACE) -> str:
"""
Internal function to make a :func:`repr`-style representation of an object.
Args:
obj: object to display
... | You are a Python code generator, capable of creating scripts from specifications. |
Convenience function for printing the object s attributes into a string - style representation. | Explain what the following Python 3 code does
def auto_repr(obj: Any, with_addr: bool = False,
sort_attrs: bool = True, joiner: str = COMMA_SPACE) -> str:
"""
Convenience function for :func:`__repr__`.
Works its way through the object's ``__dict__`` and reports accordingly.
Args:
... | As a Python code composer, you craft elegant and concise scripts. |
Simple repr function for the base class. | Explain what the following Python 3 code does
def simple_repr(obj: Any, attrnames: List[str],
with_addr: bool = False, joiner: str = COMMA_SPACE) -> str:
"""
Convenience function for :func:`__repr__`.
Works its way through a list of attribute names, and creates a ``repr()``
representatio... | You are a Python code analyst, evaluating scripts for potential improvements. |
def mapped_repr_stripping_underscores(
obj: Any, attrnames: List[str],
with_addr: bool = False, joiner: str = COMMA_SPACE) -> str:
"""
Convenience function for :func:`__repr__`.
Here, you pass a list of internal attributes, and it assumes that the
:func:`__init__` parameter names have th... | Write a Python 3 function that can
return a string representation of the object with the given attribute names stripping underscore. | As a Python code analyst, you investigate and solve complex coding mysteries |
def ordered_repr(obj: object, attrlist: Iterable[str],
joiner: str = COMMA_SPACE) -> str:
"""
Shortcut to make :func:`repr` functions ordered.
Define your :func:`__repr__` like this:
.. code-block:: python
def __repr__(self):
return ordered_repr(self, ["field1", "f... | How would you implement a function in Python 3 that
returns a string representation of the object with the given attribute list. | You are a Python code analyst, evaluating scripts for potential improvements. |
Return a pretty string representation of the object. | Given the following Python 3 function, write the documentation
def auto_str(obj: Any, indent: int = 4, width: int = 80, depth: int = None,
compact: bool = False) -> str:
"""
Make a pretty :func:`str()` representation using :func:`pprint.pformat`
and the object's ``__dict__`` attribute.
Arg... | You are a Python code generator, capable of creating scripts from specifications. |
Convert a duration in days to a NumPy timedelta64 object. | Given the following Python 3 function, write the documentation
def timedelta_days(days: int) -> timedelta64:
int_days = int(days)
if int_days != days:
raise ValueError("Fractional days passed to timedelta_days: "
"{!r}".format(days))
try:
# Do not pass e.g. 27.0; tha... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Create a result row for this application. | Here you have a function in Python 3, explain what it does
def _get_generic_two_antidep_episodes_result(
rowdata: Tuple[Any, ...] = None) -> DataFrame:
"""
Create a results row for this application.
"""
# Valid data types... see:
# - pandas.core.dtypes.common.pandas_dtype
# - https://pan... | You are a Python code generator, capable of creating scripts from specifications. |
Processes a single patient and returns a DataFrame containing the two - antidepressant episodes for that patient. | Explain what the following Python 3 code does
def two_antidepressant_episodes_single_patient(
patient_id: str,
patient_drug_date_df: DataFrame,
patient_colname: str = DEFAULT_SOURCE_PATIENT_COLNAME,
drug_colname: str = DEFAULT_SOURCE_DRUG_COLNAME,
date_colname: str = DEFAULT_SOUR... | As a Python code analyst, you investigate and solve complex coding mysteries |
Takes a pandas DataFrame or via
and returns a DataFrame containing the two - antidepressant drugs for each patient. | Given the following Python 3 function, write the documentation
def two_antidepressant_episodes(
patient_drug_date_df: DataFrame,
patient_colname: str = DEFAULT_SOURCE_PATIENT_COLNAME,
drug_colname: str = DEFAULT_SOURCE_DRUG_COLNAME,
date_colname: str = DEFAULT_SOURCE_DATE_COLNAME,
... | As a Python code analyst, you investigate and solve complex coding mysteries |
Check if the unrtf tool supports the quiet argument from a version that I m not
too sure of. | Can you generate a brief explanation for the following Python 3 code
def does_unrtf_support_quiet() -> bool:
required_unrtf_version = Version("0.21.9")
# ... probably: http://hg.savannah.gnu.org/hgweb/unrtf/
# ... 0.21.9 definitely supports --quiet
# ... 0.19.3 definitely doesn't support it
unrtf_fi... | As a python code expert, you are capable of creating scripts from specifications. |
Returns a file - like object. | Here you have a function in Python 3, explain what it does
def get_filelikeobject(filename: str = None,
blob: bytes = None) -> BinaryIO:
"""
Open a file-like object.
Guard the use of this function with ``with``.
Args:
filename: for specifying via a filename
blob:... | As a Python code analyst, you investigate and solve complex coding mysteries |
def get_file_contents(filename: str = None, blob: bytes = None) -> bytes:
"""
Returns the binary contents of a file, or of a BLOB.
"""
if not filename and not blob:
raise ValueError("no filename and no blob")
if filename and blob:
raise ValueError("specify either filename or blob")
... | How would you code a function in Python 3 to
return the contents of a file or of a BLOB. | As a Python code analyst, you investigate and solve complex coding mysteries |
def get_chardet_encoding(binary_contents: bytes) -> Optional[str]:
"""
Guess the character set encoding of the specified ``binary_contents``.
"""
if not binary_contents:
return None
if chardet is None or UniversalDetector is None:
log.warning("chardet not installed; limits detection ... | Create a Python 3 function to
guess the character set encoding of the specified binary contents. | As a Python code composer, you craft elegant and concise scripts. |
Returns the contents of a file or of a BLOB. | Make a summary of the following Python 3 code
def get_file_contents_text(
filename: str = None, blob: bytes = None,
config: TextProcessingConfig = _DEFAULT_CONFIG) -> str:
"""
Returns the string contents of a file, or of a BLOB.
"""
binary_contents = get_file_contents(filename=filename, ... | As a Python code analyst, you investigate and solve complex coding mysteries |
Returns the output of a command. | Can you generate the documentation for the following Python 3 function
def get_cmd_output(*args, encoding: str = SYS_ENCODING) -> str:
log.debug("get_cmd_output(): args = {!r}", args)
p = subprocess.Popen(args, stdout=subprocess.PIPE)
stdout, stderr = p.communicate()
return stdout.decode(encoding, error... | You are a Python code generator, capable of creating scripts from specifications. |
def get_cmd_output_from_stdin(stdint_content_binary: bytes,
*args, encoding: str = SYS_ENCODING) -> str:
"""
Returns text output of a command, passing binary data in via stdin.
"""
p = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
stdout, stderr ... | How would you code a function in Python 3 to
return text output of a command passing binary data in via stdin. | As a python code expert, you are capable of creating scripts from specifications. |
Converts a PDF file to text. | Can you generate the documentation for the following Python 3 function
def convert_pdf_to_txt(filename: str = None, blob: bytes = None,
config: TextProcessingConfig = _DEFAULT_CONFIG) -> str:
"""
Converts a PDF file to text.
Pass either a filename or a binary object.
"""
pdfto... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Returns True if there is a PDF - to - text tool available? | Here you have a function in Python 3, explain what it does
def availability_pdf() -> bool:
pdftotext = tools['pdftotext']
if pdftotext:
return True
elif pdfminer:
log.warning("PDF conversion: pdftotext missing; "
"using pdfminer (less efficient)")
return True
... | As a python code expert, you are capable of creating scripts from specifications. |
Generates XML files from a DOCX file. | Here you have a function in Python 3, explain what it does
def gen_xml_files_from_docx(fp: BinaryIO) -> Iterator[str]:
try:
z = zipfile.ZipFile(fp)
filelist = z.namelist()
for filename in filelist:
if DOCX_HEADER_FILE_REGEX.match(filename):
yield z.read(filename).... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def docx_text_from_xml(xml: str, config: TextProcessingConfig) -> str:
"""
Converts an XML tree of a DOCX file to string contents.
Args:
xml: raw XML text
config: :class:`TextProcessingConfig` control object
Returns:
contents as a string
"""
root = ElementTree.fromstrin... | Can you create a Python 3 function that
converts an XML tree of a DOCX file to a string contents. | As a Python code composer, you craft elegant and concise scripts. |
Returns a string containing the contents of an XML node within a DOCX file. | Given the following Python 3 function, write the documentation
def docx_text_from_xml_node(node: ElementTree.Element,
level: int,
config: TextProcessingConfig) -> str:
"""
Returns text from an XML node within a DOCX file.
Args:
node: an XML no... | As a Python code analyst, you investigate and solve complex coding mysteries |
def docx_table_from_xml_node(table_node: ElementTree.Element,
level: int,
config: TextProcessingConfig) -> str:
"""
Converts an XML node representing a DOCX table into a textual
representation.
Args:
table_node: XML node
level: c... | Implement a function in Python 3 to
convert an XML node representing a DOCX table into a textual representation. | As a Python code analyst, you investigate and solve complex coding mysteries |
Process text with word - wrapping. | Explain what the following Python 3 code does
def docx_process_simple_text(text: str, width: int) -> str:
if width:
return '\n'.join(textwrap.wrap(text, width=width))
else:
return text | As a Python code analyst, you investigate and solve complex coding mysteries |
This function processes a DOCX table and returns a list of text that can be used to create a new table. | Can you generate a brief explanation for the following Python 3 code
def docx_process_table(table: DOCX_TABLE_TYPE,
config: TextProcessingConfig) -> str:
"""
Converts a DOCX table to text.
Structure representing a DOCX table:
.. code-block:: none
table
.rows... | As a python code expert, you are capable of creating scripts from specifications. |
def docx_docx_iter_block_items(parent: DOCX_CONTAINER_TYPE) \
-> Iterator[DOCX_BLOCK_ITEM_TYPE]:
# only called if docx loaded
"""
Iterate through items of a DOCX file.
See https://github.com/python-openxml/python-docx/issues/40.
Yield each paragraph and table child within ``parent``, in do... | How would you implement a function in Python 3 that
iterates through items of a DOCX file. | You are a Python code architect, reviewing and designing scalable and efficient code |
def docx_docx_gen_text(doc: DOCX_DOCUMENT_TYPE,
config: TextProcessingConfig) -> Iterator[str]:
# only called if docx loaded
"""
Iterate through a DOCX file and yield text.
Args:
doc: DOCX document to process
config: :class:`TextProcessingConfig` control object
... | Write a Python 3 script to
iterate through a DOCX file and yield text. Args: doc: DOCX document to process config: :class:`TextProcessingConfig` control object Yields: pieces of text (paragraphs) | As a Python code analyst, you investigate and solve complex coding mysteries |
Converts a DOCX file to text. | Given the following Python 3 function, write the documentation
def convert_docx_to_text(
filename: str = None, blob: bytes = None,
config: TextProcessingConfig = _DEFAULT_CONFIG) -> str:
"""
Converts a DOCX file to text.
Pass either a filename or a binary object.
Args:
filename:... | You are a Python code generator, capable of creating scripts from specifications. |
def convert_odt_to_text(filename: str = None,
blob: bytes = None,
config: TextProcessingConfig = _DEFAULT_CONFIG) -> str:
"""
Converts an OpenOffice ODT file to text.
Pass either a filename or a binary object.
"""
# We can't use exactly the same metho... | Write a Python 3 script to
convert an OpenOffice ODT file to text. | As a Python code composer, you craft elegant and concise scripts. |
def convert_html_to_text(
filename: str = None,
blob: bytes = None,
config: TextProcessingConfig = _DEFAULT_CONFIG) -> str:
"""
Converts HTML to text.
"""
with get_filelikeobject(filename, blob) as fp:
soup = bs4.BeautifulSoup(fp)
return soup.get_text() | Write a Python 3 script for
converting HTML to text. | As a python code expert, you are capable of creating scripts from specifications. |
def convert_xml_to_text(filename: str = None,
blob: bytes = None,
config: TextProcessingConfig = _DEFAULT_CONFIG) -> str:
"""
Converts XML to text.
"""
with get_filelikeobject(filename, blob) as fp:
soup = bs4.BeautifulStoneSoup(fp)
return ... | Can you implement a function in Python 3 that
converts XML to text. | You are a Python code generator, capable of creating scripts from specifications. |
def convert_rtf_to_text(filename: str = None,
blob: bytes = None,
config: TextProcessingConfig = _DEFAULT_CONFIG) -> str:
"""
Converts RTF to text.
"""
unrtf = tools['unrtf']
if unrtf: # Best
args = [unrtf, '--text', '--nopict']
if UNR... | Create a Python 3 function for
converting RTF to text. | As a Python code composer, you craft elegant and concise scripts. |
def availability_rtf() -> bool:
"""
Is an RTF processor available?
"""
unrtf = tools['unrtf']
if unrtf:
return True
elif pyth:
log.warning("RTF conversion: unrtf missing; "
"using pyth (less efficient)")
return True
else:
return False | How would you code a function in Python 3 to
check if an RTF processor is available. | As a Python code composer, you craft elegant and concise scripts. |
def convert_doc_to_text(filename: str = None,
blob: bytes = None,
config: TextProcessingConfig = _DEFAULT_CONFIG) -> str:
"""
Converts Microsoft Word DOC files to text.
"""
antiword = tools['antiword']
if antiword:
if filename:
retu... | How would you implement a function in Python 3 that
converts Microsoft Word DOC files to text. | You are a Python code analyst, evaluating scripts for potential improvements. |
Convert arbitrary files to text using strings2. | Can you tell what is the following Python 3 function doing
def convert_anything_to_text(
filename: str = None,
blob: bytes = None,
config: TextProcessingConfig = _DEFAULT_CONFIG) -> str:
"""
Convert arbitrary files to text, using ``strings`` or ``strings2``.
(``strings`` is a standar... | You are a Python code architect, reviewing and designing scalable and efficient code |
Converts a document to text. | How would you explain what the following Python 3 function does
def document_to_text(filename: str = None,
blob: bytes = None,
extension: str = None,
config: TextProcessingConfig = _DEFAULT_CONFIG) -> str:
"""
Converts a document to text.
This ... | As a Python code analyst, you investigate and solve complex coding mysteries |
Returns True if a text extractor is available for the specified extension. | Given the following Python 3 function, write the documentation
def is_text_extractor_available(extension: str) -> bool:
if extension is not None:
extension = extension.lower()
info = ext_map.get(extension)
if info is None:
return False
availability = info[AVAILABILITY]
if type(availa... | As a Python code composer, you craft elegant and concise scripts. |
def main() -> None:
"""
Command-line processor. See ``--help`` for details.
"""
logging.basicConfig(level=logging.DEBUG)
parser = argparse.ArgumentParser()
parser.add_argument("inputfile", nargs="?", help="Input file name")
parser.add_argument(
"--availability", nargs='*',
he... | Write a Python 3 script to
command - line processor. | As a python code expert, you are capable of creating scripts from specifications. |
Chooses basic or verbose logging. | How would you explain what the following Python 3 function does
def set_verbose_logging(verbose: bool) -> None:
if verbose:
set_loglevel(logging.DEBUG)
else:
set_loglevel(logging.INFO) | You are a Python code generator, capable of creating scripts from specifications. |
Writes SQL and arguments to the log. | Make a summary of the following Python 3 code
def debug_sql(sql: str, *args: Any) -> None:
log.debug("SQL: %s" % sql)
if args:
log.debug("Args: %r" % args) | As a Python code composer, you craft elegant and concise scripts. |
Delimits x using delims [ 0 1 ) and [ right ] | Make a summary of the following Python 3 code
def delimit(x: str, delims: Tuple[str, str]) -> str:
return delims[0] + x + delims[1] | As a Python code translator, you convert algorithms and pseudocode into Python. |
Returns SQL SELECT all fields in the fieldlist where keyname = keyname. | Here you have a function in Python 3, explain what it does
def get_sql_select_all_fields_by_key(
table: str,
fieldlist: Sequence[str],
keyname: str,
delims: Tuple[str, str] = ("", "")) -> str:
"""Returns SQL:
SELECT [all fields in the fieldlist] WHERE [keyname] = ?
"""
... | As a python code expert, you are capable of creating scripts from specifications. |
def get_sql_insert(table: str,
fieldlist: Sequence[str],
delims: Tuple[str, str] = ("", "")) -> str:
"""Returns ?-marked SQL for an INSERT statement."""
return (
"INSERT INTO " + delimit(table, delims) +
" (" +
",".join([delimit(x, delims) for x in f... | How would you code a function in Python 3 to
return an INSERT statement. | You are a Python code architect, reviewing and designing scalable and efficient code |
def get_sql_insert_or_update(table: str,
fieldlist: Sequence[str],
delims: Tuple[str, str] = ("", "")) -> str:
"""Returns ?-marked SQL for an INSERT-or-if-duplicate-key-UPDATE statement.
"""
# http://stackoverflow.com/questions/4205181
return """... | Write a Python 3 function that can
return an INSERT - or - UPDATE statement. | As a Python code analyst, you investigate and solve complex coding mysteries |
Returns an INSERT statement ignoring the first field in the fieldlist. | Explain what the following Python 3 code does
def get_sql_insert_without_first_field(
table: str,
fieldlist: Sequence[str],
delims: Tuple[str, str] = ("", "")) -> str:
"""Returns ?-marked SQL for an INSERT statement, ignoring the first field
(typically, the PK)."""
return get_sql_ins... | As a Python code composer, you craft elegant and concise scripts. |
def get_sql_update_by_first_field(table: str,
fieldlist: Sequence[str],
delims: Tuple[str, str] = ("", "")) -> str:
"""Returns SQL for an UPDATE statement, to update all fields except the
first field (PK) using the PK as the key."""
return ... | Can you implement a function in Python 3 that
returns an UPDATE statement to update all fields except the first field. | As a python code expert, you are capable of creating scripts from specifications. |
def datetime2literal_rnc(d: datetime.datetime, c: Optional[Dict]) -> str:
"""Format a DateTime object as something MySQL will actually accept."""
# dt = d.strftime("%Y-%m-%d %H:%M:%S")
# ... can fail with e.g.
# ValueError: year=1850 is before 1900; the datetime strftime() methods
# require year... | Implement a function in Python 3 to
format a DateTime object as something MySQL will actually accept. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def full_datatype_to_mysql(d: str) -> str:
"""Converts a full datatype, e.g. INT, VARCHAR(10), VARCHAR(MAX), to a
MySQL equivalent."""
d = d.upper()
(s, length) = split_long_sqltype(d)
if d in ["VARCHAR(MAX)", "NVARCHAR(MAX)"]:
# http://wiki.ispirer.com/sqlways/mysql/data-types/longtext
... | Implement a function in Python 3 to
convert a full datatype e. g. INT VARCHAR NVARCHAR NVARBINARY or NVARCHAR to a MySQL equivalent. | As a Python code composer, you craft elegant and concise scripts. |
Prints key - value pairs for an object s dictionary. | Here you have a function in Python 3, explain what it does
def debug_object(obj: T) -> str:
pairs = []
for k, v in vars(obj).items():
pairs.append(u"{}={}".format(k, v))
return u", ".join(pairs) | As a Python code composer, you craft elegant and concise scripts. |
Prints key - value pairs for an object s dictionary. | Given the following Python 3 function, write the documentation
def dump_database_object(obj: T, fieldlist: Iterable[str]) -> None:
log.info(_LINE_EQUALS)
log.info("DUMP OF: {}", obj)
for f in fieldlist:
log.info(u"{f}: {v}", f=f, v=getattr(obj, f))
log.info(_LINE_EQUALS) | You are a Python code generator, capable of creating scripts from specifications. |
Within obj assigns the values from the value list to the fields in
the fieldlist. | Given the following Python 3 function, write the documentation
def assign_from_list(obj: T,
fieldlist: Sequence[str],
valuelist: Sequence[any]) -> None:
"""Within "obj", assigns the values from the value list to the fields in
the fieldlist."""
if len(fieldlist) != l... | As a Python code composer, you craft elegant and concise scripts. |
Create an object from a list of values. | Can you generate the documentation for the following Python 3 function
def create_object_from_list(cls: Type,
fieldlist: Sequence[str],
valuelist: Sequence[Any],
*args, **kwargs) -> T:
"""
Create an object by instantiating ``cls... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Within obj sets all fields in the fieldlist to None. | Can you generate a brief explanation for the following Python 3 code
def blank_object(obj: T, fieldlist: Sequence[str]) -> None:
for f in fieldlist:
setattr(obj, f, None) | As a python code expert, you are capable of creating scripts from specifications. |
Writes a query result to the log. | Here you have a function in Python 3, explain what it does
def debug_query_result(rows: Sequence[Any]) -> None:
log.info("Retrieved {} rows", len(rows))
for i in range(len(rows)):
log.info("Row {}: {}", i, rows[i]) | As a Python code composer, you craft elegant and concise scripts. |
def create_database_mysql(database: str,
user: str,
password: str,
server: str = "localhost",
port: int = 3306,
charset: str = "utf8",
collate: str = "utf8_general_... | Write a Python 3 script to
connect via PyMySQL and creates a database. | You are a Python code analyst, evaluating scripts for potential improvements. |
def add_master_user_mysql(database: str,
root_user: str,
root_password: str,
new_user: str,
new_password: str,
server: str = "localhost",
port: int = 3306,
... | Can you implement a function in Python 3 that
connects via PyMySQL and creates a master user. | You are a Python code generator, capable of creating scripts from specifications. |
Returns details on a specific table. | Given the following Python 3 function, write the documentation
def describe_table(cls,
db: DATABASE_SUPPORTER_FWD_REF,
table: str) -> List[List[Any]]:
"""Returns details on a specific table."""
raise RuntimeError(_MSG_NO_FLAVOUR) | You are a Python code architect, reviewing and designing scalable and efficient code |
Returns all column names for a table. | How would you explain what the following Python 3 function does
def fetch_column_names(cls,
db: DATABASE_SUPPORTER_FWD_REF,
table: str) -> List[str]:
"""Returns all column names for a table."""
raise RuntimeError(_MSG_NO_FLAVOUR) | You are a Python code architect, reviewing and designing scalable and efficient code |
Returns the SQL datatype for a column. | Can you generate the documentation for the following Python 3 function
def get_datatype(cls,
db: DATABASE_SUPPORTER_FWD_REF,
table: str,
column: str) -> str:
"""Returns database SQL datatype for a column: e.g. VARCHAR."""
raise RuntimeError(... | You are a Python code generator, capable of creating scripts from specifications. |
def is_read_only(cls,
db: DATABASE_SUPPORTER_FWD_REF,
logger: logging.Logger = None) -> bool:
"""Do we have read-only access?"""
def convert_enums(row_):
# All these columns are of type enum('N', 'Y');
# https://dev.mysql.com/doc/refman/... | Create a Python 3 function for
checking if the database has read - only access. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Connect to the database and return a boolean indicating if the connection was successful. | Make a summary of the following Python 3 code
def connect(self,
engine: str = None,
interface: str = None,
host: str = None,
port: int = None,
database: str = None,
driver: str = None,
dsn: str = None,
... | You are a Python code architect, reviewing and designing scalable and efficient code |
def ping(self) -> None:
"""Pings a database connection, reconnecting if necessary."""
if self.db is None or self.db_pythonlib not in [PYTHONLIB_MYSQLDB,
PYTHONLIB_PYMYSQL]:
return
try:
self.db.ping(True) # test conn... | Write a Python 3 script to
ping a MySQL database connection reconnecting if necessary. | You are a Python code analyst, evaluating scripts for potential improvements. |
def connect_to_database_odbc_mysql(self,
database: str,
user: str,
password: str,
server: str = "localhost",
port: int = 3306... | Implement a function in Python 3 to
connect to a MySQL database via ODBC. | As a Python code analyst, you investigate and solve complex coding mysteries |
Connects to an SQL Server database via ODBC. | Make a summary of the following Python 3 code
def connect_to_database_odbc_sqlserver(self,
odbc_connection_string: str = None,
dsn: str = None,
database: str = None,
... | As a Python code analyst, you investigate and solve complex coding mysteries |
Connects to an Access database via ODBC with the DSN
prespecified. | Can you generate the documentation for the following Python 3 function
def connect_to_database_odbc_access(self,
dsn: str,
autocommit: bool = True) -> None:
"""Connects to an Access database via ODBC, with the DSN
prespecifi... | You are a Python code architect, reviewing and designing scalable and efficient code |
def localize_sql(self, sql: str) -> str:
"""Translates ?-placeholder SQL to appropriate dialect.
For example, MySQLdb uses %s rather than ?.
"""
# pyodbc seems happy with ? now (pyodbc.paramstyle is 'qmark');
# using ? is much simpler, because we may want to use % with LIKE
... | Can you write a function in Python 3 where it
translates ?-placeholder SQL to appropriate dialect. For example, MySQLdb uses %s rather than ?. | As a Python code composer, you craft elegant and concise scripts. |
Inserts a record into the database table using the list of fieldnames and the list of values. Returns the new PK or None. | Can you tell what is the following Python 3 function doing
def insert_record(self,
table: str,
fields: Sequence[str],
values: Sequence[Any],
update_on_duplicate_key: bool = False) -> int:
"""Inserts a record into database, t... | You are a Python code analyst, evaluating scripts for potential improvements. |
Inserts a record into the database using a list of fieldspecs having
their value stored under the value key. | Can you generate the documentation for the following Python 3 function
def insert_record_by_fieldspecs_with_values(
self,
table: str,
fieldspeclist: FIELDSPECLIST_TYPE) -> int:
"""Inserts a record into the database using a list of fieldspecs having
their value stored ... | You are a Python code analyst, evaluating scripts for potential improvements. |
Inserts a record into the database table using a dictionary containing field and value mappings. Returns the new PK or None. | Here you have a function in Python 3, explain what it does
def insert_record_by_dict(self,
table: str,
valuedict: Dict[str, Any]) -> Optional[int]:
"""Inserts a record into database, table "table", using a dictionary
containing field/value mapp... | You are a Python code analyst, evaluating scripts for potential improvements. |
def insert_multiple_records(self,
table: str,
fields: Sequence[str],
records: Sequence[Sequence[Any]]) -> int:
"""Inserts a record into database, table "table", using the list of
fieldnames and the list of re... | How would you code a function in Python 3 to
insert a record into the database table using the list of AttributeNames fieldnames and the list of records. Returns the number of rows affected. | You are a Python code generator, capable of creating scripts from specifications. |
def db_exec_with_cursor(self, cursor, sql: str, *args) -> int:
"""Executes SQL on a supplied cursor, with "?" placeholders,
substituting in the arguments. Returns number of rows affected."""
sql = self.localize_sql(sql)
try:
debug_sql(sql, args)
cursor.execute(sql... | How would you implement a function in Python 3 that
executes SQL on a supplied cursor. Returns number of rows affected. | As a Python code composer, you craft elegant and concise scripts. |
Executes SQL with? placeholders for arguments for arguments. | How would you explain what the following Python 3 function does
def db_exec(self, sql: str, *args) -> int:
self.ensure_db_open()
cursor = self.db.cursor()
return self.db_exec_with_cursor(cursor, sql, *args) | As a Python code translator, you convert algorithms and pseudocode into Python. |
Execute SQL and commit. | Can you tell what is the following Python 3 function doing
def db_exec_and_commit(self, sql: str, *args) -> int:
rowcount = self.db_exec(sql, *args)
self.commit()
return rowcount | As a python code expert, you are capable of creating scripts from specifications. |
def db_exec_literal(self, sql: str) -> int:
"""Executes SQL without modification. Returns rowcount."""
self.ensure_db_open()
cursor = self.db.cursor()
debug_sql(sql)
try:
cursor.execute(sql)
return cursor.rowcount
except: # nopep8
log.... | Can you create a Python 3 function that
executes SQL without modification. Returns rowcount. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Executes SQL ; returns the first value of the first row or None. | Given the following Python 3 function, write the documentation
def fetchvalue(self, sql: str, *args) -> Optional[Any]:
row = self.fetchone(sql, *args)
if row is None:
return None
return row[0] | As a Python code translator, you convert algorithms and pseudocode into Python. |
def fetchone(self, sql: str, *args) -> Optional[Sequence[Any]]:
"""Executes SQL; returns the first row, or None."""
self.ensure_db_open()
cursor = self.db.cursor()
self.db_exec_with_cursor(cursor, sql, *args)
try:
return cursor.fetchone()
except: # nopep8
... | Can you create a Python 3 function that
executes SQL ; returns the first row or None. | You are a Python code analyst, evaluating scripts for potential improvements. |
Executes SQL ; returns all rows or []. | Can you generate a brief explanation for the following Python 3 code
def fetchall(self, sql: str, *args) -> Sequence[Sequence[Any]]:
self.ensure_db_open()
cursor = self.db.cursor()
self.db_exec_with_cursor(cursor, sql, *args)
try:
rows = cursor.fetchall()
return r... | You are a Python code generator, capable of creating scripts from specifications. |
fetchall - Executes a SQL query and returns an iterator of the result set rows. | Make a summary of the following Python 3 code
def gen_fetchall(self, sql: str, *args) -> Iterator[Sequence[Any]]:
self.ensure_db_open()
cursor = self.db.cursor()
self.db_exec_with_cursor(cursor, sql, *args)
try:
row = cursor.fetchone()
while row is not None:
... | You are a Python code architect, reviewing and designing scalable and efficient code |
def fetchall_with_fieldnames(self, sql: str, *args) \
-> Tuple[Sequence[Sequence[Any]], Sequence[str]]:
"""Executes SQL; returns (rows, fieldnames)."""
self.ensure_db_open()
cursor = self.db.cursor()
self.db_exec_with_cursor(cursor, sql, *args)
try:
rows =... | How would you implement a function in Python 3 that
executes SQL ; returns rows and fieldnames. | As a Python code composer, you craft elegant and concise scripts. |
def fetchall_as_dictlist(self, sql: str, *args) -> List[Dict[str, Any]]:
"""Executes SQL; returns list of dictionaries, where each dict contains
fieldname/value pairs."""
self.ensure_db_open()
cursor = self.db.cursor()
self.db_exec_with_cursor(cursor, sql, *args)
try:
... | Implement a function in Python 3 to
execute SQL ; returns list of dictionaries where each dict contains fieldname / value pairs. | You are a Python code analyst, evaluating scripts for potential improvements. |
def fetchallfirstvalues(self, sql: str, *args) -> List[Any]:
"""Executes SQL; returns list of first values of each row."""
rows = self.fetchall(sql, *args)
return [row[0] for row in rows] | Write a Python 3 function that can
execute SQL ; returns list of first values of each row. | As a python code expert, you are capable of creating scripts from specifications. |
Executes SQL ; returns just the output fieldnames. | Can you generate the documentation for the following Python 3 function
def fetch_fieldnames(self, sql: str, *args) -> List[str]:
self.ensure_db_open()
cursor = self.db.cursor()
self.db_exec_with_cursor(cursor, sql, *args)
try:
return [i[0] for i in cursor.description]
... | You are a Python code analyst, evaluating scripts for potential improvements. |
def count_where(self, table: str, wheredict: Dict[str, Any] = None) -> int:
"""Counts rows in a table, given a set of WHERE criteria (ANDed),
returning a count."""
sql = "SELECT COUNT(*) FROM " + self.delimit(table)
if wheredict is not None:
sql += " WHERE " + " AND ".join([
... | Write a Python 3 function that can
count rows in a table given a set of WHERE criteria and returns a count. | You are a Python code architect, reviewing and designing scalable and efficient code |
def does_row_exist(self, table: str, field: str, value: Any) -> bool:
"""Checks for the existence of a record by a single field (typically a
PK)."""
sql = ("SELECT COUNT(*) FROM " + self.delimit(table) +
" WHERE " + self.delimit(field) + "=?")
row = self.fetchone(sql, valu... | Create a Python 3 function for
checking for the existence of a record by a single field. | You are a Python code generator, capable of creating scripts from specifications. |
def delete_by_field(self, table: str, field: str, value: Any) -> int:
"""Deletes all records where "field" is "value"."""
sql = ("DELETE FROM " + self.delimit(table) +
" WHERE " + self.delimit(field) + "=?")
return self.db_exec(sql, value) | Implement a Python 3 function for
deleting all records where field is value. | You are a Python code architect, reviewing and designing scalable and efficient code |
Fetches object from database table by a field specified by keyname and keyvalue. Writes back to object. Returns True if success or False if failure. | How would you explain what the following Python 3 function does
def fetch_object_from_db_by_other_field(self,
obj: Any,
table: str,
fieldlist: Sequence[str],
... | As a Python code composer, you craft elegant and concise scripts. |
def fetch_all_objects_from_db(self,
cls: Type[T],
table: str,
fieldlist: Sequence[str],
construct_with_pk: bool,
*args) -> List[T]:
"""Fetches... | Can you write a function in Python 3 where it
fetches all objects from a table returning an array of objects of class cls. | As a Python code analyst, you investigate and solve complex coding mysteries |
Fetches all objects from a table given a list of PKs. | How would you explain what the following Python 3 function does
def fetch_all_objects_from_db_by_pklist(self,
cls: Type,
table: str,
fieldlist: Sequence[str],
... | As a python code expert, you are capable of creating scripts from specifications. |
def fetch_all_objects_from_db_where(self,
cls: Type[T],
table: str,
fieldlist: Sequence[str],
construct_with_pk: bool,
w... | Can you create a Python 3 function that
fetches all objects from a table given a set of WHERE criteria returning an array of objects of class cls. | You are a Python code architect, reviewing and designing scalable and efficient code |
Inserts object into database table with PK already in fieldlist. | Explain what the following Python 3 code does
def insert_object_into_db_pk_known(self,
obj: Any,
table: str,
fieldlist: Sequence[str]) -> None:
"""Inserts object into database table, with PK (fir... | As a Python code composer, you craft elegant and concise scripts. |
Inserts object into database table with PK initially
unknown and subsequently set in the object from the database. | Make a summary of the following Python 3 code
def insert_object_into_db_pk_unknown(self,
obj: Any,
table: str,
fieldlist: Sequence[str]) -> None:
"""Inserts object into database table, with... | You are a Python code analyst, evaluating scripts for potential improvements. |
Updates an object in the database. | Explain what the following Python 3 code does
def update_object_in_db(self,
obj: Any,
table: str,
fieldlist: Sequence[str]) -> None:
"""Updates an object in the database (saves it to the database, where
it exists there a... | You are a Python code architect, reviewing and designing scalable and efficient code |
def save_object_to_db(self,
obj: Any,
table: str,
fieldlist: Sequence[str],
is_new_record: bool) -> None:
"""Saves a object to the database, inserting or updating as
necessary."""
if is_new_re... | Implement a Python 3 function for
saving an object to the database inserting or updating as necessary. | You are a Python code analyst, evaluating scripts for potential improvements. |
def index_exists(self, table: str, indexname: str) -> bool:
"""Does an index exist? (Specific to MySQL.)"""
# MySQL:
sql = ("SELECT COUNT(*) FROM information_schema.statistics"
" WHERE table_name=? AND index_name=?")
row = self.fetchone(sql, table, indexname)
retur... | Write a Python 3 function for
doing an index exist? ( Specific to MySQL. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Creates an index for the specified key in the specified table. | Make a summary of the following Python 3 code
def create_index(self,
table: str,
field: str,
nchars: int = None,
indexname: str = None,
unique: bool = False) -> Optional[int]:
"""Creates an index (default na... | You are a Python code analyst, evaluating scripts for potential improvements. |
Calls create_index based on a fieldspec. | Given the following Python 3 function, write the documentation
def create_index_from_fieldspec(self,
table: str,
fieldspec: FIELDSPEC_TYPE,
indexname: str = None) -> None:
"""Calls create_index based on a... | You are a Python code architect, reviewing and designing scalable and efficient code |
Creates a FULLTEXT index for the given table and field. | Make a summary of the following Python 3 code
def create_fulltext_index(self,
table: str,
field: str,
indexname: str = None) -> Optional[int]:
"""Creates a FULLTEXT index (default name _idxft_FIELDNAME), unless it
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def fielddefsql_from_fieldspec(fieldspec: FIELDSPEC_TYPE) -> str:
"""Returns SQL fragment to define a field."""
sql = fieldspec["name"] + " " + fieldspec["sqltype"]
if "notnull" in fieldspec and fieldspec["notnull"]:
sql += " NOT NULL"
if "autoincrement" in fieldspec and fiel... | How would you code a function in Python 3 to
return the SQL fragment to define a field. | As a Python code analyst, you investigate and solve complex coding mysteries |
def fielddefsql_from_fieldspeclist(
self, fieldspeclist: FIELDSPECLIST_TYPE) -> str:
"""Returns list of field-defining SQL fragments."""
return ",".join([
self.fielddefsql_from_fieldspec(x)
for x in fieldspeclist
]) | Write a Python 3 function that can
return list of field - defining SQL fragments. | You are a Python code architect, reviewing and designing scalable and efficient code |
def fieldspec_subset_by_name(
fieldspeclist: FIELDSPECLIST_TYPE,
fieldnames: Container[str]) -> FIELDSPECLIST_TYPE:
"""Returns a subset of the fieldspecs matching the fieldnames list."""
result = []
for x in fieldspeclist:
if x["name"] in fieldnames:
... | Can you implement a function in Python 3 that
returns a subset of the fieldspecs matching the fieldnames list. | As a python code expert, you are capable of creating scripts from specifications. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.