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 render_wavedrom(self, node, outpath, bname, format): """ Render a wavedrom image """
# Try to convert node, raise error with code on failure try: svgout = WaveDrom().renderWaveForm(0, json.loads(node['code'])) except JSONDecodeError as e: raise SphinxError("Cannot render the following json code: \n{} \n\nError: {}".format(node['code'], e)) if not os.path.exists(outpat...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def visit_wavedrom(self, node): """ Visit the wavedrom node """
format = determine_format(self.builder.supported_image_types) if format is None: raise SphinxError(__("Cannot determine a suitable output format")) # Create random filename bname = "wavedrom-{}".format(uuid4()) outpath = path.join(self.builder.outdir, self.builder.imagedir) # Render 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 doctree_resolved(app, doctree, fromdocname): """ When the document, and all the links are fully resolved, we inject one raw html element for running the comm...
# Skip for non-html or if javascript is not inlined if not app.env.config.wavedrom_html_jsinline: return text = """ <script type="text/javascript"> function init() { WaveDrom.ProcessAll(); } window.onload = init; </script>""" doctree.append(nodes.raw...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setup(app): """ Setup the extension """
app.add_config_value('offline_skin_js_path', None, 'html') app.add_config_value('offline_wavedrom_js_path', None, 'html') app.add_config_value('wavedrom_html_jsinline', True, 'html') app.add_directive('wavedrom', WavedromDirective) app.connect('build-finished', build_finished) app.connect('buil...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def make_supercell(system, matrix, supercell=[1, 1, 1]): """ Return a supercell. This functions takes the input unitcell and creates a supercell of it that is re...
user_supercell = [[1, supercell[0]], [1, supercell[1]], [1, supercell[1]]] system = create_supercell(system, matrix, supercell=user_supercell) return MolecularSystem.load_system(system)
<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_frames(self, frames='all', override=False, **kwargs): """ Extract frames from the trajectory file. Depending on the passed parameters a frame, a list of ...
if override is True: self.frames = {} if isinstance(frames, int): frame = self._get_frame( self.trajectory_map[frames], frames, **kwargs) if frames not in self.frames.keys(): self.frames[frames] = frame return frame ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _map_trajectory(self): """ Return filepath as a class attribute"""
self.trajectory_map = {} with open(self.filepath, 'r') as trajectory_file: with closing( mmap( trajectory_file.fileno(), 0, access=ACCESS_READ)) as mapped_file: progress = 0 line = 0 ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def full_analysis(self, ncpus=1, **kwargs): """ Perform a full structural analysis of a molecule. This invokes other methods: 1. :attr:`molecular_weight()` 2. :a...
self.molecular_weight() self.calculate_centre_of_mass() self.calculate_maximum_diameter() self.calculate_average_diameter() self.calculate_pore_diameter() self.calculate_pore_volume() self.calculate_pore_diameter_opt(**kwargs) self.calculate_pore_volume_o...
<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_centre_of_mass(self): """ Return the xyz coordinates of the centre of mass of a molecule. Returns ------- :class:`numpy.array` The centre of mass o...
self.centre_of_mass = center_of_mass(self.elements, self.coordinates) self.properties['centre_of_mass'] = self.centre_of_mass return self.centre_of_mass
<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_maximum_diameter(self): """ Return the maximum diamension of a molecule. Returns ------- :class:`float` The maximum dimension of the molecule. """
self.maxd_atom_1, self.maxd_atom_2, self.maximum_diameter = max_dim( self.elements, self.coordinates) self.properties['maximum_diameter'] = { 'diameter': self.maximum_diameter, 'atom_1': int(self.maxd_atom_1), 'atom_2': int(self.maxd_atom_2), } ...
<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_average_diameter(self, **kwargs): """ Return the average diamension of a molecule. Returns ------- :class:`float` The average dimension of the mole...
self.average_diameter = find_average_diameter( self.elements, self.coordinates, **kwargs) return self.average_diameter
<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_pore_diameter(self): """ Return the intrinsic pore diameter. Returns ------- :class:`float` The intrinsic pore diameter. """
self.pore_diameter, self.pore_closest_atom = pore_diameter( self.elements, self.coordinates) self.properties['pore_diameter'] = { 'diameter': self.pore_diameter, 'atom': int(self.pore_closest_atom), } return self.pore_diameter
<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_pore_volume(self): """ Return the intrinsic pore volume. Returns ------- :class:`float` The intrinsic pore volume. """
self.pore_volume = sphere_volume(self.calculate_pore_diameter() / 2) self.properties['pore_volume'] = self.pore_volume return self.pore_volume
<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_windows(self, **kwargs): """ Return the diameters of all windows in a molecule. This function first finds and then measures the diameters of all th...
windows = find_windows(self.elements, self.coordinates, **kwargs) if windows: self.properties.update( { 'windows': { 'diameters': windows[0], 'centre_of_mass': windows[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 shift_to_origin(self, **kwargs): """ Shift a molecule to Origin. This function takes the molecule's coordinates and adjust them so that the centre of mass of...
self.coordinates = shift_com(self.elements, self.coordinates, **kwargs) self._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 rebuild_system(self, override=False, **kwargs): """ Rebuild molecules in molecular system. Parameters override : :class:`bool`, optional (default=False) If F...
# First we create a 3x3x3 supercell with the initial unit cell in the # centre and the 26 unit cell translations around to provide all the # atom positions necessary for the molecules passing through periodic # boundary reconstruction step. supercell_333 = create_supercell(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 swap_atom_keys(self, swap_dict, dict_key='atom_ids'): """ Swap a force field atom id for another user-defined value. This modified all values in :attr:`Molec...
# Similar situation to the one from decipher_atom_keys function. if 'atom_ids' not in self.system.keys(): dict_key = 'elements' for atom_key in range(len(self.system[dict_key])): for key in swap_dict.keys(): if self.system[dict_key][atom_key] == key: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def decipher_atom_keys(self, forcefield='DLF', dict_key='atom_ids'): """ Decipher force field atom ids. This takes all values in :attr:`MolecularSystem.system['a...
# In case there is no 'atom_ids' key we try 'elements'. This is for # XYZ and MOL files mostly. But, we keep the dict_key keyword for # someone who would want to decipher 'elements' even if 'atom_ids' key # is present in the system's dictionary. if 'atom_ids' not in self.system....
<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_pores(self, sampling_points): """ Under development."""
pores = [] for point in sampling_points: pores.append( Pore( self.system['elements'], self.system['coordinates'], com=point)) return pores
<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_attrname_by_colname(instance, name): """ Get value from SQLAlchemy instance by column name :Parameters: - `instance`: SQLAlchemy model instance. - `name`...
for attr, column in list(sqlalchemy.inspect(instance.__class__).c.items()): if column.name == name: return attr
<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_empty_instance(table): """ Return empty instance of model. """
instance_defaults_params = inspect.getargspec(table.__init__).args[1:] # list like ['name', 'group', 'visible'] to dict with empty # value as {'name': None, 'group': None, 'visible': None} init = dict( list(zip(instance_defaults_params, itertools.repeat(None))) ) return table(**init)
<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_pk(obj): """ Return primary key name by model class or instance. :Parameters: - `obj`: SQLAlchemy model instance or class. :Examples: (Column('id', Integ...
if inspect.isclass(obj): pk_list = sqlalchemy.inspect(obj).primary_key else: pk_list = obj.__mapper__.primary_key return pk_list
<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_rules_from_all_proxies(self): """ Clear fault injection rules from all known service proxies. """
self._queue = [] if self.debug: print 'Clearing rules' for service in self.app.get_services(): for instance in self.app.get_service_instances(service): if self.debug: print 'Clearing rules for %s - instance %s' % (service, inst...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setup_failure(self, scenario=None, **args): """Add a given failure scenario @param scenario: string 'delayrequests' or 'crash' """
assert scenario is not None and scenario in self.functiondict self.functiondict[scenario](**args)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setup_failures(self, gremlins): """Add gremlins to environment"""
assert isinstance(gremlins, dict) and 'gremlins' in gremlins for gremlin in gremlins['gremlins']: self.setup_failure(**gremlin) self.push_rules()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_vertex(self, x, y, z, name): """add vertex by coordinate and uniq name x y z is coordinates of vertex name is uniq name to refer the vertex returns Verte...
self.vertices[name] = Vertex(x, y, z, name) return self.vertices[name]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reduce_vertex(self, name1, *names): same Vertex instance as name1 """
v = self.vertices[name1] for n in names: w = self.vertices[n] v.alias.update(w.alias) # replace mapping from n w by to v self.vertices[n] = v
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def merge_vertices(self): """call reduce_vertex on all vertices with identical values."""
# groupby expects sorted data sorted_vertices = sorted(list(self.vertices.items()), key=lambda v: hash(v[1])) groups = [] for k, g in groupby(sorted_vertices, lambda v: hash(v[1])): groups.append(list(g)) for group in groups: if len(group) == 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 extract(path, to_path='', ext='', **kwargs): """ Unpack the tar or zip file at the specified path to the directory specified by to_path. """
Archive(path, ext=ext).extract(to_path, **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 _archive_cls(file, ext=''): """ Return the proper Archive implementation class, based on the file type. """
cls = None filename = None if is_string(file): filename = file else: try: filename = file.name except AttributeError: raise UnrecognizedArchiveFormat( "File object not a recognized archive 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 check_files(self, to_path=None): """ Check that all of the files contained in the archive are within the target directory. """
if to_path: target_path = os.path.normpath(os.path.realpath(to_path)) else: target_path = os.getcwd() for filename in self.filenames(): extract_path = os.path.join(target_path, filename) extract_path = os.path.normpath(os.path.realpath(extract_pat...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def meanstack(infn: Path, Navg: int, ut1: Optional[datetime]=None, method: str='mean') -> Tuple[np.ndarray, Optional[datetime]]: infn = Path(infn).expanduser() # ...
if infn.suffix == '.h5': img, ut1 = _h5mean(infn, ut1, key, method) elif infn.suffix == '.fits': with fits.open(infn, mode='readonly', memmap=False) as f: # mmap doesn't work with BZERO/BSCALE/BLANK img = collapsestack(f[0].data, key, method) elif infn.suffix == '.mat': ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _run_search_request( self, protocol_request, object_name, protocol_response_class): """ Runs the specified request at the specified object_name and instantia...
not_done = True while not_done: response_object = self._run_search_page_request( protocol_request, object_name, protocol_response_class) value_list = getattr( response_object, protocol.getValueListName(protocol_response_class)) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def list_reference_bases(self, id_, start=0, end=None): """ Returns an iterator over the bases from the server in the form of consecutive strings. This command d...
request = protocol.ListReferenceBasesRequest() request.start = pb.int(start) request.end = pb.int(end) request.reference_id = id_ not_done = True # TODO We should probably use a StringIO here to make string buffering # a bit more efficient. bases_list = [...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def search_variants( self, variant_set_id, start=None, end=None, reference_name=None, call_set_ids=None): """ Returns an iterator over the Variants fulfilling th...
request = protocol.SearchVariantsRequest() request.reference_name = pb.string(reference_name) request.start = pb.int(start) request.end = pb.int(end) request.variant_set_id = variant_set_id request.call_set_ids.extend(pb.string(call_set_ids)) request.page_size = ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def search_variant_annotations( self, variant_annotation_set_id, reference_name="", reference_id="", start=0, end=0, effects=[]): """ Returns an iterator over th...
request = protocol.SearchVariantAnnotationsRequest() request.variant_annotation_set_id = variant_annotation_set_id request.reference_name = reference_name request.reference_id = reference_id request.start = start request.end = end for effect in effects: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def search_features( self, feature_set_id=None, parent_id="", reference_name="", start=0, end=0, feature_types=[], name="", gene_symbol=""): """ Returns the resu...
request = protocol.SearchFeaturesRequest() request.feature_set_id = feature_set_id request.parent_id = parent_id request.reference_name = reference_name request.name = name request.gene_symbol = gene_symbol request.start = start request.end = end ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def search_continuous( self, continuous_set_id=None, reference_name="", start=0, end=0): """ Returns the result of running a search_continuous method on a reques...
request = protocol.SearchContinuousRequest() request.continuous_set_id = continuous_set_id request.reference_name = reference_name request.start = start request.end = end request.page_size = pb.int(self._page_size) return self._run_search_request( req...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def search_datasets(self): """ Returns an iterator over the Datasets on the server. :return: An iterator over the :class:`ga4gh.protocol.Dataset` objects on the ...
request = protocol.SearchDatasetsRequest() request.page_size = pb.int(self._page_size) return self._run_search_request( request, "datasets", protocol.SearchDatasetsResponse)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def search_variant_sets(self, dataset_id): """ Returns an iterator over the VariantSets fulfilling the specified conditions from the specified Dataset. :param st...
request = protocol.SearchVariantSetsRequest() request.dataset_id = dataset_id request.page_size = pb.int(self._page_size) return self._run_search_request( request, "variantsets", protocol.SearchVariantSetsResponse)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def search_variant_annotation_sets(self, variant_set_id): """ Returns an iterator over the Annotation Sets fulfilling the specified conditions from the specified...
request = protocol.SearchVariantAnnotationSetsRequest() request.variant_set_id = variant_set_id request.page_size = pb.int(self._page_size) return self._run_search_request( request, "variantannotationsets", protocol.SearchVariantAnnotationSetsResponse)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def search_feature_sets(self, dataset_id): """ Returns an iterator over the FeatureSets fulfilling the specified conditions from the specified Dataset. :param st...
request = protocol.SearchFeatureSetsRequest() request.dataset_id = dataset_id request.page_size = pb.int(self._page_size) return self._run_search_request( request, "featuresets", protocol.SearchFeatureSetsResponse)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def search_continuous_sets(self, dataset_id): """ Returns an iterator over the ContinuousSets fulfilling the specified conditions from the specified Dataset. :pa...
request = protocol.SearchContinuousSetsRequest() request.dataset_id = dataset_id request.page_size = pb.int(self._page_size) return self._run_search_request( request, "continuoussets", protocol.SearchContinuousSetsResponse)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def search_reference_sets( self, accession=None, md5checksum=None, assembly_id=None): """ Returns an iterator over the ReferenceSets fulfilling the specified con...
request = protocol.SearchReferenceSetsRequest() request.accession = pb.string(accession) request.md5checksum = pb.string(md5checksum) request.assembly_id = pb.string(assembly_id) request.page_size = pb.int(self._page_size) return self._run_search_request( req...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def search_references( self, reference_set_id, accession=None, md5checksum=None): """ Returns an iterator over the References fulfilling the specified conditions...
request = protocol.SearchReferencesRequest() request.reference_set_id = reference_set_id request.accession = pb.string(accession) request.md5checksum = pb.string(md5checksum) request.page_size = pb.int(self._page_size) return self._run_search_request( request...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def search_call_sets(self, variant_set_id, name=None, biosample_id=None): """ Returns an iterator over the CallSets fulfilling the specified conditions from the ...
request = protocol.SearchCallSetsRequest() request.variant_set_id = variant_set_id request.name = pb.string(name) request.biosample_id = pb.string(biosample_id) request.page_size = pb.int(self._page_size) return self._run_search_request( request, "callsets", ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def search_biosamples(self, dataset_id, name=None, individual_id=None): """ Returns an iterator over the Biosamples fulfilling the specified conditions. :param s...
request = protocol.SearchBiosamplesRequest() request.dataset_id = dataset_id request.name = pb.string(name) request.individual_id = pb.string(individual_id) request.page_size = pb.int(self._page_size) return self._run_search_request( request, "biosamples", pr...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def search_individuals(self, dataset_id, name=None): """ Returns an iterator over the Individuals fulfilling the specified conditions. :param str dataset_id: The...
request = protocol.SearchIndividualsRequest() request.dataset_id = dataset_id request.name = pb.string(name) request.page_size = pb.int(self._page_size) return self._run_search_request( request, "individuals", protocol.SearchIndividualsResponse)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def search_read_group_sets( self, dataset_id, name=None, biosample_id=None): """ Returns an iterator over the ReadGroupSets fulfilling the specified conditions f...
request = protocol.SearchReadGroupSetsRequest() request.dataset_id = dataset_id request.name = pb.string(name) request.biosample_id = pb.string(biosample_id) request.page_size = pb.int(self._page_size) return self._run_search_request( request, "readgroupsets"...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def search_reads( self, read_group_ids, reference_id=None, start=None, end=None): """ Returns an iterator over the Reads fulfilling the specified conditions from...
request = protocol.SearchReadsRequest() request.read_group_ids.extend(read_group_ids) request.reference_id = pb.string(reference_id) request.start = pb.int(start) request.end = pb.int(end) request.page_size = pb.int(self._page_size) return self._run_search_reques...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def search_phenotype_association_sets(self, dataset_id): """ Returns an iterator over the PhenotypeAssociationSets on the server. """
request = protocol.SearchPhenotypeAssociationSetsRequest() request.dataset_id = dataset_id request.page_size = pb.int(self._page_size) return self._run_search_request( request, "phenotypeassociationsets", protocol.SearchPhenotypeAssociationSetsResponse)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def search_genotype_phenotype( self, phenotype_association_set_id=None, feature_ids=None, phenotype_ids=None, evidence=None): """ Returns an iterator over the Ge...
request = protocol.SearchGenotypePhenotypeRequest() request.phenotype_association_set_id = phenotype_association_set_id if feature_ids: request.feature_ids.extend(feature_ids) if phenotype_ids: request.phenotype_ids.extend(phenotype_ids) if evidence: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def search_phenotype( self, phenotype_association_set_id=None, phenotype_id=None, description=None, type_=None, age_of_onset=None): """ Returns an iterator over ...
request = protocol.SearchPhenotypesRequest() request.phenotype_association_set_id = phenotype_association_set_id if phenotype_id: request.id = phenotype_id if description: request.description = description if type_: request.type.mergeFrom(type...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def search_rna_quantification_sets(self, dataset_id): """ Returns an iterator over the RnaQuantificationSet objects from the server """
request = protocol.SearchRnaQuantificationSetsRequest() request.dataset_id = dataset_id request.page_size = pb.int(self._page_size) return self._run_search_request( request, "rnaquantificationsets", protocol.SearchRnaQuantificationSetsResponse)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def search_rna_quantifications(self, rna_quantification_set_id=""): """ Returns an iterator over the RnaQuantification objects from the server :param str rna_qua...
request = protocol.SearchRnaQuantificationsRequest() request.rna_quantification_set_id = rna_quantification_set_id request.page_size = pb.int(self._page_size) return self._run_search_request( request, "rnaquantifications", protocol.SearchRnaQuantificationsRespons...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def search_expression_levels( self, rna_quantification_id="", names=[], threshold=0.0): """ Returns an iterator over the ExpressionLevel objects from the server ...
request = protocol.SearchExpressionLevelsRequest() request.rna_quantification_id = rna_quantification_id request.names.extend(names) request.threshold = threshold request.page_size = pb.int(self._page_size) return self._run_search_request( request, "expressio...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _setup_http_session(self): """ Sets up the common HTTP session parameters used by requests. """
headers = {"Content-type": "application/json"} if (self._id_token): headers.update({"authorization": "Bearer {}".format( self._id_token)}) self._session.headers.update(headers) # TODO is this unsafe???? self._session.verify = False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _check_response_status(self, response): """ Checks the speficied HTTP response from the requests package and raises an exception if a non-200 HTTP code was r...
if response.status_code != requests.codes.ok: self._logger.error("%s %s", response.status_code, response.text) raise exceptions.RequestNonSuccessException( "Url {0} had status_code {1}".format( response.url, response.status_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 init_app(self, app): """ Initialize the captcha extension to the given app object. """
self.enabled = app.config.get("CAPTCHA_ENABLE", True) self.digits = app.config.get("CAPTCHA_LENGTH", 4) self.max = 10**self.digits self.image_generator = ImageCaptcha() self.rand = SystemRandom() def _generate(): if not self.enabled: 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 update(self): """ Update Monit deamon and services status. """
url = self.baseurl + '/_status?format=xml' response = self.s.get(url) response.raise_for_status() from xml.etree.ElementTree import XML root = XML(response.text) for serv_el in root.iter('service'): serv = Monit.Service(self, serv_el) self[serv.na...
<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_recv(self): """ Parses the IKE_INIT response packet received from Responder. Assigns the correct values of rSPI and Nr Calculates Diffie-Hellman exchang...
assert len(self.packets) == 2 packet = self.packets[-1] for p in packet.payloads: if p._type == payloads.Type.Nr: self.Nr = p._data logger.debug(u"Responder nonce {}".format(binascii.hexlify(self.Nr))) elif p._type == payloads.Type.KE: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def authenticate_peer(self, auth_data, peer_id, message): """ Verifies the peers authentication. """
logger.debug('message: {}'.format(dump(message))) signed_octets = message + self.Ni + prf(self.SK_pr, peer_id._data) auth_type = const.AuthenticationType(struct.unpack(const.AUTH_HEADER, auth_data[:4])[0]) assert auth_type == const.AuthenticationType.RSA logger.debug(dump(auth_d...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def auth_recv(self): """ Handle peer's IKE_AUTH response. """
id_r = auth_data = None for p in self.packets[-1].payloads: if p._type == payloads.Type.IDr: id_r = p logger.debug('Got responder ID: {}'.format(dump(bytes(p)))) if p._type == payloads.Type.AUTH: auth_data = p._data if ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_payload(self, payload): """ Adds a payload to packet, updating last payload's next_payload field """
if self.payloads: self.payloads[-1].next_payload = payload._type self.payloads.append(payload)
<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_caller_module(): """ Returns the name of the caller's module as a string. '__main__' """
stack = inspect.stack() assert len(stack) > 1 caller = stack[2][0] return caller.f_globals['__name__']
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def uniform(self, key, min_value=0., max_value=1.): """Returns a random number between min_value and max_value"""
return min_value + self._random(key) * (max_value - min_value)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def perlin(self, key, **kwargs): """Return perlin noise seede with the specified key. For parameters, check the PerlinNoise class."""
if hasattr(key, "encode"): key = key.encode('ascii') value = zlib.adler32(key, self.seed) return PerlinNoise(value, **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 check_no_proxy_errors(self, **kwargs): """ Helper method to determine if the proxies logged any major errors related to the functioning of the proxy itself "...
data = self._es.search(body={ "size": max_query_results, "query": { "filtered": { "query": { "match_all": {} }, "filter": { "term": { "...
<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_requests_with_errors(self): """ Helper method to determine if proxies logged any error related to the requests passing through"""
data = self._es.search(body={ "size": max_query_results, "query": { "filtered": { "query": { "match_all": {} }, "filter": { "exists": { ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check_assertions(self, checklist, all=False): """Check a set of assertions @param all boolean if False, stop at first failure @return: False if any assertion...
assert isinstance(checklist, dict) and 'checks' in checklist retval = None retlist = [] for assertion in checklist['checks']: retval = self.check_assertion(**assertion) retlist.append(retval) if not retval.success and not all: print...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def download(odir: Path, source_url: str, irng: Sequence[int]): """Download star index files. The default range was useful for my cameras. """
assert len(irng) == 2, 'specify start, stop indices' odir = Path(odir).expanduser() odir.mkdir(parents=True, exist_ok=True) ri = int(source_url.split('/')[-2][:2]) for i in range(*irng): fn = f'index-{ri:2d}{i:02d}.fits' url = f'{source_url}{fn}' ofn = odir / fn 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 exclude_match(exclude, link_value): """ Check excluded value against the link's current value """
if hasattr(exclude, "search") and exclude.search(link_value): return True if exclude == link_value: return True return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def seoify_hyperlink(hyperlink): """Modify a hyperlink to make it SEO-friendly by replacing hyphens with spaces and trimming multiple spaces. :param hyperlink: U...
last_slash = hyperlink.rfind('/') return re.sub(r' +|-', ' ', hyperlink[last_slash + 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 find(self, limit=None, reverse=False, sort=None, exclude=None, duplicates=True, pretty=False, **filters): """ Using filters and sorts, this finds all hyperli...
if exclude is None: exclude = [] if 'href' not in filters: filters['href'] = True search = self._soup.findAll('a', **filters) if reverse: search.reverse() links = [] for anchor in search: build_link = anchor.attrs ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_plot(fn: Path, cm, ax, alpha=1): """Astrometry.net makes file ".new" with the image and the WCS SIP 2-D polynomial fit coefficients in the FITS header We...
with fits.open(fn, mode='readonly', memmap=False) as f: img = f[0].data yPix, xPix = f[0].shape[-2:] x, y = np.meshgrid(range(xPix), range(yPix)) # pixel indices to find RA/dec of xy = np.column_stack((x.ravel(order='C'), y.ravel(order='C'))) radec = wcs.WCS(f[0].header)...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dump(src): """ Returns data in hex format in groups of 4 octets delimited by spaces for debugging purposes. """
return b' '.join(binascii.hexlify(bytes(x)) for x in zip(src[::4], src[1::4], src[2::4], src[3::4]))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def index(): """ Display productpage with normal user and test user buttons"""
global productpage table = json2html.convert(json = json.dumps(productpage), table_attributes="class=\"table table-condensed table-bordered table-hover\"") return render_template('index.html', serviceTable=table)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def frange(start, end, step): """A range implementation which can handle floats"""
if start <= end: step = abs(step) else: step = -abs(step) while start < end: yield start start += step
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def gridrange(start, end, step): """Generate a grid of complex numbers"""
for x in frange(start.real, end.real, step.real): for y in frange(start.imag, end.imag, step.imag): yield x + y * 1j
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pad(data, blocksize=16): """ Pads data to blocksize according to RFC 4303. Pad length field is included in output. """
padlen = blocksize - len(data) % blocksize return bytes(data + bytearray(range(1, padlen)) + bytearray((padlen - 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 doSolve(fitsfn: Path, args: str=None): """ Astrometry.net from at least version 0.67 is OK with Python 3. """
# binpath = Path(find_executable('solve-field')).parent opts = args.split(' ') if args else [] # %% build command cmd = ['solve-field', '--overwrite', str(fitsfn)] cmd += opts print('\n', ' '.join(cmd), '\n') # %% execute ret = subprocess.check_output(cmd, universal_newlines=True) # solve-...
<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_rgb(hsv): """Converts a color from HSV to a hex RGB. HSV should be in range 0..1, though hue wraps around. Output is a hexadecimal color value as used by ...
r, g, b = [int(min(255, max(0, component * 256))) for component in colorsys.hsv_to_rgb(*hsv)] return "%02x%02x%02x" % (r, g, b)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def verbosityToLogLevel(verbosity): """ Returns the specfied verbosity level interpreted as a logging level. """
ret = 0 if verbosity == 1: ret = logging.INFO elif verbosity >= 2: ret = logging.DEBUG return ret
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def addVariantSearchOptions(parser): """ Adds common options to a variant searches command line parser. """
addVariantSetIdArgument(parser) addReferenceNameArgument(parser) addCallSetIdsArgument(parser) addStartArgument(parser) addEndArgument(parser) addPageSizeArgument(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 addAnnotationsSearchOptions(parser): """ Adds common options to a annotation searches command line parser. """
addAnnotationSetIdArgument(parser) addReferenceNameArgument(parser) addReferenceIdArgument(parser) addStartArgument(parser) addEndArgument(parser) addEffectsArgument(parser) addPageSizeArgument(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 addFeaturesSearchOptions(parser): """ Adds common options to a features search command line parser. """
addFeatureSetIdArgument(parser) addFeaturesReferenceNameArgument(parser) addStartArgument(parser) addEndArgument(parser) addParentFeatureIdArgument(parser) addFeatureTypesArgument(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 addContinuousSearchOptions(parser): """ Adds common options to a continuous search command line parser. """
addContinuousSetIdArgument(parser) addContinuousReferenceNameArgument(parser) addStartArgument(parser) addEndArgument(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 addGenotypePhenotypeSearchOptions(parser): """ Adds options to a g2p searches command line parser. """
parser.add_argument( "--phenotype_association_set_id", "-s", default=None, help="Only return associations from this phenotype_association_set.") parser.add_argument( "--feature_ids", "-f", default=None, help="Only return associations for these features.") parser.add_argument...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def addPhenotypeSearchOptions(parser): """ Adds options to a phenotype searches command line parser. """
parser.add_argument( "--phenotype_association_set_id", "-s", default=None, help="Only return phenotypes from this phenotype_association_set.") parser.add_argument( "--phenotype_id", "-p", default=None, help="Only return this phenotype.") parser.add_argument( "--descr...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _textOutput(self, gaObjects): """ Outputs a text summary of the specified protocol objects, one per line. """
for gaObject in gaObjects: if hasattr(gaObject, 'name'): print(gaObject.id, gaObject.name, sep="\t") else: print(gaObject.id, sep="\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 getAllVariantSets(self): """ Returns all variant sets on the server. """
for dataset in self.getAllDatasets(): iterator = self._client.search_variant_sets( dataset_id=dataset.id) for variantSet in iterator: yield variantSet
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getAllFeatureSets(self): """ Returns all feature sets on the server. """
for dataset in self.getAllDatasets(): iterator = self._client.search_feature_sets( dataset_id=dataset.id) for featureSet in iterator: yield featureSet
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getAllContinuousSets(self): """ Returns all continuous sets on the server. """
for dataset in self.getAllDatasets(): iterator = self._client.search_continuous_sets( dataset_id=dataset.id) for continuousSet in iterator: yield continuousSet
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getAllReadGroupSets(self): """ Returns all readgroup sets on the server. """
for dataset in self.getAllDatasets(): iterator = self._client.search_read_group_sets( dataset_id=dataset.id) for readGroupSet in iterator: yield readGroupSet
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getAllReadGroups(self): """ Get all read groups in a read group set """
for dataset in self.getAllDatasets(): iterator = self._client.search_read_group_sets( dataset_id=dataset.id) for readGroupSet in iterator: readGroupSet = self._client.get_read_group_set( readGroupSet.id) for readGroup 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 getAllAnnotationSets(self): """ Returns all variant annotation sets on the server. """
for variantSet in self.getAllVariantSets(): iterator = self._client.search_variant_annotation_sets( variant_set_id=variantSet.id) for variantAnnotationSet in iterator: yield variantAnnotationSet
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _run(self, referenceGroupId, referenceId=None): """ automatically guess reference id if not passed """
# check if we can get reference id from rg if referenceId is None: referenceId = self._referenceId if referenceId is None: rg = self._client.get_read_group( read_group_id=referenceGroupId) iterator = self._client.search_references(rg.reference...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run(self): """ Iterate passed read group ids, or go through all available read groups """
if not self._readGroupIds: for referenceGroupId in self.getAllReadGroups(): self._run(referenceGroupId) else: for referenceGroupId in self._readGroupIds: self._run(referenceGroupId)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def merge_all_sections(prnt_sctns, child_sctns, style): """ Merge the doc-sections of the parent's and child's attribute into a single docstring. Parameters prnt...
doc = [] prnt_only_raises = prnt_sctns["Raises"] and not (prnt_sctns["Returns"] or prnt_sctns["Yields"]) if prnt_only_raises and (child_sctns["Returns"] or child_sctns["Yields"]): prnt_sctns["Raises"] = None for key in prnt_sctns: sect = merge_section(key, prnt_sctns[key], child_sctns...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def merge_numpy_napoleon_docs(prnt_doc=None, child_doc=None): """ Merge two numpy-style docstrings into a single docstring, according to napoleon docstring secti...
style = "numpy" return merge_all_sections(parse_napoleon_doc(prnt_doc, style), parse_napoleon_doc(child_doc, style), style)