output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
Populates obj with the values from the all values in section.
Make a summary of the following Python 3 code def populate(self, obj=None, section=None, parse_types=True): section = self.default_section if section is None else section obj = Settings() if obj is None else obj is_dict = isinstance(obj, dict) for k, v in self.get_options(section).items(...
As a Python code analyst, you investigate and solve complex coding mysteries
def _get_calling_module(self): """Get the last module in the call stack that is not this module or ``None`` if the call originated from this module. """ for frame in inspect.stack(): mod = inspect.getmodule(frame[0]) logger.debug(f'calling module: {mod}') ...
How would you implement a function in Python 3 that gets the module that is calling this function.
You are a Python code architect, reviewing and designing scalable and efficient code
def resource_filename(self, resource_name, module_name=None): """Return a resource based on a file name. This uses the ``pkg_resources`` package first to find the resources. If it doesn't find it, it returns a path on the file system. :param: resource_name the file name of the resourc...
Create a Python 3 function for returning a resource based on a file name.
You are a Python code analyst, evaluating scripts for potential improvements.
Load the configuration file.
Make a summary of the following Python 3 code def parser(self): "Load the configuration file." if not hasattr(self, '_conf'): cfile = self.config_file logger.debug('loading config %s' % cfile) if os.path.isfile(cfile): conf = self._create_config_parser...
As a Python code composer, you craft elegant and concise scripts.
Get all options for a section.
Given the following Python 3 function, write the documentation def get_options(self, section='default', opt_keys=None, vars=None): vars = vars if vars else self.default_vars conf = self.parser opts = {} if opt_keys is None: if conf is None: opt_keys = {} ...
You are a Python code analyst, evaluating scripts for potential improvements.
def get_option(self, name, section=None, vars=None, expect=None): """Return an option from ``section`` with ``name``. :param section: section in the ini file to fetch the value; defaults to constructor's ``default_section`` """ vars = vars if vars else self.default_vars ...
Write a Python 3 function for returning an option from section with name.
As a Python code analyst, you investigate and solve complex coding mysteries
Return a list of values from the option named name in section.
Make a summary of the following Python 3 code def get_option_list(self, name, section=None, vars=None, expect=None, separator=','): """Just like ``get_option`` but parse as a list using ``split``. """ val = self.get_option(name, section, vars, expect) return val....
As a Python code translator, you convert algorithms and pseudocode into Python.
def get_option_boolean(self, name, section=None, vars=None, expect=None): """Just like ``get_option`` but parse as a boolean (any case `true`). """ val = self.get_option(name, section, vars, expect) val = val.lower() if val else 'false' return val == 'true'
How would you implement a function in Python 3 that gets option as a boolean.
As a Python code composer, you craft elegant and concise scripts.
Like get_option but return a Path object of the string.
Given the following Python 3 function, write the documentation def get_option_path(self, name, section=None, vars=None, expect=None): val = self.get_option(name, section, vars, expect) return Path(val)
As a python code expert, you are capable of creating scripts from specifications.
Wrapper for property reads which auto - dereferences Refs if required.
Given the following Python 3 function, write the documentation def property_get( prop, instance, **kwargs ): if isinstance( prop, Ref ): return prop.get( instance, **kwargs ) return prop
You are a Python code generator, capable of creating scripts from specifications.
Wrapper for property. set
Can you tell what is the following Python 3 function doing def property_set( prop, instance, value, **kwargs ): if isinstance( prop, Ref ): return prop.set( instance, value, **kwargs ) raise AttributeError( "can't change value of constant {} (context: {})".format( prop, instance ) )
As a Python code translator, you convert algorithms and pseudocode into Python.
def view_property( prop ): """Wrapper for attributes of a View class which auto-dereferences Refs. Equivalent to setting a property on the class with the getter wrapped with property_get(), and the setter wrapped with property_set(). prop A string containing the name of the class attribute...
Can you create a Python 3 function that wraps for attributes of a View class which auto-dereferences Refs. Equivalent to setting a property on the class with the getter wrapped with property_get(), and the setter wrapped with property_set(). prop A string containing the name of the class attribute to wrap.
As a python code expert, you are capable of creating scripts from specifications.
Return an attribute from an object using the Ref path.
Make a summary of the following Python 3 code def get( self, instance, **kwargs ): target = instance for attr in self._path: target = getattr( target, attr ) return target
You are a Python code generator, capable of creating scripts from specifications.
def set( self, instance, value, **kwargs ): """Set an attribute on an object using the Ref path. instance The object instance to traverse. value The value to set. Throws AttributeError if allow_write is False. """ if not self._allow_write: ...
How would you code a function in Python 3 to set an attribute on an object using the Ref path.
As a Python code translator, you convert algorithms and pseudocode into Python.
def traverse_until_fixpoint(predicate, tree): """Traverses the tree again and again until it is not modified.""" old_tree = None tree = simplify(tree) while tree and old_tree != tree: old_tree = tree tree = tree.traverse(predicate) if not tree: return None tre...
How would you code a function in Python 3 to traverse the tree until the tree is not modified.
As a Python code translator, you convert algorithms and pseudocode into Python.
def runner(self): """ Run the necessary methods in the correct order """ logging.info('Starting {} analysis pipeline'.format(self.analysistype)) # Initialise the GenObject for sample in self.runmetadata.samples: setattr(sample, self.analysistype, GenObject()) ...
Write a Python 3 function for running the necessary methods in the correct order for the current runmetadata object
You are a Python code analyst, evaluating scripts for potential improvements.
def fasta(self): """ Create FASTA files of the PointFinder results to be fed into PointFinder """ logging.info('Extracting FASTA sequences matching PointFinder database') for sample in self.runmetadata.samples: # Ensure that there are sequence data to extract from the...
How would you implement a function in Python 3 that creates the FASTA files of the PointFinder results that are fed into PointFinder
As a python code expert, you are capable of creating scripts from specifications.
def run_pointfinder(self): """ Run PointFinder on the FASTA sequences extracted from the raw reads """ logging.info('Running PointFinder on FASTA files') for i in range(len(self.runmetadata.samples)): # Start threads threads = Thread(target=self.pointfinde...
How would you code a function in Python 3 to run PointFinder on the FASTA files extracted from the raw reads and store the results in the output directory.
You are a Python code architect, reviewing and designing scalable and efficient code
def populate_summary_dict(self, genus=str(), key=str()): """ :param genus: Non-supported genus to be added to the dictionary :param key: section of dictionary to be populated. Supported keys are: prediction, table, and results Populate self.summary_dict as required. If the genus is not p...
How would you code a function in Python 3 to populate the summary dictionary for the specified genus.
As a Python code composer, you craft elegant and concise scripts.
Parse the PointFinder output files and create the nested dictionary that stores the necessary values for creating the summary reports for the PointFinder outputs
Can you generate the documentation for the following Python 3 function def parse_pointfinder(self): # Create the nested dictionary that stores the necessary values for creating summary reports self.populate_summary_dict() # Clear out any previous reports for organism in self.summary_dict...
You are a Python code architect, reviewing and designing scalable and efficient code
Parse the PointFinder outputs and write the summary report for the current analysis type and the current result type.
Given the following Python 3 function, write the documentation def write_report(summary_dict, seqid, genus, key): # Set the header string if the summary report doesn't already exist if not os.path.isfile(summary_dict[genus][key]['summary']): header_string = summary_dict[genus][key]['header']...
As a Python code composer, you craft elegant and concise scripts.
def write_table_report(summary_dict, seqid, genus): """ Parse the PointFinder table output, and write a summary report :param summary_dict: nested dictionary containing data such as header strings, and paths to reports :param seqid: name of the strain, :param genus: MASH-calculat...
Can you write a function in Python 3 where it parses the PointFinder table output and write a summary report
As a Python code analyst, you investigate and solve complex coding mysteries
Create the multi - FASTA files of all targets if necessary and populate objects
Can you tell what is the following Python 3 function doing def targets(self): logging.info('Performing analysis with {} targets folder'.format(self.analysistype)) for sample in self.runmetadata: sample[self.analysistype].runanalysis = True sample[self.analysistype].targetpath = (...
As a Python code composer, you craft elegant and concise scripts.
Create a dictionary of SEQID - > OLNID
Given the following Python 3 function, write the documentation def strains(self): with open(os.path.join(self.path, 'strains.csv')) as strains: next(strains) for line in strains: oln, seqid = line.split(',') self.straindict[oln] = seqid.rstrip() ...
You are a Python code architect, reviewing and designing scalable and efficient code
Write the metadata object to the metadata. jsonfile
Can you generate a brief explanation for the following Python 3 code def write_json(metadata): # Open the metadata file to write with open(metadata.jsonfile, 'w') as metadatafile: # Write the json dump of the object dump to the metadata file json.dump(metadata.dump(), metadatafil...
As a Python code composer, you craft elegant and concise scripts.
Read the metadata object from a JSON - formatted metadata object file.
Given the following Python 3 function, write the documentation def read_json(json_metadata): # Load the metadata object from the file with open(json_metadata) as metadatareport: jsondata = json.load(metadatareport) # Create the metadata objects metadata = MetadataObject() ...
As a Python code translator, you convert algorithms and pseudocode into Python.
def assembly_length(self): """ Use SeqIO.parse to extract the total number of bases in each assembly file """ for sample in self.metadata: # Only determine the assembly length if is has not been previously calculated if not GenObject.isattr(sample, 'assembly_lengt...
Implement a Python 3 function for determining the total number of bases in each assembly file in each assembly file and update the assembly_length attribute with the total number of bases in each assembly file in each assembly file.
You are a Python code generator, capable of creating scripts from specifications.
Create the simulated reads file for each sample in the metadata and generate the corresponding forward and reverse lengths for each depth of sequencing.
Can you tell what is the following Python 3 function doing def simulate_reads(self): logging.info('Read simulation') for sample in self.metadata: # Create the simulated_reads GenObject sample.simulated_reads = GenObject() # Iterate through all the desired depths of co...
You are a Python code architect, reviewing and designing scalable and efficient code
This method will trim the reads to the correct length using reformat. sh
Can you tell what is the following Python 3 function doing def read_length_adjust(self, analysistype): logging.info('Trimming {at} reads'.format(at=analysistype)) for sample in self.metadata: # Iterate through all the desired depths of coverage for depth in self.read_depths: ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Perform quality trim and toss reads below appropriate thresholds
Can you tell what is the following Python 3 function doing def read_quality_trim(self): logging.info('Quality trim') for sample in self.metadata: sample.sampled_reads = GenObject() sample.sampled_reads.outputdir = os.path.join(sample.outputdir, 'sampled') sample.sampl...
As a python code expert, you are capable of creating scripts from specifications.
def sample_reads(self): """ For each PacBio assembly, sample reads from corresponding FASTQ files for appropriate forward and reverse lengths and sequencing depths using reformat.sh from the bbtools suite """ logging.info('Read sampling') for sample in self.metadata: ...
How would you code a function in Python 3 to sample reads from corresponding FASTQ files for appropriate forward and reverse lengths and sequencing depths.
As a Python code analyst, you investigate and solve complex coding mysteries
Create the necessary directories to link the reads to the output directories
Can you generate a brief explanation for the following Python 3 code def link_reads(self, analysistype): logging.info('Linking {at} reads'.format(at=analysistype)) for sample in self.metadata: # Create the output directories genesippr_dir = os.path.join(self.path, 'genesippr', sa...
You are a Python code generator, capable of creating scripts from specifications.
def run_genesippr(self): """ Run GeneSippr on each of the samples """ from pathlib import Path home = str(Path.home()) logging.info('GeneSippr') # These unfortunate hard coded paths appear to be necessary miniconda_path = os.path.join(home, 'miniconda3') ...
Can you write a function in Python 3 where it runs GeneSippr on each of the samples in the current directory.
You are a Python code analyst, evaluating scripts for potential improvements.
def set_level(self, level): """ Set the logging level of this logger. :param level: must be an int or a str. """ for handler in self.__coloredlogs_handlers: handler.setLevel(level=level) self.logger.setLevel(level=level)
Write a Python 3 function for setting the logging level of this logger.
You are a Python code architect, reviewing and designing scalable and efficient code
def disable_logger(self, disabled=True): """ Disable all logging calls. """ # Disable standard IO streams if disabled: sys.stdout = _original_stdout sys.stderr = _original_stderr else: sys.stdout = self.__stdout_stream sys.s...
How would you implement a function in Python 3 that disables all logging calls.
You are a Python code architect, reviewing and designing scalable and efficient code
Redirect sys. stdout to file - like object.
Explain what the following Python 3 code does def redirect_stdout(self, enabled=True, log_level=logging.INFO): if enabled: if self.__stdout_wrapper: self.__stdout_wrapper.update_log_level(log_level=log_level) else: self.__stdout_wrapper = StdOutWrapper(log...
As a python code expert, you are capable of creating scripts from specifications.
Redirect sys. stderr to file - like object.
Can you tell what is the following Python 3 function doing def redirect_stderr(self, enabled=True, log_level=logging.ERROR): if enabled: if self.__stderr_wrapper: self.__stderr_wrapper.update_log_level(log_level=log_level) else: self.__stderr_wrapper = Std...
You are a Python code analyst, evaluating scripts for potential improvements.
Set the logging level and time for a file.
Can you generate the documentation for the following Python 3 function def use_file(self, enabled=True, file_name=None, level=logging.WARNING, when='d', interval=1, backup_count=30, delay=False, utc=Fa...
As a Python code translator, you convert algorithms and pseudocode into Python.
def use_loggly(self, enabled=True, loggly_token=None, loggly_tag=None, level=logging.WARNING, log_format=None, date_format=None): """ Enable handler for sending the record to Loggly service. """ ...
Create a Python 3 function for enabling handler for sending the record to Loggly service.
You are a Python code analyst, evaluating scripts for potential improvements.
Find the caller name so that we can note the source file name line number and function name.
Can you generate the documentation for the following Python 3 function def __find_caller(stack_info=False): frame = logging.currentframe() # On some versions of IronPython, currentframe() returns None if # IronPython isn't run with -X:Frames. if frame: frame = frame.f_back ...
You are a Python code analyst, evaluating scripts for potential improvements.
def _log(self, level, msg, *args, **kwargs): """ Log 'msg % args' with the integer severity 'level'. To pass exception information, use the keyword argument exc_info with a true value, e.g. logger.log(level, "We have a %s", "mysterious problem", exc_info=1) """ ...
Can you create a Python 3 function that logs a message at the specified severity level.
As a Python code analyst, you investigate and solve complex coding mysteries
def flush(self): """ Flush the buffer, if applicable. """ if self.__buffer.tell() > 0: # Write the buffer to log # noinspection PyProtectedMember self.__logger._log(level=self.__log_level, msg=self.__buffer.getvalue().strip(), ...
Write a Python 3 script for flushing the buffer to the log if applicable.
As a Python code composer, you craft elegant and concise scripts.
def syllabify(word): '''Syllabify the given word, whether simplex or complex.''' compound = bool(re.search(r'(-| |=)', word)) syllabify = _syllabify_compound if compound else _syllabify syllabifications = list(syllabify(word)) for syll, rules in syllabifications: yield syll, rules n = ...
Create a Python 3 function for syllabifying the given word whether simplex or complex.
As a Python code composer, you craft elegant and concise scripts.
A generator function that applies T4 to a word.
Can you generate a brief explanation for the following Python 3 code def apply_T4(word): '''An agglutination diphthong that ends in /u, y/ optionally contains a syllable boundary when -C# or -CCV follow, e.g., [lau.ka.us], [va.ka.ut.taa].''' WORD = word.split('.') PARTS = [[] for part in range(len(W...
You are a Python code analyst, evaluating scripts for potential improvements.
def format(self, record): """Uses contextstring if request_id is set, otherwise default.""" # NOTE(sdague): default the fancier formating params # to an empty string so we don't throw an exception if # they get used for key in ('instance', 'color'): if key not in reco...
Write a Python 3 function that can use contextstring if request_id is set otherwise default.
You are a Python code architect, reviewing and designing scalable and efficient code
def formatException(self, exc_info, record=None): """Format exception output with CONF.logging_exception_prefix.""" if not record: return logging.Formatter.formatException(self, exc_info) stringbuffer = cStringIO.StringIO() traceback.print_exception(exc_info[0], exc_info[1],...
Write a Python 3 function that can format exception output with CONF. logging_exception_prefix.
As a python code expert, you are capable of creating scripts from specifications.
Display buttons given by the list of tuples id function description is_active
Can you generate a brief explanation for the following Python 3 code def _set_boutons_interface(self, buttons): for id_action, f, d, is_active in buttons: icon = self.get_icon(id_action) action = self.addAction(QIcon(icon), d) action.setEnabled(is_active) action.t...
You are a Python code analyst, evaluating scripts for potential improvements.
def set_interface(self, interface): """Add update toolbar callback to the interface""" self.interface = interface self.interface.callbacks.update_toolbar = self._update self._update()
Write a Python 3 script to add update toolbar callback to the interface
You are a Python code analyst, evaluating scripts for potential improvements.
def _update(self): """Update the display of button after querying data from interface""" self.clear() self._set_boutons_communs() if self.interface: self.addSeparator() l_actions = self.interface.get_actions_toolbar() self._set_boutons_interface(l_acti...
How would you implement a function in Python 3 that updates the display of button after querying data from interface
You are a Python code analyst, evaluating scripts for potential improvements.
Display login screen. May ask for local data loading if from_local is True.
Given the following Python 3 function, write the documentation def init_login(self, from_local=False): if self.toolbar: self.removeToolBar(self.toolbar) widget_login = login.Loading(self.statusBar(), self.theory_main) self.centralWidget().addWidget(widget_login) widget_login....
As a Python code composer, you craft elegant and concise scripts.
Shortcut for making a response to the client s request.
Can you tell what is the following Python 3 function doing def make_response(self, status, content_type, response): headers = [('Access-Control-Allow-Origin', '*'), ('Access-Control-Allow-Methods', 'GET, POST, OPTIONS'), ('Access-Control-Allow-Headers', 'Content-Type'), ...
You are a Python code generator, capable of creating scripts from specifications.
def on_post(self): """Extracts the request, feeds the module, and returns the response.""" request = self.environ['wsgi.input'] try: return self.process_request(request) except ClientError as exc: return self.on_client_error(exc) except BadGateway as exc: ...
Create a Python 3 function to extract the request feeds the module and returns the response.
You are a Python code analyst, evaluating scripts for potential improvements.
Handles dispatching of the request.
Make a summary of the following Python 3 code def dispatch(self): method_name = 'on_' + self.environ['REQUEST_METHOD'].lower() method = getattr(self, method_name, None) if method: return method() else: return self.on_bad_method()
You are a Python code analyst, evaluating scripts for potential improvements.
Clone data from another Block instance to copy from.
Given the following Python 3 function, write the documentation def clone_data( self, source ): klass = self.__class__ assert isinstance( source, klass ) for name in klass._fields: self._field_data[name] = getattr( source, name )
You are a Python code generator, capable of creating scripts from specifications.
Import data from a byte array.
Can you generate a brief explanation for the following Python 3 code def import_data( self, raw_buffer ): klass = self.__class__ if raw_buffer: assert common.is_bytes( raw_buffer ) # raw_buffer = memoryview( raw_buffer ) self._field_data = {} for name in klass._f...
As a python code expert, you are capable of creating scripts from specifications.
Export data to a byte array.
Make a summary of the following Python 3 code def export_data( self ): klass = self.__class__ output = bytearray( b'\x00'*self.get_size() ) # prevalidate all data before export. # this is important to ensure that any dependent fields # are updated beforehand, e.g. a count refer...
You are a Python code architect, reviewing and designing scalable and efficient code
def update_deps( self ): """Update dependencies on all the fields on this Block instance.""" klass = self.__class__ for name in klass._fields: self.update_deps_on_field( name ) return
Can you write a function in Python 3 where it updates dependencies on all the fields on this Block instance.
You are a Python code analyst, evaluating scripts for potential improvements.
def validate( self ): """Validate all the fields on this Block instance.""" klass = self.__class__ for name in klass._fields: self.validate_field( name ) return
How would you code a function in Python 3 to validate all the fields on this Block instance.
You are a Python code analyst, evaluating scripts for potential improvements.
def get_size( self ): """Get the projected size (in bytes) of the exported data from this Block instance.""" klass = self.__class__ size = 0 for name in klass._fields: size = max( size, klass._fields[name].get_end_offset( self._field_data[name], parent=self ) ) for ch...
Implement a function in Python 3 to get the projected size of the exported data from this Block instance.
You are a Python code architect, reviewing and designing scalable and efficient code
Save the GADDAG to a file.
How would you explain what the following Python 3 function does def save(self, path, compressed=True, exist_ok=False): path = os.path.expandvars(os.path.expanduser(path)) if os.path.isfile(path) and not exist_ok: raise OSError(17, os.strerror(17), path) if os.path.isdir(path): ...
As a python code expert, you are capable of creating scripts from specifications.
def load(self, path): """ Load a GADDAG from file, replacing the words currently in this GADDAG. Args: path: path to saved GADDAG to be loaded. """ path = os.path.expandvars(os.path.expanduser(path)) gdg = cgaddag.gdg_load(path.encode("ascii")) if no...
Can you implement a function in Python 3 that loads a GADDAG from file and replace the words currently in this GADDAG with the words currently in the GADDAG.
As a python code expert, you are capable of creating scripts from specifications.
def starts_with(self, prefix): """ Find all words starting with a prefix. Args: prefix: A prefix to be searched for. Returns: A list of all words found. """ prefix = prefix.lower() found_words = [] res = cgaddag.gdg_starts_with(s...
Create a Python 3 function to find all words starting with a prefix.
You are a Python code analyst, evaluating scripts for potential improvements.
Find all words containing a substring.
Given the following Python 3 function, write the documentation def contains(self, sub): sub = sub.lower() found_words = set() res = cgaddag.gdg_contains(self.gdg, sub.encode(encoding="ascii")) tmp = res while tmp: word = tmp.contents.str.decode("ascii") ...
You are a Python code architect, reviewing and designing scalable and efficient code
Find all words ending with a suffix.
Can you generate a brief explanation for the following Python 3 code def ends_with(self, suffix): suffix = suffix.lower() found_words = [] res = cgaddag.gdg_ends_with(self.gdg, suffix.encode(encoding="ascii")) tmp = res while tmp: word = tmp.contents.str.decode("asc...
As a Python code analyst, you investigate and solve complex coding mysteries
def add_word(self, word): """ Add a word to the GADDAG. Args: word: A word to be added to the GADDAG. """ word = word.lower() if not (word.isascii() and word.isalpha()): raise ValueError("Invalid character in word '{}'".format(word)) wor...
Implement a function in Python 3 to add a word to the GADDAG.
As a python code expert, you are capable of creating scripts from specifications.
Format a log message.
Given the following Python 3 function, write the documentation def formatLog(source="", level="", title="", data={}): # consistently output empty string for unset params, because null values differ by language source = "" if source is None else source level = "" if level is None else level title = "" if title i...
You are a Python code generator, capable of creating scripts from specifications.
Updates this task type on the saltant server.
Here you have a function in Python 3, explain what it does def put(self): return self.manager.put( id=self.id, name=self.name, description=self.description, command_to_run=self.command_to_run, environment_variables=self.environment_variables, ...
As a Python code analyst, you investigate and solve complex coding mysteries
Creates a new container task type.
Explain what the following Python 3 code does def create( self, name, command_to_run, container_image, container_type, description="", logs_path="", results_path="", environment_variables=None, required_arguments=None, required_argu...
As a Python code analyst, you investigate and solve complex coding mysteries
Updates a task type on the saltant server.
Can you generate a brief explanation for the following Python 3 code def put( self, id, name, description, command_to_run, environment_variables, required_arguments, required_arguments_default_values, logs_path, results_path, contai...
You are a Python code analyst, evaluating scripts for potential improvements.
Convert a string representation of truth to true or false ( 0.
Can you tell what is the following Python 3 function doing def _strtobool(val): val = val.lower() if val in ('y', 'yes', 't', 'true', 'on', '1'): return 1 elif val in ('n', 'no', 'f', 'false', 'off', '0', ''): return 0 else: raise ValueError('Invalid truth value: {0}'.format(val)...
As a Python code translator, you convert algorithms and pseudocode into Python.
Convert a string to a list with sanitization.
Explain what the following Python 3 code does def _str_to_list(value, separator): value_list = [item.strip() for item in value.split(separator)] value_list_sanitized = builtins.list(filter(None, value_list)) if len(value_list_sanitized) > 0: return value_list_sanitized else: raise ValueE...
You are a Python code analyst, evaluating scripts for potential improvements.
def write(name, value): """Write a raw env value. A ``None`` value clears the environment variable. Args: name: The environment variable name value: The value to write """ if value is not None: environ[name] = builtins.str(value) elif environ.get(name): del envi...
Can you implement a function in Python 3 that writes a raw env value. A None value clears the environment variable.
As a Python code analyst, you investigate and solve complex coding mysteries
Reads the raw env value.
Given the following Python 3 function, write the documentation def read(name, default=None, allow_none=False, fallback=None): raw_value = environ.get(name) if raw_value is None and fallback is not None: if not isinstance(fallback, builtins.list) and not isinstance(fallback, builtins.tuple): ...
As a Python code analyst, you investigate and solve complex coding mysteries
def str(name, default=None, allow_none=False, fallback=None): """Get a string based environment value or the default. Args: name: The environment variable name default: The default value to use if no environment variable is found allow_none: If the return value can be `None` (i.e. optio...
Can you create a Python 3 function that gets a string based environment variable value or the default.
You are a Python code analyst, evaluating scripts for potential improvements.
Get a boolean based environment variable value or the default.
Can you tell what is the following Python 3 function doing def bool(name, default=None, allow_none=False, fallback=None): value = read(name, default, allow_none, fallback=fallback) if isinstance(value, builtins.bool): return value elif isinstance(value, builtins.int): return True if value > ...
You are a Python code generator, capable of creating scripts from specifications.
def int(name, default=None, allow_none=False, fallback=None): """Get a string environment value or the default. Args: name: The environment variable name default: The default value to use if no environment variable is found allow_none: If the return value can be `None` (i.e. optional) ...
Implement a Python 3 function for getting a string environment variable value or the default.
As a Python code translator, you convert algorithms and pseudocode into Python.
def list(name, default=None, allow_none=False, fallback=None, separator=','): """Get a list of strings or the default. The individual list elements are whitespace-stripped. Args: name: The environment variable name default: The default value to use if no environment variable is found ...
Write a Python 3 function for getting a list of strings or the default.
You are a Python code architect, reviewing and designing scalable and efficient code
this function adds some configuration for the application
Can you tell what is the following Python 3 function doing def includeme(config): config.add_route('references', '/references') _add_referencer(config.registry) config.add_view_deriver(protected_resources.protected_view) config.add_renderer('json_item', json_renderer) config.scan()
You are a Python code architect, reviewing and designing scalable and efficient code
def _add_referencer(registry): """ Gets the Referencer from config and adds it to the registry. """ referencer = registry.queryUtility(IReferencer) if referencer is not None: return referencer ref = registry.settings['urireferencer.referencer'] url = registry.settings['urireferencer....
Write a Python 3 function for adding the Referencer to the registry.
You are a Python code architect, reviewing and designing scalable and efficient code
Get the referencer class
Can you generate the documentation for the following Python 3 function def get_referencer(registry): # Argument might be a config or request regis = getattr(registry, 'registry', None) if regis is None: regis = registry return regis.queryUtility(IReferencer)
As a python code expert, you are capable of creating scripts from specifications.
def _connect_to_ec2(region, credentials): """ :param region: The region of AWS to connect to. :param EC2Credentials credentials: The credentials to use to authenticate with EC2. :return: a connection object to AWS EC2 """ conn = boto.ec2.connect_to_region( region, aws_ac...
Write a Python 3 script for connecting to AWS EC2
You are a Python code generator, capable of creating scripts from specifications.
def write(self, *args, **kwargs): """ :param args: tuple(value, style), tuple(value, style) :param kwargs: header=tuple(value, style), header=tuple(value, style) :param args: value, value :param kwargs: header=value, header=value """ if args: kwargs =...
Create a Python 3 function for writing the contents of the record to the table.
You are a Python code analyst, evaluating scripts for potential improvements.
Clear the layout off all its components
Can you generate a brief explanation for the following Python 3 code def clear_layout(layout: QLayout) -> None: if layout is not None: while layout.count(): item = layout.takeAt(0) widget = item.widget() if widget is not None: widget.deleteLater() ...
You are a Python code architect, reviewing and designing scalable and efficient code
Loads the Hangul syllable types from the Unicode Character Database.
How would you explain what the following Python 3 function does def _load_hangul_syllable_types(): filename = "HangulSyllableType.txt" current_dir = os.path.abspath(os.path.dirname(__file__)) with codecs.open(os.path.join(current_dir, filename), mode="r", encoding="utf-8") as fp: for line in fp: ...
As a Python code analyst, you investigate and solve complex coding mysteries
def _load_jamo_short_names(): """ Function for parsing the Jamo short names from the Unicode Character Database (UCD) and generating a lookup table For more info on how this is used, see the Unicode Standard, ch. 03, section 3.12, "Conjoining Jamo Behavior" and ch. 04, section 4.8, "Name". https://...
Can you create a Python 3 function that functions for parsing the Jamo short names from the Unicode Character Database and generating a lookup table
As a Python code analyst, you investigate and solve complex coding mysteries
Function for taking a Unicode scalar value representing a Hangul syllable and determining the correct value for its Hangul_Syllable_Type property.
How would you explain what the following Python 3 function does def _get_hangul_syllable_type(hangul_syllable): if not _is_hangul_syllable(hangul_syllable): raise ValueError("Value 0x%0.4x does not represent a Hangul syllable!" % hangul_syllable) if not _hangul_syllable_types: _load_hangul_sylla...
As a python code expert, you are capable of creating scripts from specifications.
def _get_jamo_short_name(jamo): """ Function for taking a Unicode scalar value representing a Jamo and determining the correct value for its Jamo_Short_Name property. For more information on the Jamo_Short_Name property see the Unicode Standard, ch. 03, section 3.12, Conjoining Jamo Behavior. http...
How would you code a function in Python 3 to function for taking a Unicode scalar value representing a Jamo and determining the correct value for its Jamo_Short_Name property.
As a Python code analyst, you investigate and solve complex coding mysteries
Function for taking a tuple or list of Unicode scalar values representing Jamo and composing it into a Hangul syllable.
Can you generate a brief explanation for the following Python 3 code def compose_hangul_syllable(jamo): fmt_str_invalid_sequence = "{0} does not represent a valid sequence of Jamo!" if len(jamo) == 3: l_part, v_part, t_part = jamo if not (l_part in range(0x1100, 0x1112 + 1) and v...
You are a Python code analyst, evaluating scripts for potential improvements.
def decompose_hangul_syllable(hangul_syllable, fully_decompose=False): """ Function for taking a Unicode scalar value representing a Hangul syllable and decomposing it into a tuple representing the scalar values of the decomposed (canonical decomposition) Jamo. If the Unicode scalar value passed in is ...
Implement a function in Python 3 to function for decomposing a Unicode scalar value representing a Hangul syllable into a tuple of Unicode scalar values l_part v_part t_part.
As a Python code analyst, you investigate and solve complex coding mysteries
def _get_hangul_syllable_name(hangul_syllable): """ Function for taking a Unicode scalar value representing a Hangul syllable and converting it to its syllable name as defined by the Unicode naming rule NR1. See the Unicode Standard, ch. 04, section 4.8, Names, for more information. :param hangul_syll...
Create a Python 3 function for functioning for converting a Unicode scalar value representing a Hangul syllable to its syllable name as transformed according to the Unicode naming rule NR1.
As a Python code analyst, you investigate and solve complex coding mysteries
Generate a dict mapping method names to anonymous functions that will call the server s endpoint of the corresponding name.
How would you explain what the following Python 3 function does def generate_client_callers(spec, timeout, error_callback, local, app): callers_dict = {} def mycallback(endpoint): if not endpoint.handler_client: return callers_dict[endpoint.handler_client] = _generate_client_calle...
As a Python code composer, you craft elegant and concise scripts.
def _call_retry(self, force_retry): """Call request and retry up to max_attempts times (or none if self.max_attempts=1)""" last_exception = None for i in range(self.max_attempts): try: log.info("Calling %s %s" % (self.method, self.url)) response = self...
Write a Python 3 function that can call the requests_method method and retry up to max_attempts times.
You are a Python code analyst, evaluating scripts for potential improvements.
Syllabify the given word whether simplex or complex.
Explain what the following Python 3 code does def syllabify(word): '''Syllabify the given word, whether simplex or complex.''' word = split(word) # detect any non-delimited compounds compound = True if re.search(r'-| |\.', word) else False syllabify = _syllabify_compound if compound else _syllabify ...
As a Python code analyst, you investigate and solve complex coding mysteries
Syllabify the given word.
Can you tell what is the following Python 3 function doing def _syllabify(word, T4=True): '''Syllabify the given word.''' word = replace_umlauts(word) word, rules = apply_T1(word) if re.search(r'[^ieAyOauo]*([ieAyOauo]{2})[^ieAyOauo]*', word): word, T2 = apply_T2(word) word, T8 = apply_...
As a python code expert, you are capable of creating scripts from specifications.
This function applies T1 to every CV - sequence.
Here you have a function in Python 3, explain what it does def apply_T1(word): '''There is a syllable boundary in front of every CV-sequence.''' # split consonants and vowels: 'balloon' -> ['b', 'a', 'll', 'oo', 'n'] WORD = [w for w in re.split('([ieAyOauo]+)', word) if w] count = 0 for i, v in enu...
As a python code expert, you are capable of creating scripts from specifications.
def extended_cigar(aligned_template, aligned_query): ''' Convert mutation annotations to extended cigar format https://github.com/lh3/minimap2#the-cs-optional-tag USAGE: >>> template = 'CGATCGATAAATAGAGTAG---GAATAGCA' >>> query = 'CGATCG---AATAGAGTAGGTCGAATtGCA' >>> extended_cigar(tem...
Write a Python 3 script for converting the alignment of the given template and the given query into an extended cigar.
You are a Python code generator, capable of creating scripts from specifications.
Generates a query sequence from the template and extended cigar annotation.
Can you tell what is the following Python 3 function doing def cigar2query(template, cigar): ''' Generate query sequence from the template and extended cigar annotation USAGE: >>> template = 'CGATCGATAAATAGAGTAGGAATAGCA' >>> cigar = ':6-ata:10+gtc:4*at:3' >>> cigar2query(template, cigar) == ...
As a Python code composer, you craft elegant and concise scripts.
def Blaster(inputfile, databases, db_path, out_path='.', min_cov=0.6, threshold=0.9, blast='blastn', cut_off=True): ''' BLAST wrapper method, that takes a simple input and produces a overview list of the hits to templates, and their alignments Usage >>> import os, subprocess, collections ...
Can you create a Python 3 function that blasts wrapper method that takes a simple input and produces a overview list of the hits to templates and their alignments.
You are a Python code architect, reviewing and designing scalable and efficient code
Function for comparing hits and saving only the best hit
Here you have a function in Python 3, explain what it does def compare_results(save, best_hsp, tmp_results, tmp_gene_split): ''' Function for comparing hits and saving only the best hit ''' # Get data for comparison hit_id = best_hsp['hit_id'] new_start_query = best_hsp['query_start'] new_end_query = bes...
As a Python code translator, you convert algorithms and pseudocode into Python.
def calculate_new_length(gene_split, gene_results, hit): ''' Function for calcualting new length if the gene is split on several contigs ''' # Looping over splitted hits and calculate new length first = 1 for split in gene_split[hit['sbjct_header']]: new_start = int(gene_results[split]['sbjct_st...
Implement a function in Python 3 to function for calcualting new length if the gene is split on several contigs
As a Python code composer, you craft elegant and concise scripts.