output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
def guess_base_branch(): # type: (str) -> Optional[str, None] """ Try to guess the base branch for the current branch. Do not trust this guess. git makes it pretty much impossible to guess the base branch reliably so this function implements few heuristics that will work on most common use cases bu...
Write a Python 3 function that can try to guess the base branch for the current branch.
You are a Python code architect, reviewing and designing scalable and efficient code
Returns the author of the given commit.
Make a summary of the following Python 3 code def commit_author(sha1=''): # type: (str) -> Author """ Return the author of the given commit. Args: sha1 (str): The sha1 of the commit to query. If not given, it will return the sha1 for the current commit. Returns: ...
As a Python code analyst, you investigate and solve complex coding mysteries
Return a list of unstaged files in the project repository.
Here you have a function in Python 3, explain what it does def unstaged(): # type: () -> List[str] """ Return a list of unstaged files in the project repository. Returns: list[str]: The list of files not tracked by project git repo. """ with conf.within_proj_dir(): status = shell.ru...
As a Python code composer, you craft elegant and concise scripts.
Return a list of patterns in the project. gitignore that are not in the project. gitignore file.
Can you generate the documentation for the following Python 3 function def ignore(): # type: () -> List[str] """ Return a list of patterns in the project .gitignore Returns: list[str]: List of patterns set to be ignored by git. """ def parse_line(line): # pylint: disable=missing-docstrin...
As a Python code analyst, you investigate and solve complex coding mysteries
def branches(): # type: () -> List[str] """ Return a list of branches in the current repo. Returns: list[str]: A list of branches in the current repo. """ out = shell.run( 'git branch', capture=True, never_pretend=True ).stdout.strip() return [x.strip('* \t\n...
How would you code a function in Python 3 to return a list of branches in the current repo.
You are a Python code generator, capable of creating scripts from specifications.
def tag(name, message, author=None): # type: (str, str, Author, bool) -> None """ Tag the current commit. Args: name (str): The tag name. message (str): The tag message. Same as ``-m`` parameter in ``git tag``. author (Author): The commit author. ...
How would you code a function in Python 3 to tag the current commit.
You are a Python code architect, reviewing and designing scalable and efficient code
Return the current git configuration.
Can you tell what is the following Python 3 function doing def config(): # type: () -> dict[str, Any] """ Return the current git configuration. Returns: dict[str, Any]: The current git config taken from ``git config --list``. """ out = shell.run( 'git config --list', capture...
You are a Python code analyst, evaluating scripts for potential improvements.
Returns all tags in the repo sorted as versions.
Make a summary of the following Python 3 code def tags(): # type: () -> List[str] """ Returns all tags in the repo. Returns: list[str]: List of all tags in the repo, sorted as versions. All tags returned by this function will be parsed as if the contained versions (using ``v:refname`` sort...
As a Python code translator, you convert algorithms and pseudocode into Python.
Verify if a given branch exists.
Make a summary of the following Python 3 code def verify_branch(branch_name): # type: (str) -> bool """ Verify if the given branch exists. Args: branch_name (str): The name of the branch to check. Returns: bool: **True** if a branch with name *branch_name* exits, **False** ...
As a Python code composer, you craft elegant and concise scripts.
Return branches protected by deletion. By default those are master and devel branches as configured in pelconf. Returns: list[str]: Names of important branches that should not be deleted.
Can you tell what is the following Python 3 function doing def protected_branches(): # type: () -> list[str] """ Return branches protected by deletion. By default those are master and devel branches as configured in pelconf. Returns: list[str]: Names of important branches that should not be de...
As a Python code composer, you craft elegant and concise scripts.
def branches(self): # type: () -> List[str] """ List of all branches this commit is a part of. """ if self._branches is None: cmd = 'git branch --contains {}'.format(self.sha1) out = shell.run( cmd, capture=True, never_prete...
Write a Python 3 script for listing of all branches this commit is a part of.
You are a Python code generator, capable of creating scripts from specifications.
Return the list of parents of this commit.
Can you generate a brief explanation for the following Python 3 code def parents(self): # type: () -> List[CommitDetails] """ Parents of the this commit. """ if self._parents is None: self._parents = [CommitDetails.get(x) for x in self.parents_sha1] return self._parents
As a Python code composer, you craft elegant and concise scripts.
Return this commits number.
Can you generate the documentation for the following Python 3 function def number(self): # type: () -> int """ Return this commits number. This is the same as the total number of commits in history up until this commit. This value can be useful in some CI scenarios as it allows...
As a Python code translator, you convert algorithms and pseudocode into Python.
Returns the details about a given commit.
Given the following Python 3 function, write the documentation def get(cls, sha1=''): # type: (str) -> CommitDetails """ Return details about a given commit. Args: sha1 (str): The sha1 of the commit to query. If not given, it will return the details f...
As a Python code analyst, you investigate and solve complex coding mysteries
def main(): """Sample usage for this python module This main method simply illustrates sample usage for this python module. :return: None """ log = logging.getLogger(Logify.get_name() + '.logify.main') log.info('logger name is: %s', Logify.get_name()) log.debug('This is DEBUG') log...
Write a Python 3 function for sampling usage for this python module This main method simply illustrates sample usage for this python module. :return: None
As a Python code translator, you convert algorithms and pseudocode into Python.
def set_log_level(cls, log_level): """Sets the log level for cons3rt assets This method sets the logging level for cons3rt assets using pycons3rt. The loglevel is read in from a deployment property called loglevel and set appropriately. :type log_level: str :return: Tru...
Write a Python 3 script to set the log level for cons3rt assets using .
As a Python code composer, you craft elegant and concise scripts.
def get_record_by_name(self, index, name): """ Searches for a single document in the given index on the 'name' field . Performs a case-insensitive search by utilizing Elasticsearch's `match_phrase` query. Args: index: `str`. The name of an Elasticsearch index (i.e. biosa...
Create a Python 3 function to search for a single record in the given index on the name field.
You are a Python code architect, reviewing and designing scalable and efficient code
Finds an in object via a period - delimited string name.
Can you generate a brief explanation for the following Python 3 code def getattr_in(obj, name): for part in name.split('.'): obj = getattr(obj, part) return obj
You are a Python code architect, reviewing and designing scalable and efficient code
def import_from(name): """ Imports a module, class or method from string and unwraps it if wrapped by functools @name: (#str) name of the python object -> imported object """ obj = name if isinstance(name, str) and len(name): try: obj = locate(name) ...
Write a Python 3 script for importing a module class or method from string and unwraps it AttributeNames if wrapped by functools AttributeNames.
As a Python code translator, you convert algorithms and pseudocode into Python.
def unwrap_obj(obj): """ Gets the actual object from a decorated or wrapped function @obj: (#object) the object to unwrap """ try: obj = obj.fget except (AttributeError, TypeError): pass try: # Cached properties if obj.func.__doc__ == obj.__doc__: ...
Can you write a function in Python 3 where it gets the actual object from a decorated or wrapped function AttributeNames
You are a Python code analyst, evaluating scripts for potential improvements.
def add_modality(output_path, modality): """Modality can be appended to the file name (such as 'bold') or use in the folder (such as "func"). You should always use the specific modality ('bold'). This function converts it to the folder name. """ if modality is None: return output_path el...
Can you create a Python 3 function that adds modality to the file name.
As a Python code analyst, you investigate and solve complex coding mysteries
def load(): # type: () -> None """ Load configuration from file. This will search the directory structure upwards to find the project root (directory containing ``pelconf.py`` file). Once found it will import the config file which should initialize all the configuration (using `peltak.core.conf...
Implement a Python 3 function for loading configuration from file.
As a python code expert, you are capable of creating scripts from specifications.
def load_yaml_config(conf_file): # type: (str) -> None """ Load a YAML configuration. This will not update the configuration but replace it entirely. Args: conf_file (str): Path to the YAML config. This function will not check the file name or extension and will just cr...
Create a Python 3 function for loading a YAML file into the global configuration object.
You are a Python code analyst, evaluating scripts for potential improvements.
def load_py_config(conf_file): # type: (str) -> None """ Import configuration from a python file. This will just import the file into python. Sky is the limit. The file has to deal with the configuration all by itself (i.e. call conf.init()). You will also need to add your src directory to sys.path...
Implement a function in Python 3 to load a configuration file into a python module.
As a Python code composer, you craft elegant and concise scripts.
def load_template(filename): # type: (str) -> str """ Load template from file. The templates are part of the package and must be included as ``package_data`` in project ``setup.py``. Args: filename (str): The template path. Relative to `peltak` package directory. Returns: ...
Can you create a Python 3 function that loads a template from a file.
You are a Python code generator, capable of creating scripts from specifications.
def proj_path(*path_parts): # type: (str) -> str """ Return absolute path to the repo dir (root project directory). Args: path (str): The path relative to the project root (pelconf.yaml). Returns: str: The given path converted to an absolute path. """ path_parts = p...
Can you create a Python 3 function that returns the absolute path to the project directory.
You are a Python code analyst, evaluating scripts for potential improvements.
def within_proj_dir(path='.'): # type: (Optional[str]) -> str """ Return an absolute path to the given project relative path. :param path: Project relative path that will be converted to the system wide absolute path. :return: Absolute path. """ curr_dir = os.getcwd() ...
Write a Python 3 script for returning an absolute path to the given project relative path.
You are a Python code analyst, evaluating scripts for potential improvements.
def get(name, *default): # type: (str, Any) -> Any """ Get config value with the given name and optional default. Args: name (str): The name of the config value. *default (Any): If given and the key doesn't not exist, this will be returned instead. If it'...
Can you implement a function in Python 3 that gets the config value with the given name and optional default.
As a Python code composer, you craft elegant and concise scripts.
def get_path(name, *default): # type: (str, Any) -> Any """ Get config value as path relative to the project directory. This allows easily defining the project configuration within the fabfile as always relative to that fabfile. Args: name (str): The name of the config value co...
Create a Python 3 function for getting the config value as path relative to the project directory.
You are a Python code analyst, evaluating scripts for potential improvements.
Find the project root of the current directory.
Can you generate a brief explanation for the following Python 3 code def _find_proj_root(): # type: () -> Optional[str] """ Find the project path by going up the file tree. This will look in the current directory and upwards for the pelconf file (.yaml or .py) """ proj_files = frozenset(('pelco...
As a python code expert, you are capable of creating scripts from specifications.
Проверяем ошибки ключ получаем пол
Make a summary of the following Python 3 code def verify(verified_entity, verification_key): verification = get_object_or_none(Verification, verified_entity=verified_entity) if verification is None: raise ServerError(VerificationHandler.STATUS_VERIFICATION_NOT_FOUND) if not verifica...
You are a Python code analyst, evaluating scripts for potential improvements.
Gets the XML element value.
Make a summary of the following Python 3 code def _xml_element_value(el: Element, int_tags: list): # None if el.text is None: return None # int try: if el.tag in int_tags: return int(el.text) except: pass # default to str if not empty s = str(el.text).stri...
As a Python code analyst, you investigate and solve complex coding mysteries
def _xml_tag_filter(s: str, strip_namespaces: bool) -> str: """ Returns tag name and optionally strips namespaces. :param el: Element :param strip_namespaces: Strip namespace prefix :return: str """ if strip_namespaces: ns_end = s.find('}') if ns_end != -1: s = s[...
Implement a function in Python 3 to filter XML tags to remove namespaces.
As a python code expert, you are capable of creating scripts from specifications.
Parses XML string to dict.
Given the following Python 3 function, write the documentation def xml_to_dict(xml_bytes: bytes, tags: list=[], array_tags: list=[], int_tags: list=[], strip_namespaces: bool=True, parse_attributes: bool=True, value_key: str='@', attribute_prefix: str='@', document_tag: b...
As a Python code analyst, you investigate and solve complex coding mysteries
Generates XML element from dict.
Make a summary of the following Python 3 code def dict_to_element(doc: dict, value_key: str='@', attribute_prefix: str='@') -> Element: from xml.etree import ElementTree as ET if len(doc) != 1: raise Exception('Invalid data dict for XML generation, document root must have single element') for tag,...
You are a Python code architect, reviewing and designing scalable and efficient code
Property structure which maps within the thread - local variable.
Given the following Python 3 function, write the documentation def local_property(): ls = local() def fget(self): try: return ls.var except AttributeError: raise RuntimeError("Request context not initialized.") def fset(self, value): ls.var = value def ...
You are a Python code analyst, evaluating scripts for potential improvements.
This method searches the S3 bucket for matching the passed regular expression and returns a list of strings containing the keys that match the passed regular expression.
Explain what the following Python 3 code does def find_bucket_keys(bucket_name, regex, region_name=None, aws_access_key_id=None, aws_secret_access_key=None): log = logging.getLogger(mod_logger + '.find_bucket_keys') matched_keys = [] if not isinstance(regex, basestring): log.error('regex argument is...
As a Python code analyst, you investigate and solve complex coding mysteries
Verify that the specified bucket exists.
Here you have a function in Python 3, explain what it does def validate_bucket(self): log = logging.getLogger(self.cls_logger + '.validate_bucket') log.info('Attempting to get bucket: {b}'.format(b=self.bucket_name)) max_tries = 10 count = 1 while count <= max_tries: ...
As a Python code analyst, you investigate and solve complex coding mysteries
Downloads a file from the specified S3 bucket and stores it in the specified destination directory.
Can you tell what is the following Python 3 function doing def download_file_by_key(self, key, dest_dir): log = logging.getLogger(self.cls_logger + '.download_file_by_key') if not isinstance(key, basestring): log.error('key argument is not a string') return None if not is...
You are a Python code architect, reviewing and designing scalable and efficient code
Downloads a file from the specified S3 bucket and stores it in the specified destination directory.
Can you generate a brief explanation for the following Python 3 code def download_file(self, regex, dest_dir): log = logging.getLogger(self.cls_logger + '.download_file') if not isinstance(regex, basestring): log.error('regex argument is not a string') return None if not ...
As a Python code composer, you craft elegant and concise scripts.
def find_key(self, regex): """Attempts to find a single S3 key based on the passed regex Given a regular expression, this method searches the S3 bucket for a matching key, and returns it if exactly 1 key matches. Otherwise, None is returned. :param regex: (str) Regular expressi...
Can you write a function in Python 3 where it attempts to find a single S3 key based on the passed regex Given a regular expression, this method searches the S3 bucket for a matching key, and returns it if exactly 1 key matches. Otherwise, None is returned. :param regex: (str) Regular expression for an S3 key :return: ...
As a python code expert, you are capable of creating scripts from specifications.
This method searches the S3 bucket for matching the passed regular expression and returns a list of strings containing the matched S3 keys.
Can you tell what is the following Python 3 function doing def find_keys(self, regex, bucket_name=None): log = logging.getLogger(self.cls_logger + '.find_keys') matched_keys = [] if not isinstance(regex, basestring): log.error('regex argument is not a string, found: {t}'.format(t=reg...
As a python code expert, you are capable of creating scripts from specifications.
def upload_file(self, filepath, key): """Uploads a file using the passed S3 key This method uploads a file specified by the filepath to S3 using the provided S3 key. :param filepath: (str) Full path to the file to be uploaded :param key: (str) S3 key to be set for the upload ...
Implement a Python 3 function for uploading a file to the specified S3 key using the passed S3 key.
You are a Python code generator, capable of creating scripts from specifications.
def delete_key(self, key_to_delete): """Deletes the specified key :param key_to_delete: :return: """ log = logging.getLogger(self.cls_logger + '.delete_key') log.info('Attempting to delete key: {k}'.format(k=key_to_delete)) try: self.s3client.delete_...
Create a Python 3 function for deleting the specified key in the specified bucket.
You are a Python code generator, capable of creating scripts from specifications.
def assert_branch_type(branch_type): # type: (str) -> None """ Print error and exit if the current branch is not of a given type. Args: branch_type (str): The branch type. This assumes the branch is in the '<type>/<title>` format. """ branch = git.current_branch(refr...
Create a Python 3 function to check that the current branch is of a given type.
As a Python code composer, you craft elegant and concise scripts.
def assert_on_branch(branch_name): # type: (str) -> None """ Print error and exit if *branch_name* is not the current branch. Args: branch_name (str): The supposed name of the current branch. """ branch = git.current_branch(refresh=True) if branch.name != branch_name: ...
Can you write a function in Python 3 where it prints error and exit if you re not on a branch.
As a python code expert, you are capable of creating scripts from specifications.
Delete the given branch.
Can you generate a brief explanation for the following Python 3 code def git_branch_delete(branch_name): # type: (str) -> None """ Delete the given branch. Args: branch_name (str): Name of the branch to delete. """ if branch_name not in git.protected_branches(): log.info...
As a Python code analyst, you investigate and solve complex coding mysteries
def git_branch_rename(new_name): # type: (str) -> None """ Rename the current branch Args: new_name (str): New name for the current branch. """ curr_name = git.current_branch(refresh=True).name if curr_name not in git.protected_branches(): log.info("Renaming branch ...
How would you implement a function in Python 3 that renames the current branch to new name.
You are a Python code generator, capable of creating scripts from specifications.
Checkout or create a given branch
Can you generate the documentation for the following Python 3 function def git_checkout(branch_name, create=False): # type: (str, bool) -> None """ Checkout or create a given branch Args: branch_name (str): The name of the branch to checkout or create. create (bool): ...
You are a Python code analyst, evaluating scripts for potential improvements.
Merge head into base branch.
Here you have a function in Python 3, explain what it does def git_merge(base, head, no_ff=False): # type: (str, str, bool) -> None """ Merge *head* into *base*. Args: base (str): The base branch. *head* will be merged into this branch. head (str): The branch that wi...
As a Python code analyst, you investigate and solve complex coding mysteries
def get_base_branch(): # type: () -> str """ Return the base branch for the current branch. This function will first try to guess the base branch and if it can't it will let the user choose the branch from the list of all local branches. Returns: str: The name of the branch the current bra...
How would you code a function in Python 3 to return the base branch for the current branch.
You are a Python code generator, capable of creating scripts from specifications.
def choose_branch(exclude=None): # type: (List[str]) -> str """ Show the user a menu to pick a branch from the existing ones. Args: exclude (list[str]): List of branch names to exclude from the menu. By default it will exclude master and develop branches. To show all branche...
Write a Python 3 function for showing the user a menu to choose a branch from the existing ones.
As a python code expert, you are capable of creating scripts from specifications.
def autorun(): ''' Call the run method of the decorated class if the current file is the main file ''' def wrapper(cls): import inspect if inspect.getmodule(cls).__name__ == "__main__": cls().run() return cls return wrapper
How would you code a function in Python 3 to call the run method of the decorated class if the current file is the main file
As a python code expert, you are capable of creating scripts from specifications.
Returns a list of unique elements from given list or sequence - like object.
Make a summary of the following Python 3 code def unique_list(seq): seen = set() seen_add = seen.add return [x for x in seq if not (x in seen or seen_add(x))]
As a Python code analyst, you investigate and solve complex coding mysteries
Flattens a sequence e. g. |1 2 3 4 5
Can you tell what is the following Python 3 function doing def flatten(*seqs): for seq in seqs: for item in seq: if isinstance(item, (tuple, list, UserList)): for subitem in flatten(item): yield subitem else: yield item
As a Python code composer, you craft elegant and concise scripts.
Yields random values from the given sequence.
Can you generate a brief explanation for the following Python 3 code def randrange(seq): seq = seq.copy() choose = rng().choice remove = seq.remove for x in range(len(seq)): y = choose(seq) remove(y) yield y
You are a Python code analyst, evaluating scripts for potential improvements.
Linearly solve a least - squares solution to a linear matrix equation.
Can you tell what is the following Python 3 function doing def linear_least_squares(a, b, residuals=False): # Copyright (c) 2013 Alexandre Drouin. All rights reserved. # From https://gist.github.com/aldro61/5889795 from warnings import warn # from scipy.linalg.fblas import dgemm from scipy.linalg.b...
You are a Python code generator, capable of creating scripts from specifications.
def validate_ip_address(ip_address): """Validate the ip_address :param ip_address: (str) IP address :return: (bool) True if the ip_address is valid """ # Validate the IP address log = logging.getLogger(mod_logger + '.validate_ip_address') if not isinstance(ip_address, basestring): l...
Write a Python 3 script for validating the IP address and return a boolean if the IP address is valid otherwise False
As a Python code composer, you craft elegant and concise scripts.
Uses the ip addr command to enumerate IP addresses by device
Given the following Python 3 function, write the documentation def ip_addr(): log = logging.getLogger(mod_logger + '.ip_addr') log.debug('Running the ip addr command...') ip_addr_output = {} command = ['ip', 'addr'] try: ip_addr_result = run_command(command, timeout_sec=20) except Comma...
As a Python code composer, you craft elegant and concise scripts.
def alias_ip_address(ip_address, interface, aws=False): """Adds an IP alias to a specific interface Adds an ip address as an alias to the specified interface on Linux systems. :param ip_address: (str) IP address to set as an alias :param interface: (str) The interface number or full device name, i...
Create a Python 3 function for adding an IP address to an existing alias on the specified interface on the specified Linux systems.
As a Python code translator, you convert algorithms and pseudocode into Python.
def set_source_ip_for_interface(source_ip_address, desired_source_ip_address, device_num=0): """Configures the source IP address for a Linux interface :param source_ip_address: (str) Source IP address to change :param desired_source_ip_address: (str) IP address to configure as the source in outgoing packet...
How would you code a function in Python 3 to configure the source IP address for a Linux interface.
You are a Python code generator, capable of creating scripts from specifications.
Save the object to the database.
How would you explain what the following Python 3 function does def save_logic(self, some_object): some_object.validate_model() some_object.save() self.send_success_response(data=some_object.to_dict())
You are a Python code architect, reviewing and designing scalable and efficient code
Generate shell color opcodes from a pretty coloring syntax.
Here you have a function in Python 3, explain what it does def fmt(msg, *args, **kw): # type: (str, *Any, **Any) -> str """ Generate shell color opcodes from a pretty coloring syntax. """ global is_tty if len(args) or len(kw): msg = msg.format(*args, **kw) opcode_subst = '\x1b[\\1m' if is_...
You are a Python code analyst, evaluating scripts for potential improvements.
def cprint(msg, *args, **kw): # type: (str, *Any, **Any) -> None """ Print colored message to stdout. """ if len(args) or len(kw): msg = msg.format(*args, **kw) print(fmt('{}<0>'.format(msg)))
Implement a function in Python 3 to print a message to stdout.
You are a Python code generator, capable of creating scripts from specifications.
Runs a command and returns a list of the return code and output of the command.
Given the following Python 3 function, write the documentation def run(cmd, capture=False, shell=True, env=None, exit_on_error=None, never_pretend=False): # type: (str, bool, bool, Dict[str, str], bool) -> ExecResult """ Run a shell command. Args: cmd (str): ...
As a Python code composer, you craft elegant and concise scripts.
Extracts the request s payload information.
Can you generate the documentation for the following Python 3 function def get_payload(request): # always extract values from the URL payload = dict(request.params.mixed()) # provide override capability from the JSON body try: json_data = request.json_body # no JSON body was found, pyramid...
As a python code expert, you are capable of creating scripts from specifications.
This module is called by the module s main function.
Given the following Python 3 function, write the documentation def main(): log = logging.getLogger(mod_logger + '.main') parser = argparse.ArgumentParser(description='This module allows sending email messages.') parser.add_argument('-f', '--file', help='Full path to a plain text file', required=False) p...
You are a Python code architect, reviewing and designing scalable and efficient code
def send_cons3rt_agent_logs(self): """Send the cons3rt agent log file :return: """ log = logging.getLogger(self.cls_logger + '.send_cons3rt_agent_logs') if self.cons3rt_agent_log_dir is None: log.warn('There is not CONS3RT agent log directory on this system') ...
Can you implement a function in Python 3 that sends the cons3rt agent log files to the system
As a Python code composer, you craft elegant and concise scripts.
Sends an email with the contents of the provided text file.
Here you have a function in Python 3, explain what it does def send_text_file(self, text_file, sender=None, recipient=None): log = logging.getLogger(self.cls_logger + '.send_text_file') if not isinstance(text_file, basestring): msg = 'arg text_file must be a string, found type: {t}'.format(...
As a python code expert, you are capable of creating scripts from specifications.
Get a date range by name.
Given the following Python 3 function, write the documentation def get_date_range_by_name(name: str, today: datetime=None, tz=None) -> (datetime, datetime): if today is None: today = datetime.utcnow() if name == 'last_month': return last_month(today, tz) elif name == 'last_week': ret...
As a Python code analyst, you investigate and solve complex coding mysteries
def parse_date_range_arguments(options: dict, default_range='last_month') -> (datetime, datetime, list): """ :param options: :param default_range: Default datetime range to return if no other selected :return: begin, end, [(begin1,end1), (begin2,end2), ...] """ begin, end = get_date_range_by_nam...
Implement a function in Python 3 to parse the options dictionary to get the datetime range and the list of times that are needed to select the next time.
You are a Python code analyst, evaluating scripts for potential improvements.
def load_elements(self): #Set atomic data #atomicData.setDataFile('he_i_rec_Pal12-Pal13.fits') atomicData.setDataFile('s_iii_coll_HRS12.dat') #Default: 's_iii_atom_PKW09.dat' 'S3: All energy and A values: Podobedova, Kelleher, and Wiese 2009, J. Phys. Chem. Ref. Data, Vol.' ...
Implement a function in Python 3 to load the elements of the current species and set the attributes of the current species.
You are a Python code analyst, evaluating scripts for potential improvements.
Clones a git repository into a new directory.
Explain what the following Python 3 code does def git_clone(url, clone_dir, branch='master', username=None, password=None, max_retries=10, retry_sec=30, git_cmd=None): """Clones a git url :param url: (str) Git URL in https or ssh :param clone_dir: (str) Path to the desired destination dir ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Performs URL encoding for passwords
Can you tell what is the following Python 3 function doing def encode_password(password): log = logging.getLogger(mod_logger + '.password_encoder') log.debug('Encoding password: {p}'.format(p=password)) encoded_password = '' for c in password: encoded_password += encode_character(char=c) log...
You are a Python code analyst, evaluating scripts for potential improvements.
def search_tags_as_filters(tags): """Get different tags as dicts ready to use as dropdown lists.""" # set dicts actions = {} contacts = {} formats = {} inspire = {} keywords = {} licenses = {} md_types = dict() owners = defaultdict(str) srs = {} unused = {} # 0/1 valu...
Write a Python 3 script for getting different tags as dicts ready to use as dropdown lists.
You are a Python code architect, reviewing and designing scalable and efficient code
Generate a new instance of the class.
Can you generate a brief explanation for the following Python 3 code def generate(self, verified, keygen): return Verification( verified_entity=verified, key=keygen(), verified=False )
As a Python code translator, you convert algorithms and pseudocode into Python.
def iban_bank_info(v: str) -> (str, str): """ Returns BIC code and bank name from IBAN number. :param v: IBAN account number :return: (BIC code, bank name) or ('', '') if not found / unsupported country """ v = iban_filter(v) if v[:2] == 'FI': return fi_iban_bank_info(v) else: ...
Write a Python 3 script for returning BIC code and bank name from IBAN number.
You are a Python code generator, capable of creating scripts from specifications.
def fi_payment_reference_number(num: str): """ Appends Finland reference number checksum to existing number. :param num: At least 3 digits :return: Number plus checksum """ assert isinstance(num, str) num = STRIP_WHITESPACE.sub('', num) num = re.sub(r'^0+', '', num) assert len(num) >...
Write a Python 3 script to add Finland reference number checksum to existing number.
You are a Python code analyst, evaluating scripts for potential improvements.
Validates ISO payment reference checksum.
Given the following Python 3 function, write the documentation def iso_payment_reference_validator(v: str): num = '' v = STRIP_WHITESPACE.sub('', v) for ch in v[4:] + v[0:4]: x = ord(ch) if ord('0') <= x <= ord('9'): num += ch else: x -= 55 if x < ...
As a Python code analyst, you investigate and solve complex coding mysteries
Returns BIC code and bank name from FI IBAN number.
Make a summary of the following Python 3 code def fi_iban_bank_info(v: str) -> (str, str): from jutil.bank_const_fi import FI_BIC_BY_ACCOUNT_NUMBER, FI_BANK_NAME_BY_BIC v = iban_filter(v) bic = FI_BIC_BY_ACCOUNT_NUMBER.get(v[4:7], None) return (bic, FI_BANK_NAME_BY_BIC[bic]) if bic is not None else ('',...
As a Python code analyst, you investigate and solve complex coding mysteries
def se_clearing_code_bank_info(clearing: str) -> (str, int): """ Returns Sweden bank info by clearning code. :param clearing: 4-digit clearing code :return: (Bank name, account digit count) or ('', None) if not found """ from jutil.bank_const_se import SE_BANK_CLEARING_LIST for name, begin, ...
Write a Python 3 script for returning Sweden bank info by clearing code.
You are a Python code analyst, evaluating scripts for potential improvements.
Formats the value in required HTTP style -> string HTTP - style formatted date
How would you explain what the following Python 3 function does def http_date(value): if isinstance(value, datetime.datetime): value = value.utctimetuple() elif isinstance(value, (int, float)): value = time.gmtime(value) if not isinstance(value, str): value = time.strftime("%a, %d %b...
You are a Python code generator, capable of creating scripts from specifications.
Parse RFC 2617 HTTP authentication header string and return user and pass tuple.
Can you generate a brief explanation for the following Python 3 code def parse_auth(header): try: method, data = header.split(None, 1) if method.lower() == 'basic': data = base64.b64decode(uniorbytes(data, bytes)) user, pwd = uniorbytes(data).split(':', 1) return ...
You are a Python code analyst, evaluating scripts for potential improvements.
Generates an identicon image based on the data passed in.
Given the following Python 3 function, write the documentation def image(request, data): # Get image width, height, padding, and format from GET parameters, or # fall-back to default values from settings. try: width = int(request.GET.get("w", PYDENTICON_WIDTH)) except ValueError: raise ...
You are a Python code analyst, evaluating scripts for potential improvements.
def rename(name): # type: (str) -> None """ Give the currently developed hotfix a new name. """ from peltak.extra.gitflow import logic if name is None: name = click.prompt('Hotfix name') logic.hotfix.rename(name)
Write a Python 3 function that can give the currently developed hotfix a new name.
You are a Python code analyst, evaluating scripts for potential improvements.
A function to wrap a lru_cache function that can be used to cache the objects in a single thread.
Explain what the following Python 3 code does def typed_lru(maxsize, types=None): types = types or collections.Hashable def lru(obj): @lru_cache(maxsize) def _lru_cache(*args, **kwargs): return obj(*args, **kwargs) @wraps(obj) def _convenience(*args, **kwargs): ...
You are a Python code generator, capable of creating scripts from specifications.
Get the context value with the given name and optional default value.
Make a summary of the following Python 3 code def get(self, name, *default): # type: (str, Any) -> Any """ Get context value with the given name and optional default. Args: name (str): The name of the context value. *default (Any): If give...
As a Python code composer, you craft elegant and concise scripts.
def set(self, name, value): """ Set context value. Args: name (str): The name of the context value to change. value (Any): The new value for the selected context value """ curr = self.values parts = name.split('.') ...
Write a Python 3 script for setting the value of the context value.
As a Python code analyst, you investigate and solve complex coding mysteries
Checks if an alias already exists in a keystore
Can you tell what is the following Python 3 function doing def alias_exists(alias, keystore_path=None, keystore_password='changeit'): log = logging.getLogger(mod_logger + '.alias_exists') if not isinstance(alias, basestring): msg = 'alias arg must be a string' log.error(msg) raise OSErro...
As a Python code analyst, you investigate and solve complex coding mysteries
Define the filter function that every node must to implement.
Make a summary of the following Python 3 code def filter(self, query: Query, entity: type) -> Tuple[Query, Any]: raise NotImplementedError('You must implement this.')
As a Python code composer, you craft elegant and concise scripts.
Split and return the list of relation ( s ) and the attribute.
Make a summary of the following Python 3 code def _extract_relations(self, attribute: str) -> Tuple[List[str], str]: splitted = attribute.split(self._attr_sep) return (splitted[:-1], splitted[-1])
As a python code expert, you are capable of creating scripts from specifications.
def _get_relation(self, related_model: type, relations: List[str]) -> Tuple[Optional[List[type]], Optional[type]]: """Transform the list of relation to list of class. :param related_mode: The model of the query. :type related_mode: type :param relations: The relation list get from the ...
Write a Python 3 script to transform the list of relation to list of class.
You are a Python code generator, capable of creating scripts from specifications.
Apply the _method to all childs of the node.
Make a summary of the following Python 3 code def filter(self, query: Query, entity: type) -> Tuple[Query, Any]: new_query = query c_filter_list = [] for child in self._childs: new_query, f_list = child.filter(new_query, entity) c_filter_list.append(f_list) return...
You are a Python code analyst, evaluating scripts for potential improvements.
Sends SMS via Kajala Group SMS API. Contact info@kajala. com for access.
Can you generate the documentation for the following Python 3 function def send_sms(phone: str, message: str, sender: str='', **kw): if not hasattr(settings, 'SMS_TOKEN'): raise Exception('Invalid configuration: settings.SMS_TOKEN missing') if not sender: sender = settings.SMS_SENDER_NAME if...
You are a Python code analyst, evaluating scripts for potential improvements.
Just a meta func to get execution time
Make a summary of the following Python 3 code def _meta_get_resource_sync(md_uuid): isogeo.resource(id_resource=md_uuid) elapsed = default_timer() - START_TIME time_completed_at = "{:5.2f}s".format(elapsed) print("{0:<30} {1:>20}".format(md_uuid, time_completed_at)) return
You are a Python code architect, reviewing and designing scalable and efficient code
def process_exception(self, request, e): """ Logs exception error message and sends email to ADMINS if hostname is not testserver and DEBUG=False. :param request: HttpRequest :param e: Exception """ from jutil.email import send_email assert isinstance(request, Ht...
Create a Python 3 function to log exception message and sends email to ADMINS if DEBUG = False.
You are a Python code analyst, evaluating scripts for potential improvements.
Get the first Gtk. Window in a Gtk. Builder hierarchy.
Can you generate a brief explanation for the following Python 3 code def get_first_builder_window(builder): for obj in builder.get_objects(): if isinstance(obj, Gtk.Window): # first window return obj
As a Python code composer, you craft elegant and concise scripts.
def add_slave(self, slave, container_name="widget"): """Add a slave delegate """ cont = getattr(self, container_name, None) if cont is None: raise AttributeError( 'Container name must be a member of the delegate') cont.add(slave.widget) self.sl...
Write a Python 3 script for adding a slave to the container
As a python code expert, you are capable of creating scripts from specifications.
def get_builder_toplevel(self, builder): """Get the toplevel widget from a Gtk.Builder file. The slave view implementation first searches for the widget named as self.toplevel_name (which defaults to "main". If this is missing, the first toplevel widget is discovered in the Builder file...
Write a Python 3 script to get the toplevel widget from a Gtk. Builder file.
As a Python code translator, you convert algorithms and pseudocode into Python.
Show the main widget in a window and run the gtk loop
Make a summary of the following Python 3 code def show_and_run(self): if not self._ui_ready: self.prepare_ui() self.display_widget = Gtk.Window() self.display_widget.add(self.widget) self.display_widget.show() self.display_widget.connect('destroy', lambda *args: self....
You are a Python code generator, capable of creating scripts from specifications.