text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clear_layout(layout: QLayout) -> None: """Clear the layout off all its components"""
if layout is not None: while layout.count(): item = layout.takeAt(0) widget = item.widget() if widget is not None: widget.deleteLater() else: clear_layout(item.layout())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_hangul_syllable_type(hangul_syllable): """ Function for taking a Unicode scalar value representing a Hangul syllable and determining the correct value f...
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_syllable_types() return _hangul_syllable_types[hangul_syllable]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 prop...
if not _is_jamo(jamo): raise ValueError("Value 0x%0.4x passed in does not represent a Jamo!" % jamo) if not _jamo_short_names: _load_jamo_short_names() return _jamo_short_names[jamo]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def compose_hangul_syllable(jamo): """ Function for taking a tuple or list of Unicode scalar values representing Jamo and composing it into a Hangul syllable. If...
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_part in range(0x1161, 0x1175 + 1) and t_part in range(0x11a8, 0x11c2 + 1)): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_hangul_syllable_name(hangul_syllable): """ Function for taking a Unicode scalar value representing a Hangul syllable and converting it to its syllable n...
if not _is_hangul_syllable(hangul_syllable): raise ValueError("Value passed in does not represent a Hangul syllable!") jamo = decompose_hangul_syllable(hangul_syllable, fully_decompose=True) result = '' for j in jamo: if j is not None: result += _get_jamo_short_name(j) r...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generate_client_callers(spec, timeout, error_callback, local, app): """Return a dict mapping method names to anonymous functions that will call the server's ...
callers_dict = {} def mycallback(endpoint): if not endpoint.handler_client: return callers_dict[endpoint.handler_client] = _generate_client_caller(spec, endpoint, timeout, error_callback, local, app) spec.call_on_each_endpoint(mycallback) return callers_dict
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def stream_to_packet(data): """ Chop a stream of data into MODBUS packets. :param data: stream of data :returns: a tuple of the data that is a packet with the re...
if len(data) < 6: return None # unpack the length pktlen = struct.unpack(">H", data[4:6])[0] + 6 if (len(data) < pktlen): return None return (data[:pktlen], data[pktlen:])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_primitive(value, convert_instances=False, convert_datetime=True, level=0, max_depth=3): """Convert a complex object into primitives. Handy for JSON serial...
# handle obvious types first - order of basic types determined by running # full tests on nova project, resulting in the following counts: # 572754 <type 'NoneType'> # 460353 <type 'int'> # 379632 <type 'unicode'> # 274610 <type 'str'> # 199918 <type 'dict'> # 114200 <type 'datetime.dat...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def stress(syllabified_simplex_word): '''Assign primary and secondary stress to 'syllabified_simplex_word'.''' syllables = syllabified_simplex_word.split('.') stressed = '\'' + syllables[0] # primary stress try: n = 0 medial = syllables[1:-1] for i, syll in enumerate(medial): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def confindr_reporter(self, analysistype='confindr'): """ Creates a final report of all the ConFindr results """
# Initialise the data strings data = 'Strain,Genus,NumContamSNVs,ContamStatus,PercentContam,PercentContamSTD\n' with open(os.path.join(self.reportpath, analysistype + '.csv'), 'w') as report: # Iterate through all the results for sample in self.runmetadata.samples: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def methodreporter(self): """ Create final reports collating results from all the individual iterations through the method pipeline """
# Ensure that the analyses are set to complete self.analysescomplete = True # Reset the report path to original value self.reportpath = os.path.join(self.path, 'reports') # Clear the runmetadata - it will be populated with all the metadata from completemetadata self.runm...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def main(self): """ Run the methods required to create the genesippr report summary image """
self.dataframe_setup() self.figure_populate(self.outputfolder, self.image_report, self.header_list, self.samples, 'genesippr', 'report', ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dir_exists(location, use_sudo=False): """Tells if there is a remote directory at the given location."""
with settings(hide('running', 'stdout', 'stderr'), warn_only=True): if use_sudo: # convert return code 0 to True return not bool(sudo('test -d %s' % (location)).return_code) else: return not bool(run('test -d %s' % (location)).return_code)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def disable_requiretty_on_sudoers(log=False): """ allow sudo calls through ssh without a tty """
if log: bookshelf2.logging_helpers.log_green( 'disabling requiretty on sudo calls') comment_line('/etc/sudoers', '^Defaults.*requiretty', use_sudo=True) return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def linux_distribution(): """ returns the linux distribution in lower case """
with settings(hide('warnings', 'running', 'stdout', 'stderr'), warn_only=True, capture=True): data = os_release() return(data['ID'])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def systemd(service, start=True, enabled=True, unmask=False, restart=False): """ manipulates systemd services """
with settings(hide('warnings', 'running', 'stdout', 'stderr'), warn_only=True, capture=True): if restart: sudo('systemctl restart %s' % service) else: if start: sudo('systemctl start %s' % service) else: sudo('s...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def install_os_updates(distribution, force=False): """ installs OS updates """
if ('centos' in distribution or 'rhel' in distribution or 'redhat' in distribution): bookshelf2.logging_helpers.log_green('installing OS updates') sudo("yum -y --quiet clean all") sudo("yum group mark convert") sudo("yum -y --quiet update") if ('ubuntu' ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def put(self): """Updates this task whitelist on the saltant server. Returns: :class:`saltant.models.task_whitelist.TaskWhitelist`: A task whitelist model instan...
return self.manager.put( id=self.id, name=self.name, description=self.description, whitelisted_container_task_types=( self.whitelisted_container_task_types ), whitelisted_executable_task_types=( self.whiteli...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create( self, name, description="", whitelisted_container_task_types=None, whitelisted_executable_task_types=None, ): """Create a task whitelist. Args: name ...
# Translate whitelists None to [] if necessary if whitelisted_container_task_types is None: whitelisted_container_task_types = [] if whitelisted_executable_task_types is None: whitelisted_executable_task_types = [] # Create the object request_url = self...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def patch( self, id, name=None, description=None, whitelisted_container_task_types=None, whitelisted_executable_task_types=None, ): """Partially updates a task w...
# Update the object request_url = self._client.base_api_url + self.detail_url.format(id=id) data_to_patch = {} if name is not None: data_to_patch["name"] = name if description is not None: data_to_patch["description"] = description if whitelis...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def enable_logging( level='WARNING' ): """Enable sending logs to stderr. Useful for shell sessions. level Logging threshold, as defined in the logging module of ...
log = logging.getLogger( 'mrcrowbar' ) log.setLevel( level ) out = logging.StreamHandler() out.setLevel( level ) form = logging.Formatter( '[%(levelname)s] %(name)s - %(message)s' ) out.setFormatter( form ) log.addHandler( out )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find_all_iter( source, substring, start=None, end=None, overlap=False ): """Iterate through every location a substring can be found in a source string. sourc...
data = source base = 0 if end is not None: data = data[:end] if start is not None: data = data[start:] base = start pointer = 0 increment = 1 if overlap else (len( substring ) or 1) while True: pointer = data.find( substring, pointer ) if pointer == -...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find_all( source, substring, start=None, end=None, overlap=False ): """Return every location a substring can be found in a source string. source The source s...
return [x for x in find_all_iter( source, substring, start, end, overlap )]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pixdump_iter( source, start=None, end=None, length=None, width=64, height=None, palette=None ): """Return the contents of a byte string as a 256 colour image...
assert is_bytes( source ) if not palette: palette = colour.TEST_PALETTE start = 0 if (start is None) else start if (end is not None) and (length is not None): raise ValueError( 'Can\'t define both an end and a length!' ) elif (length is not None): end = start+length el...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pixdump( source, start=None, end=None, length=None, width=64, height=None, palette=None ): """Print the contents of a byte string as a 256 colour image. sour...
for line in pixdump_iter( source, start, end, length, width, height, palette ): print( line )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def put_bits( self, value, count ): """Push bits into the target. value Integer containing bits to push, ordered from least-significant bit to most-significant b...
for _ in range( count ): # bits are retrieved from the source LSB first bit = (value & 1) value >>= 1 # however, bits are put into the result based on the rule if self.bits_reverse: if self.insert_at_msb: self.cur...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_buffer( self ): """Return a byte string containing the target as currently written."""
last_byte = self.current_bits if (self.bits_remaining < 8) else None result = self.output if last_byte is not None: result = bytearray( result ) result.append( last_byte ) if self.bytes_reverse: return bytes( reversed( result ) ) else: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convert_case(name): """Converts name from CamelCase to snake_case"""
s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name) return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def table_name(self): """Pluralises the class_name using utterly simple algo and returns as table_name"""
if not self.class_name: raise ValueError else: tbl_name = ModelCompiler.convert_case(self.class_name) last_letter = tbl_name[-1] if last_letter in ("y",): return "{}ies".format(tbl_name[:-1]) elif last_letter in ("s",): return "{}e...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def types(self): """All the unique types found in user supplied model"""
res = [] for column in self.column_definitions: tmp = column.get('type', None) res.append(ModelCompiler.get_column_type(tmp)) if tmp else False res = list(set(res)) return res
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def basic_types(self): """Returns non-postgres types referenced in user supplied model """
if not self.foreign_key_definitions: return self.standard_types else: tmp = self.standard_types tmp.append('ForeignKey') return tmp
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def primary_keys(self): """Returns the primary keys referenced in user supplied model"""
res = [] for column in self.column_definitions: if 'primary_key' in column.keys(): tmp = column.get('primary_key', None) res.append(column['name']) if tmp else False return res
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def compiled_columns(self): """Returns compiled column definitions"""
def get_column_args(column): tmp = [] for arg_name, arg_val in column.items(): if arg_name not in ('name', 'type'): if arg_name in ('server_default', 'server_onupdate'): arg_val = '"{}"'.format(arg_val) tmp...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def compiled_foreign_keys(self): """Returns compiled foreign key definitions"""
def get_column_args(column): tmp = [] for arg_name, arg_val in column.items(): if arg_name not in ('name', 'type', 'reference'): if arg_name in ('server_default', 'server_onupdate'): arg_val = '"{}"'.format(arg_val) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def compiled_relationships(self): """Returns compiled relationship definitions"""
def get_column_args(column): tmp = [] for arg_name, arg_val in column.items(): if arg_name not in ('name', 'type', 'reference', 'class'): if arg_name in ('back_populates', ): arg_val = "'{}'".format(arg_val) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def compiled_init_func(self): """Returns compiled init function"""
def get_column_assignment(column_name): return ALCHEMY_TEMPLATES.col_assignment.safe_substitute(col_name=column_name) def get_compiled_args(arg_name): return ALCHEMY_TEMPLATES.func_arg.safe_substitute(arg_name=arg_name) join_string = "\n" + self.tab + self.tab ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def compiled_update_func(self): """Returns compiled update function"""
def get_not_none_col_assignment(column_name): return ALCHEMY_TEMPLATES.not_none_col_assignment.safe_substitute(col_name=column_name) def get_compiled_args(arg_name): return ALCHEMY_TEMPLATES.func_arg.safe_substitute(arg_name=arg_name) join_string = "\n" + self.tab + s...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def compiled_hash_func(self): """Returns compiled hash function based on hash of stringified primary_keys. This isn't the most efficient way"""
def get_primary_key_str(pkey_name): return "str(self.{})".format(pkey_name) hash_str = "+ ".join([get_primary_key_str(n) for n in self.primary_keys]) return ALCHEMY_TEMPLATES.hash_function.safe_substitute(concated_primary_key_strs=hash_str)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def compiled_model(self): """Returns compile ORM class for the user supplied model"""
return ALCHEMY_TEMPLATES.model.safe_substitute(class_name=self.class_name, table_name=self.table_name, column_definitions=self.compiled_columns, i...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def put(self): """Updates this task queue on the saltant server. Returns: :class:`saltant.models.task_queue.TaskQueue`: A task queue model instance representing ...
return self.manager.put( id=self.id, name=self.name, description=self.description, private=self.private, runs_executable_tasks=self.runs_executable_tasks, runs_docker_container_tasks=self.runs_docker_container_tasks, runs_singu...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get(self, id=None, name=None): """Get a task queue. Either the id xor the name of the task type must be specified. Args: id (int, optional): The id of the t...
# Validate arguments - use an xor if not (id is None) ^ (name is None): raise ValueError("Either id or name must be set (but not both!)") # If it's just ID provided, call the parent function if id is not None: return super(TaskQueueManager, self).get(id=id) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create( self, name, description="", private=False, runs_executable_tasks=True, runs_docker_container_tasks=True, runs_singularity_container_tasks=True, active...
# Translate whitelists None to [] if necessary if whitelists is None: whitelists = [] # Create the object request_url = self._client.base_api_url + self.list_url data_to_post = { "name": name, "description": description, "private"...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def patch( self, id, name=None, description=None, private=None, runs_executable_tasks=None, runs_docker_container_tasks=None, runs_singularity_container_tasks=Non...
# Update the object request_url = self._client.base_api_url + self.detail_url.format(id=id) data_to_patch = {} if name is not None: data_to_patch["name"] = name if description is not None: data_to_patch["description"] = description if private ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def put( self, id, name, description, private, runs_executable_tasks, runs_docker_container_tasks, runs_singularity_container_tasks, active, whitelists, ): """Up...
# Update the object request_url = self._client.base_api_url + self.detail_url.format(id=id) data_to_put = { "name": name, "description": description, "private": private, "runs_executable_tasks": runs_executable_tasks, "runs_docker_cont...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def main(self): """ Run the required methods in the appropriate order """
self.targets() self.bait(k=49) self.reversebait(maskmiddle='t', k=19) self.subsample_reads()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def targets(self): """ Using the data from the BLAST analyses, set the targets folder, and create the 'mapping file'. This is the genera-specific FASTA file that...
logging.info('Performing analysis with {} targets folder'.format(self.analysistype)) for sample in self.runmetadata: if sample.general.bestassemblyfile != 'NA': sample[self.analysistype].targetpath = \ os.path.join(self.targetpath, 'genera', sample[self.a...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def subsample(self): """ Subsample 1000 reads from the baited files """
# Create the threads for the analysis logging.info('Subsampling FASTQ reads') for _ in range(self.cpus): threads = Thread(target=self.subsamplethreads, args=()) threads.setDaemon(True) threads.start() with progressbar(self.runmetadata.samples) as bar:...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fasta(self): """ Convert the subsampled reads to FASTA format using reformat.sh """
logging.info('Converting FASTQ files to FASTA format') # Create the threads for the analysis for _ in range(self.cpus): threads = Thread(target=self.fastathreads, args=()) threads.setDaemon(True) threads.start() with progressbar(self.runmetadata.sampl...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def blast(self): """ Run BLAST analyses of the subsampled FASTQ reads against the NCBI 16S reference database """
logging.info('BLASTing FASTA files against {} database'.format(self.analysistype)) for _ in range(self.cpus): threads = Thread(target=self.blastthreads, args=()) threads.setDaemon(True) threads.start() with progressbar(self.runmetadata.samples) as bar: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def blastparse(self): """ Parse the blast results, and store necessary data in dictionaries in sample object """
logging.info('Parsing BLAST results') # Load the NCBI 16S reference database as a dictionary for sample in self.runmetadata.samples: if sample.general.bestassemblyfile != 'NA': # Load the NCBI 16S reference database as a dictionary dbrecords = SeqIO.t...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def load_json(json_object): ''' Load json from file or file name ''' content = None if isinstance(json_object, str) and os.path.exists(json_object): with open_(json_object) as f: try: content = json.load(f) except Exception as e: debug.log("Warning: Content of '%...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sort2groups(array, gpat=['_R1','_R2']): """ Sort an array of strings to groups by patterns """
groups = [REGroup(gp) for gp in gpat] unmatched = [] for item in array: matched = False for m in groups: if m.match(item): matched = True break if not matched: unmatched.append(item) return [sorted(m.list) for m in groups], sorted(unmatched)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sort_and_distribute(array, splits=2): """ Sort an array of strings to groups by alphabetically continuous distribution """
if not isinstance(array, (list,tuple)): raise TypeError("array must be a list") if not isinstance(splits, int): raise TypeError("splits must be an integer") remaining = sorted(array) if sys.version_info < (3, 0): myrange = xrange(splits) else: myrange = range(splits) groups = [[] for i in...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def file_zipper(root_dir): """ This function will zip the files created in the runroot directory and subdirectories """
# FINDING AND ZIPPING UNZIPPED FILES for root, dirs, files in os.walk(root_dir, topdown=False): if root != "": if root[-1] != '/': root += '/' for current_file in files: filepath = "%s/%s"%(root, current_file) try: file_size = os.path.getsize(filepat...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def file_unzipper(directory): """ This function will unzip all files in the runroot directory and subdirectories """
debug.log("Unzipping directory (%s)..."%directory) #FINDING AND UNZIPPING ZIPPED FILES for root, dirs, files in os.walk(directory, topdown=False): if root != "": orig_dir = os.getcwd() os.chdir(directory) Popen('gunzip -q -f *.gz > /dev/null 2>&1', shell=True).wait() ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def move_file(src, dst): """ this function will simply move the file from the source path to the dest path given as input """
# Sanity checkpoint src = re.sub('[^\w/\-\.\*]', '', src) dst = re.sub('[^\w/\-\.\*]', '', dst) if len(re.sub('[\W]', '', src)) < 5 or len(re.sub('[\W]', '', dst)) < 5: debug.log("Error: Moving file failed. Provided paths are invalid! src='%s' dst='%s'"%(src, dst)) else: # Check destination ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def log(self, *lst): """ Print list of strings to the predefined logfile if debug is set. and sets the caught_error message if an error is found """
self.print2file(self.logfile, self.debug, True, *lst) if 'Error' in '\n'.join([str(x) for x in lst]): self.caught_error = '\n'.join([str(x) for x in lst])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def log_no_newline(self, msg): """ print the message to the predefined log file without newline """
self.print2file(self.logfile, False, False, msg)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def graceful_exit(self, msg): """ This function Tries to update the MSQL database before exiting. """
# Print stored errors to stderr if self.caught_error: self.print2file(self.stderr, False, False, self.caught_error) # Kill process with error message self.log(msg) sys.exit(1)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def match(self, s): """ Matches the string to the stored regular expression, and stores all groups in mathches. Returns False on negative match. """
self.matches = self.re.search(s) return self.matches
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reporter(self): """ Create the MASH report """
logging.info('Creating {} report'.format(self.analysistype)) make_path(self.reportpath) header = 'Strain,ReferenceGenus,ReferenceFile,ReferenceGenomeMashDistance,Pvalue,NumMatchingHashes\n' data = '' for sample in self.metadata: try: data += '{},{},{}...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def edges(self): """ Return the edge characters of this node. """
edge_str = ctypes.create_string_buffer(MAX_CHARS) cgaddag.gdg_edges(self.gdg, self.node, edge_str) return [char for char in edge_str.value.decode("ascii")]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def letter_set(self): """ Return the letter set of this node. """
end_str = ctypes.create_string_buffer(MAX_CHARS) cgaddag.gdg_letter_set(self.gdg, self.node, end_str) return [char for char in end_str.value.decode("ascii")]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_end(self, char): """ Return `True` if this `char` is part of this node's letter set, `False` otherwise. """
char = char.lower() return bool(cgaddag.gdg_is_end(self.gdg, self.node, char.encode("ascii")))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def follow(self, chars): """ Traverse the GADDAG to the node at the end of the given characters. Args: chars: An string of characters to traverse in the GADDAG. ...
chars = chars.lower() node = self.node for char in chars: node = cgaddag.gdg_follow_edge(self.gdg, node, char.encode("ascii")) if not node: raise KeyError(char) return Node(self.gdg, node)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read(alias_name, allow_none=False): """Get the raw docker link value. Get the raw environment variable for the docker link Args: alias_name: The environment ...
warnings.warn('Will be removed in v1.0', DeprecationWarning, stacklevel=2) return core.read('{0}_PORT'.format(alias_name), default=None, allow_none=allow_none)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def isset(alias_name): """Return a boolean if the docker link is set or not and is a valid looking docker link value. Args: alias_name: The link alias name """
warnings.warn('Will be removed in v1.0', DeprecationWarning, stacklevel=2) raw_value = read(alias_name, allow_none=True) if raw_value: if re.compile(r'.+://.+:\d+').match(raw_value): return True else: warnings.warn('"{0}_PORT={1}" does not look like a docker link.'.f...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def protocol(alias_name, default=None, allow_none=False): """Get the protocol from the docker link alias or return the default. Args: alias_name: The docker link...
warnings.warn('Will be removed in v1.0', DeprecationWarning, stacklevel=2) try: return _split_docker_link(alias_name)[0] except KeyError as err: if default or allow_none: return default else: raise err
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def port(alias_name, default=None, allow_none=False): """Get the port from the docker link alias or return the default. Args: alias_name: The docker link alias d...
warnings.warn('Will be removed in v1.0', DeprecationWarning, stacklevel=2) try: return int(_split_docker_link(alias_name)[2]) except KeyError as err: if default or allow_none: return default else: raise err
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def attributer(self): """ Parses the 16S target files to link accession numbers stored in the .fai and metadata files to the genera stored in the target file """
from Bio import SeqIO import operator for sample in self.runmetadata.samples: # Load the records from the target file into a dictionary record_dict = SeqIO.to_dict(SeqIO.parse(sample[self.analysistype].baitfile, "fasta")) sample[self.analysistype].classificat...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def spawn_server_api(api_name, app, api_spec, error_callback, decorator): """Take a a Flask app and a swagger file in YAML format describing a REST API, and popu...
def mycallback(endpoint): handler_func = get_function(endpoint.handler_server) # Generate api endpoint around that handler handler_wrapper = _generate_handler_wrapper(api_name, api_spec, endpoint, handler_func, error_callback, decorator) # Bind handler to the API path log...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _responsify(api_spec, error, status): """Take a bravado-core model representing an error, and return a Flask Response with the given error code and error ins...
result_json = api_spec.model_to_json(error) r = jsonify(result_json) r.status_code = status return r
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def format_escape( foreground=None, background=None, bold=False, faint=False, italic=False, underline=False, blink=False, inverted=False ): """Returns the ANSI e...
fg_format = None if isinstance( foreground, int ): fg_format = ANSI_FORMAT_FOREGROUND_XTERM_CMD.format( foreground ) else: fg_rgba = colour.normalise_rgba( foreground ) if fg_rgba[3] != 0: fg_format = ANSI_FORMAT_FOREGROUND_CMD.format( *fg_rgba[:3] ) bg_format = Non...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def format_string( string, foreground=None, background=None, reset=True, bold=False, faint=False, italic=False, underline=False, blink=False, inverted=False ): "...
colour_format = format_escape( foreground, background, bold, faint, italic, underline, blink, inverted ) reset_format = '' if not reset else ANSI_FORMAT_RESET return '{}{}{}'.format( colour_format, string, reset_format )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def format_pixels( top, bottom, reset=True, repeat=1 ): """Return the ANSI escape sequence to render two vertically-stacked pixels as a single monospace characte...
top_src = None if isinstance( top, int ): top_src = top else: top_rgba = colour.normalise_rgba( top ) if top_rgba[3] != 0: top_src = top_rgba bottom_src = None if isinstance( bottom, int ): bottom_src = bottom else: bottom_rgba = colour.norma...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def format_image_iter( data_fetch, x_start=0, y_start=0, width=32, height=32, frame=0, columns=1, downsample=1 ): """Return the ANSI escape sequence to render a ...
frames = [] try: frame_iter = iter( frame ) frames = [f for f in frame_iter] except TypeError: frames = [frame] rows = math.ceil( len( frames )/columns ) for r in range( rows ): for y in range( 0, height, 2*downsample ): result = [] for c in ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update_buffer_with_value( self, value, buffer, parent=None ): """Write a Python object into a byte array, using the field definition. value Input Python obje...
assert common.is_bytes( buffer ) self.validate( value, parent ) return
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_end_offset( self, value, parent=None, index=None ): """Return the end offset of the Field's data. Useful for chainloading. value Input Python object to p...
return self.get_start_offset( value, parent, index ) + self.get_size( value, parent, index )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def nonalpha_split(string): '''Split 'string' along any punctuation or whitespace.''' return re.findall(r'[%s]+|[^%s]+' % (A, A), string, flags=FLAGS)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def extract_words(string): '''Extract all alphabetic syllabified forms from 'string'.''' return re.findall(r'[%s]+[%s\.]*[%s]+' % (A, A, A), string, flags=FLAGS)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def init_threads(t=None, s=None): """Should define dummyThread class and dummySignal class"""
global THREAD, SIGNAL THREAD = t or dummyThread SIGNAL = s or dummySignal
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def thread_with_callback(on_error, on_done, requete_with_callback): """ Return a thread emiting `state_changed` between each sub-requests. :param on_error: callb...
class C(THREAD): error = SIGNAL(str) done = SIGNAL(object) state_changed = SIGNAL(int, int) def __del__(self): self.wait() def run(self): try: r = requete_with_callback(self.state_changed.emit) except (ConnexionError, S...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def build_parser(parser: argparse.ArgumentParser) -> None: """Build a parser for CLI arguments and options."""
parser.add_argument( '--delimiter', help='a delimiter for the samples (teeth) in the key', default=' ', ) parser.add_argument( '--encoding', help='the encoding of the population file', default='utf-8', ) parser.add_argument( '--nsamples', '-n'...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def default_parser() -> argparse.ArgumentParser: """Create a parser for CLI arguments and options."""
parser = argparse.ArgumentParser( prog=CONSOLE_SCRIPT, formatter_class=argparse.ArgumentDefaultsHelpFormatter, ) build_parser(parser) return parser
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def key( seq: Sequence, tooth: Callable[[Sequence], str] = ( lambda seq: str(random.SystemRandom().choice(seq)).strip() ), nteeth: int = 6, delimiter: str = ' ', ...
return delimiter.join(tooth(seq) for _ in range(nteeth))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def main(argv: Sequence[str] = SYS_ARGV) -> int: """Execute CLI commands."""
args = default_parser().parse_args(argv) try: seq = POPULATIONS[args.population] # type: Sequence except KeyError: try: with open(args.population, 'r', encoding=args.encoding) as file_: seq = list(file_) except (OSError, UnicodeError) as ex: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def apt_add_repository_from_apt_string(apt_string, apt_file): """ adds a new repository file for apt """
apt_file_path = '/etc/apt/sources.list.d/%s' % apt_file if not file_contains(apt_file_path, apt_string.lower(), use_sudo=True): file_append(apt_file_path, apt_string.lower(), use_sudo=True) with hide('running', 'stdout'): sudo("DEBIAN_FRONTEND=noninteractive apt-get update")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def arch(): """ returns the current cpu archictecture """
with settings(hide('warnings', 'running', 'stdout', 'stderr'), warn_only=True, capture=True): result = sudo('rpm -E %dist').strip() return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def disable_openssh_rdns(distribution): """ Set 'UseDNS no' in openssh config to disable rDNS lookups On each request for a new channel openssh defaults to an rD...
log_green('Disabling openssh reverse dns lookups') openssh_config_file = '/etc/ssh/sshd_config' dns_config = 'UseDNS no' if not file_contains(openssh_config_file, dns_config, use_sudo=True): file_append(openssh_config_file, dns_config, use_sudo=True) service_name = 'sshd' if 'ub...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def connect_to_ec2(region, access_key_id, secret_access_key): """ returns a connection object to AWS EC2 """
conn = boto.ec2.connect_to_region(region, aws_access_key_id=access_key_id, aws_secret_access_key=secret_access_key) return conn
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def connect_to_rackspace(region, access_key_id, secret_access_key): """ returns a connection object to Rackspace """
pyrax.set_setting('identity_type', 'rackspace') pyrax.set_default_region(region) pyrax.set_credentials(access_key_id, secret_access_key) nova = pyrax.connect_to_cloudservers(region=region) return nova
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_gce_image(zone, project, instance_name, name, description): """ Shuts down the instance and creates and image from the disk. Assumes that the disk nam...
disk_name = instance_name try: down_gce(instance_name=instance_name, project=project, zone=zone) except HttpError as e: if e.resp.status == 404: log_yellow("the instance {} is already down".format(instance_name)) else: raise e body = { "rawDisk"...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_image(cloud, **kwargs): """ proxy call for ec2, rackspace create ami backend functions """
if cloud == 'ec2': return create_ami(**kwargs) if cloud == 'rackspace': return create_rackspace_image(**kwargs) if cloud == 'gce': return create_gce_image(**kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_server(cloud, **kwargs): """ Create a new instance """
if cloud == 'ec2': _create_server_ec2(**kwargs) elif cloud == 'rackspace': _create_server_rackspace(**kwargs) elif cloud == 'gce': _create_server_gce(**kwargs) else: raise ValueError("Unknown cloud type: {}".format(cloud))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def gce_wait_until_done(operation): """ Perform a GCE operation, blocking until the operation completes. This function will then poll the operation until it reac...
operation_name = operation['name'] if 'zone' in operation: zone_url_parts = operation['zone'].split('/') project = zone_url_parts[-3] zone = zone_url_parts[-1] def get_zone_operation(): return _get_gce_compute().zoneOperations().get( project=project,...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def startup_gce_instance(instance_name, project, zone, username, machine_type, image, public_key, disk_name=None): """ For now, jclouds is broken for GCE and we ...
log_green("Started...") log_yellow("...Creating GCE Jenkins Slave Instance...") instance_config = get_gce_instance_config( instance_name, project, zone, machine_type, image, username, public_key, disk_name ) operation = _get_gce_compute().instances().insert( project=project,...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _create_server_ec2(region, access_key_id, secret_access_key, disk_name, disk_size, ami, key_pair, instance_type, username, tags={}, security_groups=None): ""...
conn = connect_to_ec2(region, access_key_id, secret_access_key) log_green("Started...") log_yellow("...Creating EC2 instance...") # we need a larger boot device to store our cached images ebs_volume = EBSBlockDeviceType() ebs_volume.size = disk_size bdm = BlockDeviceMapping() bdm[disk...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def enable_marathon_basic_authentication(principal, password): """ configures marathon to start with authentication """
upstart_file = '/etc/init/marathon.conf' with hide('running', 'stdout'): sudo('echo -n "{}" > /etc/marathon-mesos.credentials'.format(password)) boot_args = ' '.join(['exec', '/usr/bin/marathon', '--http_credentials', '"{...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def enable_mesos_basic_authentication(principal, password): """ enables and adds a new authorized principal """
restart = False secrets_file = '/etc/mesos/secrets' secrets_entry = '%s %s' % (principal, password) if not file_contains(filename=secrets_file, text=secrets_entry, use_sudo=True): file_append(filename=secrets_file, text=secrets_entry, use_sudo=True) file_attribs...