output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
Set intersection percentage of intersecting divisions.
Make a summary of the following Python 3 code def set_intersection(self, division, intersection): IntersectRelationship.objects.filter( from_division=self, to_division=division ).update(intersection=intersection)
You are a Python code architect, reviewing and designing scalable and efficient code
def get_intersection(self, division): """Get intersection percentage of intersecting divisions.""" try: return IntersectRelationship.objects.get( from_division=self, to_division=division ).intersection except ObjectDoesNotExist: raise Exception...
Create a Python 3 function for getting intersection percentage of intersecting divisions.
As a Python code analyst, you investigate and solve complex coding mysteries
def launch_slurm(jobname: str, cmd: str, memory_mb: int, project: str, qos: str, email: str, duration: timedelta, tasks_per_node: int, cpus_per_task: int, partition: s...
Can you create a Python 3 function that launches a job into the SLURM environment.
As a Python code analyst, you investigate and solve complex coding mysteries
Launch a Cambridge HPHI.
Make a summary of the following Python 3 code def launch_cambridge_hphi( jobname: str, cmd: str, memory_mb: int, qos: str, email: str, duration: timedelta, cpus_per_task: int, project: str = "hphi", tasks_per_node: int = 1, partition: str =...
As a python code expert, you are capable of creating scripts from specifications.
def get_drug(drug_name: str, name_is_generic: bool = False, include_categories: bool = False) -> Optional[Drug]: """ Converts a drug name to a :class:`.Drug` class. If you already have the generic name, you can get the Drug more efficiently by setting ``name_is_generic=True``....
Write a Python 3 script to convert a drug name to a : class :. Drug class.
You are a Python code generator, capable of creating scripts from specifications.
def drug_name_to_generic(drug_name: str, unknown_to_default: bool = False, default: str = None, include_categories: bool = False) -> str: """ Converts a drug name to the name of its generic equivalent. """ drug = get_drug(drug_na...
Write a Python 3 function for converting a drug name to its generic equivalent.
As a Python code analyst, you investigate and solve complex coding mysteries
def drug_names_to_generic(drugs: List[str], unknown_to_default: bool = False, default: str = None, include_categories: bool = False) -> List[str]: """ Converts a list of drug names to their generic equivalents. The arguments are ...
Write a Python 3 script to convert a list of drug names to their generic equivalents.
As a Python code analyst, you investigate and solve complex coding mysteries
def drug_matches_criteria(drug: Drug, **criteria: Dict[str, bool]) -> bool: """ Determines whether a drug, passed as an instance of :class:`.Drug`, matches the specified criteria. Args: drug: a :class:`.Drug` instance criteria: ``name=value`` pairs to match against the attributes of ...
How would you implement a function in Python 3 that determines whether a drug instance matches the specified criteria.
As a Python code composer, you craft elegant and concise scripts.
Returns a list of all the drugs that match the criteria.
Can you generate a brief explanation for the following Python 3 code def all_drugs_where(sort=True, include_categories: bool = False, **criteria: Dict[str, bool]) -> List[Drug]: """ Find all drugs matching the specified criteria (see :func:`drug_matches_criteria`). If...
You are a Python code architect, reviewing and designing scalable and efficient code
Determines whether a single drug passed by name matches the specified criteria.
Given the following Python 3 function, write the documentation def drug_name_matches_criteria(drug_name: str, name_is_generic: bool = False, include_categories: bool = False, **criteria: Dict[str, bool]) -> bool: """ Es...
You are a Python code generator, capable of creating scripts from specifications.
def drug_names_match_criteria(drug_names: List[str], names_are_generic: bool = False, include_categories: bool = False, **criteria: Dict[str, bool]) -> List[bool]: """ Establish whether multiple drugs, passed as a list of ...
Create a Python 3 function to establish whether multiple drugs passed as a list of drug names each racket matches the specified criteria.
As a Python code composer, you craft elegant and concise scripts.
def regex_text(self) -> str: """ Return regex text (yet to be compiled) for this drug. """ if self._regex_text is None: possibilities = [] # type: List[str] for p in list(set(self.all_generics + self.alternatives)): if self.add_preceding_word_boun...
How would you implement a function in Python 3 that returns the regex text for this drug.
As a Python code translator, you convert algorithms and pseudocode into Python.
Returns a compiled regex for this drug.
Can you generate a brief explanation for the following Python 3 code def regex(self) -> Pattern: if self._regex is None: self._regex = re.compile(self.regex_text, re.IGNORECASE | re.DOTALL) return self._regex
As a Python code translator, you convert algorithms and pseudocode into Python.
def regex_to_sql_like(regex_text: str, single_wildcard: str = "_", zero_or_more_wildcard: str = "%") -> List[str]: """ Converts regular expression text to a reasonably close fragment for the SQL ``LIKE`` operator. NOT PERFECT, but work...
Implement a Python 3 function for converting a regular expression text to a reasonably close fragment of SQL string.
As a Python code translator, you convert algorithms and pseudocode into Python.
def sql_like_fragments(self) -> List[str]: """ Returns all the string literals to which a database column should be compared using the SQL ``LIKE`` operator, to match this drug. This isn't as accurate as the regex, but ``LIKE`` can do less. ``LIKE`` uses the wildcards ``?`` and...
Can you create a Python 3 function that returns all the SQL - like fragments that are used to compare the database column names with the SQL - LIKE operator.
As a Python code analyst, you investigate and solve complex coding mysteries
Determines whether the given name matches our knowledge of any of the related objects.
Can you generate the documentation for the following Python 3 function def name_matches(self, name: str) -> bool: return bool(self.regex.match(name))
As a Python code translator, you convert algorithms and pseudocode into Python.
Returns the SQL like clause for the drug column_name.
Can you generate the documentation for the following Python 3 function def sql_column_like_drug(self, column_name: str) -> str: clauses = [ "{col} LIKE {fragment}".format( col=column_name, fragment=sql_string_literal(f)) for f in self.sql_like_fragments ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Returns the unit quaternion for a vector and an angle.
Given the following Python 3 function, write the documentation def quaternion(vector, angle): return N.cos(angle/2)+vector*N.sin(angle/2)
As a Python code composer, you craft elegant and concise scripts.
def ellipse(n=1000, adaptive=False): """ Get a parameterized set of vectors defining ellipse for a major and minor axis length. Resulting vector bundle has major axes along axes given. """ u = N.linspace(0,2*N.pi,n) # Get a bundle of vectors defining # a full rotation around the unit...
Can you implement a function in Python 3 that returns a parameterized set of vectors defining an ellipse.
You are a Python code generator, capable of creating scripts from specifications.
def scale_errors(cov_axes, confidence_level=0.95): """ Returns major axes of error ellipse or hyperbola, rescaled using chi2 test statistic """ dof = len(cov_axes) x2t = chi2.ppf(confidence_level,dof) return N.sqrt(x2t*cov_axes)
Implement a function in Python 3 to return major axes of error ellipse or rescaled using chi2 test statistic
As a Python code analyst, you investigate and solve complex coding mysteries
Returns a list of lon lat values for a set of normal axes.
Make a summary of the following Python 3 code def normal_errors(axes, covariance_matrix, **kwargs): level = kwargs.pop('level',1) traditional_layout = kwargs.pop('traditional_layout',True) d = N.diagonal(covariance_matrix) ell = ellipse(**kwargs) if axes[2,2] < 0: axes *= -1 # Not sure...
As a python code expert, you are capable of creating scripts from specifications.
Returns a list of lon lat values for each plane in the diagram.
Here you have a function in Python 3, explain what it does def plane_errors(axes, covariance_matrix, sheet='upper',**kwargs): level = kwargs.pop('level',1) traditional_layout = kwargs.pop('traditional_layout',True) d = N.sqrt(covariance_matrix) ell = ellipse(**kwargs) bundle = dot(ell, d[:2]) ...
As a python code expert, you are capable of creating scripts from specifications.
This function computes an iterative version of pca. plane_errors which computes an error surface for a plane.
Explain what the following Python 3 code does def iterative_plane_errors(axes,covariance_matrix, **kwargs): sheet = kwargs.pop('sheet','upper') level = kwargs.pop('level',1) n = kwargs.pop('n',100) cov = N.sqrt(N.diagonal(covariance_matrix)) u = N.linspace(0, 2*N.pi, n) scales = dict(upper=1,l...
As a Python code analyst, you investigate and solve complex coding mysteries
Transforms a SQL identifier into a version that is quoted if required.
Can you generate the documentation for the following Python 3 function def quote_identifier_if_required(cls, identifier: str, debug_force_quote: bool = False) -> str: """ Transforms a SQL identifier (such as a column name) into a version that is quoted if req...
You are a Python code generator, capable of creating scripts from specifications.
def to_topojson(self): """Adds points and converts to topojson string.""" topojson = self.topojson topojson["objects"]["points"] = { "type": "GeometryCollection", "geometries": [point.to_topojson() for point in self.points.all()], } return json.dumps(topoj...
Write a Python 3 function that can add points and converts to topojson string.
As a Python code translator, you convert algorithms and pseudocode into Python.
def post(self, element): """ :param element: Element to post to Netuitive :type element: object """ try: if self.disabled is True: element.clear_samples() logging.error('Posting has been disabled. ' ...
Create a Python 3 function for posting an element to Netuitive.
As a Python code translator, you convert algorithms and pseudocode into Python.
def post_event(self, event): """ :param event: Event to post to Netuitive :type event: object """ if self.disabled is True: logging.error('Posting has been disabled. ' 'See previous errors for details.') return(False) ...
Implement a function in Python 3 to post an event to Netuitive .
You are a Python code architect, reviewing and designing scalable and efficient code
def post_check(self, check): """ :param check: Check to post to Metricly :type check: object """ if self.disabled is True: logging.error('Posting has been disabled. ' 'See previous errors for details.') return(False) ...
Write a Python 3 function that can post a check to the Metricly API.
As a Python code translator, you convert algorithms and pseudocode into Python.
Split url into scheme host port path query fragment
Make a summary of the following Python 3 code def urlsplit(url): p = '((?P<scheme>.*)?.*://)?(?P<host>[^:/ ]+).?(?P<port>[0-9]*).*' m = re.search(p, url) scheme = m.group('scheme') host = m.group('host') port = m.group('port') _scheme, _netloc, path, query, _fragment = tuple(py_urlsplit(url)) ...
You are a Python code generator, capable of creating scripts from specifications.
def generate_url(scheme=None, host=None, port=None, path=None, query=None): """ Generate URI from parameters. :param str scheme: :param str host: :param int port: :param str path: :param dict query: :return: """ url = "" if scheme is not None: url += "%s://" % scheme...
How would you code a function in Python 3 to generate URI from parameters.
As a python code expert, you are capable of creating scripts from specifications.
def download(self, output_dir, url, overwrite): """ Dowload file to /tmp """ tmp = self.url2tmp(output_dir, url) if os.path.isfile(tmp) and not overwrite: logging.info("File {0} already exists. Skipping download.".format(tmp)) return tmp f = open(tmp, 'wb') ...
Write a Python 3 function that can download a file from the given url to the given directory.
You are a Python code analyst, evaluating scripts for potential improvements.
def extract(self, pbf, output): """ extract POI nodes from osm pbf extract """ logging.info("Extracting POI nodes from {0} to {1}".format(pbf, output)) with open(output, 'w') as f: # define callback for each node that is processed def nodes_callback(nodes): ...
Write a Python 3 script for extracting POI nodes from osm pbf extract
As a Python code translator, you convert algorithms and pseudocode into Python.
def url2tmp(self, root, url): """ convert url path to filename """ filename = url.rsplit('/', 1)[-1] return os.path.join(root, filename)
Implement a Python 3 function for converting url to tmp filename
As a python code expert, you are capable of creating scripts from specifications.
def ask_user(prompt: str, default: str = None) -> Optional[str]: """ Prompts the user, with a default. Returns user input from ``stdin``. """ if default is None: prompt += ": " else: prompt += " [" + default + "]: " result = input(prompt) return result if len(result) > 0 else...
How would you code a function in Python 3 to prompt the user with a default. Returns user input from stdin.
As a python code expert, you are capable of creating scripts from specifications.
Provides a GUI Save As dialogue and returns the filename.
How would you explain what the following Python 3 function does def get_save_as_filename(defaultfilename: str, defaultextension: str, title: str = "Save As") -> str: """ Provides a GUI "Save As" dialogue (via ``tkinter``) and returns the filename. """ ...
You are a Python code architect, reviewing and designing scalable and efficient code
def get_open_filename(defaultfilename: str, defaultextension: str, title: str = "Open") -> str: """ Provides a GUI "Open" dialogue (via ``tkinter``) and returns the filename. """ root = tkinter.Tk() # create and get Tk topmost window # (don't do this too ...
How would you code a function in Python 3 to provide a GUI Open dialogue and returns the filename.
You are a Python code analyst, evaluating scripts for potential improvements.
Convert a string to a boolean value.
Explain what the following Python 3 code does def str2bool(v: str) -> bool: lv = v.lower() if lv in ('yes', 'true', 't', 'y', '1'): return True elif lv in ('no', 'false', 'f', 'n', '0'): return False else: raise ArgumentTypeError('Boolean value expected.')
You are a Python code analyst, evaluating scripts for potential improvements.
def abort_request(self, request): """Called to abort request on timeout""" self.timedout = True try: request.cancel() except error.AlreadyCancelled: return
Write a Python 3 function that can call to abort the request on timeout
As a Python code translator, you convert algorithms and pseudocode into Python.
def getBody(cls, url, method='GET', headers={}, data=None, socket=None, timeout=120): """Make an HTTP request and return the body """ if not 'User-Agent' in headers: headers['User-Agent'] = ['Tensor HTTP checker'] return cls().request(url, method, headers, data, socket, time...
Create a Python 3 function to make an HTTP request and return the body
You are a Python code generator, capable of creating scripts from specifications.
Fetch a JSON result via HTTP HTTP
How would you explain what the following Python 3 function does def getJson(cls, url, method='GET', headers={}, data=None, socket=None, timeout=120): if not 'Content-Type' in headers: headers['Content-Type'] = ['application/json'] body = yield cls().getBody(url, method, headers, data, socke...
As a Python code composer, you craft elegant and concise scripts.
def aligned_covariance(fit, type='noise'): """ Covariance rescaled so that eigenvectors sum to 1 and rotated into data coordinates from PCA space """ cov = fit._covariance_matrix(type) # Rescale eigenvectors to sum to 1 cov /= N.linalg.norm(cov) return dot(fit.axes,cov)
How would you code a function in Python 3 to return the covariance matrix aligned to the fit.
You are a Python code generator, capable of creating scripts from specifications.
def fit_angle(fit1, fit2, degrees=True): """ Finds the angle between the nominal vectors """ return N.degrees(angle(fit1.normal,fit2.normal))
Write a Python 3 function for finding the angle between the nominal vectors fit1 and fit2.
As a Python code composer, you craft elegant and concise scripts.
def fit_similarity(fit1, fit2): """ Distance apart for vectors, given in standard deviations """ cov1 = aligned_covariance(fit1) cov2 = aligned_covariance(fit2) if fit2.axes[2,2] < 0: cov2 *= -1 v0 = fit1.normal-fit2.normal cov0 = cov1+cov2 # Axes are aligned, so no covarianc...
Write a Python 3 function that can calculate the similarity between two fit objects.
As a python code expert, you are capable of creating scripts from specifications.
Generates three transformation matrices to map three - dimensional data on the xy xz and yz planes respectively.
Can you generate a brief explanation for the following Python 3 code def axis_aligned_transforms(): I = N.eye(3) xy = I[:2] xz = N.vstack((I[0],I[2])) yz = I[1:] return xy,xz,yz
You are a Python code generator, capable of creating scripts from specifications.
Converts a pyplot figure to an HTML IMG tag with encapsulated PNG.
Make a summary of the following Python 3 code def png_img_html_from_pyplot_figure(fig: "Figure", dpi: int = 100, extra_html_class: str = None) -> str: """ Converts a ``pyplot`` figure to an HTML IMG tag with encapsulated PNG. """ if...
You are a Python code analyst, evaluating scripts for potential improvements.
def svg_html_from_pyplot_figure(fig: "Figure") -> str: """ Converts a ``pyplot`` figure to an SVG tag. """ if fig is None: return "" memfile = io.BytesIO() # StringIO doesn't like mixing str/unicode fig.savefig(memfile, format="svg") return memfile.getvalue().decode("utf-8")
Can you implement a function in Python 3 that converts a pyplot figure to an SVG tag.
You are a Python code architect, reviewing and designing scalable and efficient code
def set_matplotlib_fontsize(matplotlib: ModuleType, fontsize: Union[int, float] = 12) -> None: """ Sets the current font size within the ``matplotlib`` library. **WARNING:** not an appropriate method for multithreaded environments, as it writes (indirectly) to ``matplotlib``...
Create a Python 3 function to set the current font size within the matplotlib library.
As a Python code analyst, you investigate and solve complex coding mysteries
Takes a list of GPG keys and returns a list of GPG keys.
Explain what the following Python 3 code does def massage_keys(keys): m_keys = [] for key in keys: if key.startswith('keybase:'): m_keys.append(cryptorito.key_from_keybase(key[8:])['fingerprint']) else: m_keys.append(key) return m_keys
As a Python code composer, you craft elegant and concise scripts.
Encrypt a file with the specific GPG keys and write out to the specified path
Can you tell what is the following Python 3 function doing def encrypt_file(src, dest, csv_keys): keys = massage_keys(csv_keys.split(',')) cryptorito.encrypt(src, dest, keys)
You are a Python code architect, reviewing and designing scalable and efficient code
def encrypt_var(csv_keys): """Encrypt what comes in from stdin and return base64 encrypted against the specified keys, returning on stdout""" keys = massage_keys(csv_keys.split(',')) data = sys.stdin.read() encrypted = cryptorito.encrypt_var(data, keys) print(cryptorito.portable_b64encode(encryp...
Write a Python 3 script for encrypting what comes in from stdin and return base64 encrypted against the specified keys returning on stdout
As a Python code translator, you convert algorithms and pseudocode into Python.
def import_keybase(useropt): """Imports a public GPG key from Keybase""" public_key = None u_bits = useropt.split(':') username = u_bits[0] if len(u_bits) == 1: public_key = cryptorito.key_from_keybase(username) else: fingerprint = u_bits[1] public_key = cryptorito.key_fr...
Write a Python 3 script for importing a public GPG key from Keybase
You are a Python code analyst, evaluating scripts for potential improvements.
Execute command line cryptorito actions
Can you generate a brief explanation for the following Python 3 code def do_thing(): if len(sys.argv) == 5 and sys.argv[1] == "encrypt_file": encrypt_file(sys.argv[2], sys.argv[3], sys.argv[4]) elif len(sys.argv) == 4 and sys.argv[1] == "decrypt_file": decrypt_file(sys.argv[2], sys.argv[3]) ...
As a Python code analyst, you investigate and solve complex coding mysteries
Returns a Monochrome log handler using a standard format.
Can you generate a brief explanation for the following Python 3 code def get_monochrome_handler( extranames: List[str] = None, with_process_id: bool = False, with_thread_id: bool = False, stream: TextIO = None) -> logging.StreamHandler: """ Gets a monochrome log handler using a s...
As a Python code analyst, you investigate and solve complex coding mysteries
def get_colour_handler(extranames: List[str] = None, with_process_id: bool = False, with_thread_id: bool = False, stream: TextIO = None) -> logging.StreamHandler: """ Gets a colour log handler using a standard format. Args: extran...
How would you code a function in Python 3 to return a colour log handler using a standard format.
As a Python code analyst, you investigate and solve complex coding mysteries
def configure_logger_for_colour(logger: logging.Logger, level: int = logging.INFO, remove_existing: bool = False, extranames: List[str] = None, with_process_id: bool = False, ...
Implement a function in Python 3 to configure a logger for a colour.
You are a Python code generator, capable of creating scripts from specifications.
Quick function to set up the root logger for colour.
Can you generate the documentation for the following Python 3 function def main_only_quicksetup_rootlogger(level: int = logging.DEBUG, with_process_id: bool = False, with_thread_id: bool = False) -> None: """ Quick function to set up the ro...
As a Python code translator, you convert algorithms and pseudocode into Python.
Removes all handlers from a logger.
Make a summary of the following Python 3 code def remove_all_logger_handlers(logger: logging.Logger) -> None: while logger.handlers: h = logger.handlers[0] logger.removeHandler(h)
As a Python code translator, you convert algorithms and pseudocode into Python.
def reset_logformat(logger: logging.Logger, fmt: str, datefmt: str = '%Y-%m-%d %H:%M:%S') -> None: """ Create a new formatter and apply it to the logger. :func:`logging.basicConfig` won't reset the formatter if another module has called it, so always set the form...
Write a Python 3 function for resetting the log format of the given logger.
You are a Python code architect, reviewing and designing scalable and efficient code
Reset a logger s logformat to a simple time - stamped log format.
Make a summary of the following Python 3 code def reset_logformat_timestamped(logger: logging.Logger, extraname: str = "", level: int = logging.INFO) -> None: """ Apply a simple time-stamped log format to an existing logger, and set its logleve...
As a Python code composer, you craft elegant and concise scripts.
def configure_all_loggers_for_colour(remove_existing: bool = True) -> None: """ Applies a preconfigured datetime/colour scheme to ALL logger. Should ONLY be called from the ``if __name__ == 'main'`` script; see https://docs.python.org/3.4/howto/logging.html#library-config. Generally MORE SENSIBLE ...
Write a Python 3 script to apply a preconfigured datetime / colour scheme to ALL loggers.
You are a Python code analyst, evaluating scripts for potential improvements.
def apply_handler_to_root_log(handler: logging.Handler, remove_existing: bool = False) -> None: """ Applies a handler to all logs, optionally removing existing handlers. Should ONLY be called from the ``if __name__ == 'main'`` script; see https://docs.python.org/3.4/howto/...
How would you implement a function in Python 3 that applies a handler to all logs in the root logger.
You are a Python code architect, reviewing and designing scalable and efficient code
def apply_handler_to_all_logs(handler: logging.Handler, remove_existing: bool = False) -> None: """ Applies a handler to all logs, optionally removing existing handlers. Should ONLY be called from the ``if __name__ == 'main'`` script; see https://docs.python.org/3.4/howto/...
Create a Python 3 function for applying a handler to all logs.
As a python code expert, you are capable of creating scripts from specifications.
def copy_root_log_to_file(filename: str, fmt: str = LOG_FORMAT, datefmt: str = LOG_DATEFMT) -> None: """ Copy all currently configured logs to the specified file. Should ONLY be called from the ``if __name__ == 'main'`` script; see https://docs.python...
Create a Python 3 function for copying all currently configured logs to a file.
As a Python code composer, you craft elegant and concise scripts.
def copy_all_logs_to_file(filename: str, fmt: str = LOG_FORMAT, datefmt: str = LOG_DATEFMT) -> None: """ Copy all currently configured logs to the specified file. Should ONLY be called from the ``if __name__ == 'main'`` script; see https://docs.python...
How would you code a function in Python 3 to copy all currently configured logs to a file.
As a python code expert, you are capable of creating scripts from specifications.
def get_formatter_report(f: logging.Formatter) -> Optional[Dict[str, str]]: """ Returns information on a log formatter, as a dictionary. For debugging. """ if f is None: return None return { '_fmt': f._fmt, 'datefmt': f.datefmt, '_style': str(f._style), }
Implement a Python 3 function for returning information on a log formatter as a dictionary.
As a Python code analyst, you investigate and solve complex coding mysteries
def get_handler_report(h: logging.Handler) -> Dict[str, Any]: """ Returns information on a log handler, as a dictionary. For debugging. """ return { 'get_name()': h.get_name(), 'level': h.level, 'formatter': get_formatter_report(h.formatter), 'filters': h.filters, ...
Create a Python 3 function for returning information on a log handler as a dictionary.
As a Python code composer, you craft elegant and concise scripts.
def get_log_report(log: Union[logging.Logger, logging.PlaceHolder]) -> Dict[str, Any]: """ Returns information on a log, as a dictionary. For debugging. """ if isinstance(log, logging.Logger): # suppress invalid error for Logger.manager: # noinspection PyUnr...
Write a Python 3 script to return information on a log as a dictionary. For debugging.
As a Python code analyst, you investigate and solve complex coding mysteries
Use this function to print a report on all logs.
Here you have a function in Python 3, explain what it does def print_report_on_all_logs() -> None: d = {} # noinspection PyUnresolvedReferences for name, obj in logging.Logger.manager.loggerDict.items(): d[name] = get_log_report(obj) rootlogger = logging.getLogger() d['(root logger)'] = get_...
You are a Python code analyst, evaluating scripts for potential improvements.
def set_level_for_logger_and_its_handlers(log: logging.Logger, level: int) -> None: """ Set a log level for a log and all its handlers. Args: log: log to modify level: log level to set """ log.setLevel(level) for h in log.handlers: # ty...
Write a Python 3 function for setting a log level for a log and all its handlers.
As a Python code analyst, you investigate and solve complex coding mysteries
Returns a log with the specified name that has a null handler attached.
Explain what the following Python 3 code does def get_brace_style_log_with_null_handler(name: str) -> BraceStyleAdapter: log = logging.getLogger(name) log.addHandler(logging.NullHandler()) return BraceStyleAdapter(log)
You are a Python code architect, reviewing and designing scalable and efficient code
Format the log record as HTML.
Can you tell what is the following Python 3 function doing def format(self, record: logging.LogRecord) -> str: # message = super().format(record) super().format(record) # Since fmt does not contain asctime, the Formatter.format() # will not write asctime (since its usesTime()) function ...
You are a Python code architect, reviewing and designing scalable and efficient code
Internal function to process a logging. LogRecord.
Explain what the following Python 3 code does def emit(self, record: logging.LogRecord) -> None: # noinspection PyBroadException try: html = self.format(record) self.logfunction(html) except: # nopep8 self.handleError(record)
As a python code expert, you are capable of creating scripts from specifications.
def get_table_names(engine: Engine) -> List[str]: """ Returns a list of database table names from the :class:`Engine`. """ insp = Inspector.from_engine(engine) return insp.get_table_names()
Can you implement a function in Python 3 that returns a list of database table names from the given engine.
You are a Python code architect, reviewing and designing scalable and efficient code
def get_view_names(engine: Engine) -> List[str]: """ Returns a list of database view names from the :class:`Engine`. """ insp = Inspector.from_engine(engine) return insp.get_view_names()
Can you create a Python 3 function that returns a list of database view names from the Engine.
As a python code expert, you are capable of creating scripts from specifications.
def table_or_view_exists(engine: Engine, table_or_view_name: str) -> bool: """ Does the named table/view exist (either as a table or as a view) in the database? """ tables_and_views = get_table_names(engine) + get_view_names(engine) return table_or_view_name in tables_and_views
Can you write a function in Python 3 where it returns whether the named table or view exists in the database?
You are a Python code analyst, evaluating scripts for potential improvements.
Generate column info for the specified table.
Can you tell what is the following Python 3 function doing def gen_columns_info(engine: Engine, tablename: str) -> Generator[SqlaColumnInspectionInfo, None, None]: """ For the specified table, generate column information as :class:`SqlaC...
You are a Python code analyst, evaluating scripts for potential improvements.
Get the SQLAlchemy column information for the specified column in the specified table.
Can you tell what is the following Python 3 function doing def get_column_info(engine: Engine, tablename: str, columnname: str) -> Optional[SqlaColumnInspectionInfo]: """ For the specified column in the specified table, get column information as a :class:`SqlaColumnInspectionInfo` object...
As a python code expert, you are capable of creating scripts from specifications.
def get_column_type(engine: Engine, tablename: str, columnname: str) -> Optional[TypeEngine]: """ For the specified column in the specified table, get its type as an instance of an SQLAlchemy column type class (or ``None`` if such a column can't be found). For more on :class:`Ty...
Implement a function in Python 3 to get the SQLAlchemy column type class for the specified column in the specified table.
As a python code expert, you are capable of creating scripts from specifications.
Get all the database column names for the specified table.
Here you have a function in Python 3, explain what it does def get_column_names(engine: Engine, tablename: str) -> List[str]: return [info.name for info in gen_columns_info(engine, tablename)]
As a Python code translator, you convert algorithms and pseudocode into Python.
Returns a list of database column names for a table.
How would you explain what the following Python 3 function does def get_pk_colnames(table_: Table) -> List[str]: pk_names = [] # type: List[str] for col in table_.columns: if col.primary_key: pk_names.append(col.name) return pk_names
You are a Python code analyst, evaluating scripts for potential improvements.
def get_single_int_pk_colname(table_: Table) -> Optional[str]: """ If a table has a single-field (non-composite) integer PK, this will return its database column name; otherwise, None. Note that it is legitimate for a database table to have both a composite primary key and a separate ``IDENTITY`` (...
How would you code a function in Python 3 to return the database column name for a single - field integer PK.
As a Python code composer, you craft elegant and concise scripts.
def get_single_int_autoincrement_colname(table_: Table) -> Optional[str]: """ If a table has a single integer ``AUTOINCREMENT`` column, this will return its name; otherwise, ``None``. - It's unlikely that a database has >1 ``AUTOINCREMENT`` field anyway, but we should check. - SQL Server's ``...
Create a Python 3 function to return the name of the column that is used for autoincrementing the given table.
You are a Python code architect, reviewing and designing scalable and efficient code
def index_exists(engine: Engine, tablename: str, indexname: str) -> bool: """ Does the specified index exist for the specified table? """ insp = Inspector.from_engine(engine) return any(i['name'] == indexname for i in insp.get_indexes(tablename))
Create a Python 3 function to return True if the specified index exists for the specified table.
As a python code expert, you are capable of creating scripts from specifications.
def mssql_get_pk_index_name(engine: Engine, tablename: str, schemaname: str = MSSQL_DEFAULT_SCHEMA) -> str: """ For Microsoft SQL Server specifically: fetch the name of the PK index for the specified table (in the specified schema), or ``''`` if none i...
How would you implement a function in Python 3 that fetches the name of the PK index for the specified table in the specified schema.
As a Python code translator, you convert algorithms and pseudocode into Python.
def mssql_transaction_count(engine_or_conn: Union[Connection, Engine]) -> int: """ For Microsoft SQL Server specifically: fetch the value of the ``TRANCOUNT`` variable (see e.g. https://docs.microsoft.com/en-us/sql/t-sql/functions/trancount-transact-sql?view=sql-server-2017). Returns ``None`` if it ...
How would you code a function in Python 3 to get the number of transactions in the database.
As a python code expert, you are capable of creating scripts from specifications.
Adds an index to a database column or multiple columns.
Can you generate the documentation for the following Python 3 function def add_index(engine: Engine, sqla_column: Column = None, multiple_sqla_columns: List[Column] = None, unique: bool = False, fulltext: bool = False, length: int = None) -> None: ...
You are a Python code analyst, evaluating scripts for potential improvements.
def make_bigint_autoincrement_column(column_name: str, dialect: Dialect) -> Column: """ Returns an instance of :class:`Column` representing a :class:`BigInteger` ``AUTOINCREMENT`` column in the specified :class:`Dialect`. """ # noinspection PyUnresolvedReferences...
How would you code a function in Python 3 to return an instance of Column representing a BIGINT autoincrement column.
As a python code expert, you are capable of creating scripts from specifications.
def column_creation_ddl(sqla_column: Column, dialect: Dialect) -> str: """ Returns DDL to create a column, using the specified dialect. The column should already be bound to a table (because e.g. the SQL Server dialect requires this for DDL generation). Manual testing: .. code-block:: pyt...
Can you write a function in Python 3 where it returns a DDL to create a column using the specified dialect.
As a Python code translator, you convert algorithms and pseudocode into Python.
Returns the SQL column type used to make very large text columns for a SQLAlchemy dialect.
How would you explain what the following Python 3 function does def giant_text_sqltype(dialect: Dialect) -> str: if dialect.name == SqlaDialectName.SQLSERVER: return 'NVARCHAR(MAX)' elif dialect.name == SqlaDialectName.MYSQL: return 'LONGTEXT' else: raise ValueError("Unknown dialect:...
As a Python code analyst, you investigate and solve complex coding mysteries
Returns the SQLAlchemy class corresponding to a particular SQL column type in a given dialect.
How would you explain what the following Python 3 function does def _get_sqla_coltype_class_from_str(coltype: str, dialect: Dialect) -> Type[TypeEngine]: """ Returns the SQLAlchemy class corresponding to a particular SQL column type in a given dialect. Performs an u...
As a Python code translator, you convert algorithms and pseudocode into Python.
This function takes a quoted CSV file and returns a list of SQL string literals.
Explain what the following Python 3 code does def get_list_of_sql_string_literals_from_quoted_csv(x: str) -> List[str]: f = io.StringIO(x) reader = csv.reader(f, delimiter=',', quotechar="'", quoting=csv.QUOTE_ALL, skipinitialspace=True) for line in reader: # should only be one ...
As a python code expert, you are capable of creating scripts from specifications.
Returns an SQLAlchemy column type given a column type name and an SQLAlchemy dialect.
Here you have a function in Python 3, explain what it does def get_sqla_coltype_from_dialect_str(coltype: str, dialect: Dialect) -> TypeEngine: """ Returns an SQLAlchemy column type, given a column type name (a string) and an SQLAlchemy dialect. For example, this might ...
You are a Python code architect, reviewing and designing scalable and efficient code
def remove_collation(coltype: TypeEngine) -> TypeEngine: """ Returns a copy of the specific column type with any ``COLLATION`` removed. """ if not getattr(coltype, 'collation', None): return coltype newcoltype = copy.copy(coltype) newcoltype.collation = None return newcoltype
How would you code a function in Python 3 to return a copy of the specific column type with any COLLATION removed.
As a python code expert, you are capable of creating scripts from specifications.
Converts an SQLAlchemy column type instance from one SQL dialect to another.
How would you explain what the following Python 3 function does def convert_sqla_type_for_dialect( coltype: TypeEngine, dialect: Dialect, strip_collation: bool = True, convert_mssql_timestamp: bool = True, expand_for_scrubbing: bool = False) -> TypeEngine: """ Converts an...
As a Python code translator, you convert algorithms and pseudocode into Python.
def _coltype_to_typeengine(coltype: Union[TypeEngine, VisitableType]) -> TypeEngine: """ An example is simplest: if you pass in ``Integer()`` (an instance of :class:`TypeEngine`), you'll get ``Integer()`` back. If you pass in ``Integer`` (an instance of :class:`...
Can you implement a function in Python 3 that converts a column type to a typeengine.
As a Python code composer, you craft elegant and concise scripts.
Returns True if the SQLAlchemy column type is a binary type.
Here you have a function in Python 3, explain what it does def is_sqlatype_binary(coltype: Union[TypeEngine, VisitableType]) -> bool: # Several binary types inherit internally from _Binary, making that the # easiest to check. coltype = _coltype_to_typeengine(coltype) # noinspection PyProtectedMember ...
As a Python code analyst, you investigate and solve complex coding mysteries
Is the SQLAlchemy column type a date type?
Can you generate the documentation for the following Python 3 function def is_sqlatype_date(coltype: TypeEngine) -> bool: coltype = _coltype_to_typeengine(coltype) # No longer valid in SQLAlchemy 1.2.11: # return isinstance(coltype, sqltypes._DateAffinity) return ( isinstance(coltype, sqltypes.D...
You are a Python code analyst, evaluating scripts for potential improvements.
Returns true if the SQLAlchemy column type is an integer type?
Can you generate a brief explanation for the following Python 3 code def is_sqlatype_integer(coltype: Union[TypeEngine, VisitableType]) -> bool: coltype = _coltype_to_typeengine(coltype) return isinstance(coltype, sqltypes.Integer)
As a Python code analyst, you investigate and solve complex coding mysteries
def is_sqlatype_numeric(coltype: Union[TypeEngine, VisitableType]) -> bool: """ Is the SQLAlchemy column type one that inherits from :class:`Numeric`, such as :class:`Float`, :class:`Decimal`? """ coltype = _coltype_to_typeengine(coltype) return isinstance(coltype, sqltypes.Numeric)
Write a Python 3 script for returning true if the SQLAlchemy column type is a numeric type.
As a Python code analyst, you investigate and solve complex coding mysteries
def is_sqlatype_string(coltype: Union[TypeEngine, VisitableType]) -> bool: """ Is the SQLAlchemy column type a string type? """ coltype = _coltype_to_typeengine(coltype) return isinstance(coltype, sqltypes.String)
Can you write a function in Python 3 where it returns true if the SQLAlchemy column type is a string type.
As a Python code analyst, you investigate and solve complex coding mysteries