_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q56400
RecordIndexer._index_action
train
def _index_action(self, payload): """Bulk index action. :param payload: Decoded message body. :returns: Dictionary defining an Elasticsearch bulk 'index' action. """ record = Record.get_record(payload['id']) index, doc_type = self.record_to_index(record) return ...
python
{ "resource": "" }
q56401
RecordIndexer._prepare_record
train
def _prepare_record(record, index, doc_type): """Prepare record data for indexing. :param record: The record to prepare. :param index: The Elasticsearch index. :param doc_type: The Elasticsearch document type. :returns: The record metadata. """ if current_app.con...
python
{ "resource": "" }
q56402
greedy_merge_helper
train
def greedy_merge_helper( variant_sequences, min_overlap_size=MIN_VARIANT_SEQUENCE_ASSEMBLY_OVERLAP_SIZE): """ Returns a list of merged VariantSequence objects, and True if any were successfully merged. """ merged_variant_sequences = {} merged_any = False # here we'll keep tr...
python
{ "resource": "" }
q56403
greedy_merge
train
def greedy_merge( variant_sequences, min_overlap_size=MIN_VARIANT_SEQUENCE_ASSEMBLY_OVERLAP_SIZE): """ Greedily merge overlapping sequences into longer sequences. Accepts a collection of VariantSequence objects and returns another collection of elongated variant sequences. The reads fie...
python
{ "resource": "" }
q56404
collapse_substrings
train
def collapse_substrings(variant_sequences): """ Combine shorter sequences which are fully contained in longer sequences. Parameters ---------- variant_sequences : list List of VariantSequence objects Returns a (potentially shorter) list without any contained subsequences. """ if...
python
{ "resource": "" }
q56405
iterative_overlap_assembly
train
def iterative_overlap_assembly( variant_sequences, min_overlap_size=MIN_VARIANT_SEQUENCE_ASSEMBLY_OVERLAP_SIZE): """ Assembles longer sequences from reads centered on a variant by between merging all pairs of overlapping sequences and collapsing shorter sequences onto every longer sequen...
python
{ "resource": "" }
q56406
groupby
train
def groupby(xs, key_fn): """ Group elements of the list `xs` by keys generated from calling `key_fn`. Returns a dictionary which maps keys to sub-lists of `xs`. """ result = defaultdict(list) for x in xs: key = key_fn(x) result[key].append(x) return result
python
{ "resource": "" }
q56407
ortho_basis
train
def ortho_basis(normal, ref_vec=None): """Generates an orthonormal basis in the plane perpendicular to `normal` The orthonormal basis generated spans the plane defined with `normal` as its normal vector. The handedness of `on1` and `on2` in the returned basis is such that: .. math:: ...
python
{ "resource": "" }
q56408
orthonorm_check
train
def orthonorm_check(a, tol=_DEF.ORTHONORM_TOL, report=False): """Checks orthonormality of the column vectors of a matrix. If a one-dimensional |nparray| is passed to `a`, it is treated as a single column vector, rather than a row matrix of length-one column vectors. The matrix `a` does not need to be ...
python
{ "resource": "" }
q56409
parallel_check
train
def parallel_check(vec1, vec2): """Checks whether two vectors are parallel OR anti-parallel. Vectors must be of the same dimension. Parameters ---------- vec1 length-R |npfloat_| -- First vector to compare vec2 length-R |npfloat_| -- Second vector to compare ...
python
{ "resource": "" }
q56410
proj
train
def proj(vec, vec_onto): """ Vector projection. Calculated as: .. math:: \\mathsf{vec\\_onto} * \\frac{\\mathsf{vec}\\cdot\\mathsf{vec\\_onto}} {\\mathsf{vec\\_onto}\\cdot\\mathsf{vec\\_onto}} Parameters ---------- vec length-R |npfloat_| -- Vector to projec...
python
{ "resource": "" }
q56411
rej
train
def rej(vec, vec_onto): """ Vector rejection. Calculated by subtracting from `vec` the projection of `vec` onto `vec_onto`: .. math:: \\mathsf{vec} - \\mathrm{proj}\\left(\\mathsf{vec}, \\ \\mathsf{vec\\_onto}\\right) Parameters ---------- vec length-R |npfloat_| ...
python
{ "resource": "" }
q56412
vec_angle
train
def vec_angle(vec1, vec2): """ Angle between two R-dimensional vectors. Angle calculated as: .. math:: \\arccos\\left[ \\frac{\\mathsf{vec1}\cdot\\mathsf{vec2}} {\\left\\|\\mathsf{vec1}\\right\\| \\left\\|\\mathsf{vec2}\\right\\|} \\right] Parameters -...
python
{ "resource": "" }
q56413
new_module
train
def new_module(name): """ Do all of the gruntwork associated with creating a new module. """ parent = None if '.' in name: parent_name = name.rsplit('.', 1)[0] parent = __import__(parent_name, fromlist=['']) module = imp.new_module(name) sys.modules[name] = module if pa...
python
{ "resource": "" }
q56414
allele_counts_dataframe
train
def allele_counts_dataframe(variant_and_allele_reads_generator): """ Creates a DataFrame containing number of reads supporting the ref vs. alt alleles for each variant. """ df_builder = DataFrameBuilder( AlleleCount, extra_column_fns={ "gene": lambda variant, _: ";".join(...
python
{ "resource": "" }
q56415
install_extension
train
def install_extension(conn, extension: str): """Install Postgres extension.""" query = 'CREATE EXTENSION IF NOT EXISTS "%s";' with conn.cursor() as cursor: cursor.execute(query, (AsIs(extension),)) installed = check_extension(conn, extension) if not installed: raise psycopg2.Prog...
python
{ "resource": "" }
q56416
check_extension
train
def check_extension(conn, extension: str) -> bool: """Check to see if an extension is installed.""" query = 'SELECT installed_version FROM pg_available_extensions WHERE name=%s;' with conn.cursor() as cursor: cursor.execute(query, (extension,)) result = cursor.fetchone() if result is ...
python
{ "resource": "" }
q56417
make_iterable
train
def make_iterable(obj, default=None): """ Ensure obj is iterable. """ if obj is None: return default or [] if isinstance(obj, (compat.string_types, compat.integer_types)): return [obj] return obj
python
{ "resource": "" }
q56418
CorpusReader.iter_documents
train
def iter_documents(self, fileids=None, categories=None, _destroy=False): """ Return an iterator over corpus documents. """ doc_ids = self._filter_ids(fileids, categories) for doc in imap(self.get_document, doc_ids): yield doc if _destroy: doc.destroy()
python
{ "resource": "" }
q56419
CorpusReader._create_meta_cache
train
def _create_meta_cache(self): """ Try to dump metadata to a file. """ try: with open(self._cache_filename, 'wb') as f: compat.pickle.dump(self._document_meta, f, 1) except (IOError, compat.pickle.PickleError): pass
python
{ "resource": "" }
q56420
CorpusReader._load_meta_cache
train
def _load_meta_cache(self): """ Try to load metadata from file. """ try: if self._should_invalidate_cache(): os.remove(self._cache_filename) else: with open(self._cache_filename, 'rb') as f: self._document_meta = compat.pickle.l...
python
{ "resource": "" }
q56421
CorpusReader._compute_document_meta
train
def _compute_document_meta(self): """ Return documents meta information that can be used for fast document lookups. Meta information consists of documents titles, categories and positions in file. """ meta = OrderedDict() bounds_iter = xml_utils.bounds(se...
python
{ "resource": "" }
q56422
CorpusReader._document_xml
train
def _document_xml(self, doc_id): """ Return xml Element for the document document_id. """ doc_str = self._get_doc_by_raw_offset(str(doc_id)) return compat.ElementTree.XML(doc_str.encode('utf8'))
python
{ "resource": "" }
q56423
CorpusReader._get_doc_by_line_offset
train
def _get_doc_by_line_offset(self, doc_id): """ Load document from xml using line offset information. This is much slower than _get_doc_by_raw_offset but should work everywhere. """ bounds = self._get_meta()[str(doc_id)].bounds return xml_utils.load_chunk(self.file...
python
{ "resource": "" }
q56424
_threeDdot_simple
train
def _threeDdot_simple(M,a): "Return Ma, where M is a 3x3 transformation matrix, for each pixel" result = np.empty(a.shape,dtype=a.dtype) for i in range(a.shape[0]): for j in range(a.shape[1]): A = np.array([a[i,j,0],a[i,j,1],a[i,j,2]]).reshape((3,1)) L = np.dot(M,A) ...
python
{ "resource": "" }
q56425
_swaplch
train
def _swaplch(LCH): "Reverse the order of an LCH numpy dstack or tuple for analysis." try: # Numpy array L,C,H = np.dsplit(LCH,3) return np.dstack((H,C,L)) except: # Tuple L,C,H = LCH return H,C,L
python
{ "resource": "" }
q56426
ColorSpace.rgb_to_hsv
train
def rgb_to_hsv(self,RGB): "linear rgb to hsv" gammaRGB = self._gamma_rgb(RGB) return self._ABC_to_DEF_by_fn(gammaRGB,rgb_to_hsv)
python
{ "resource": "" }
q56427
ColorSpace.hsv_to_rgb
train
def hsv_to_rgb(self,HSV): "hsv to linear rgb" gammaRGB = self._ABC_to_DEF_by_fn(HSV,hsv_to_rgb) return self._ungamma_rgb(gammaRGB)
python
{ "resource": "" }
q56428
ColorConverter.image2working
train
def image2working(self,i): """Transform images i provided into the specified working color space.""" return self.colorspace.convert(self.image_space, self.working_space, i)
python
{ "resource": "" }
q56429
ColorConverter.working2analysis
train
def working2analysis(self,r): "Transform working space inputs to the analysis color space." a = self.colorspace.convert(self.working_space, self.analysis_space, r) return self.swap_polar_HSVorder[self.analysis_space](a)
python
{ "resource": "" }
q56430
ColorConverter.analysis2working
train
def analysis2working(self,a): "Convert back from the analysis color space to the working space." a = self.swap_polar_HSVorder[self.analysis_space](a) return self.colorspace.convert(self.analysis_space, self.working_space, a)
python
{ "resource": "" }
q56431
load_chunk
train
def load_chunk(filename, bounds, encoding='utf8', slow=False): """ Load a chunk from file using Bounds info. Pass 'slow=True' for an alternative loading method based on line numbers. """ if slow: return _load_chunk_slow(filename, bounds, encoding) with open(filename, 'rb') as f: ...
python
{ "resource": "" }
q56432
generate_numeric_range
train
def generate_numeric_range(items, lower_bound, upper_bound): """Generate postgresql numeric range and label for insertion. Parameters ---------- items: iterable labels for ranges. lower_bound: numeric lower bound upper_bound: numeric upper bound """ quantile_grid = create_quantiles(ite...
python
{ "resource": "" }
q56433
edge_average
train
def edge_average(a): "Return the mean value around the edge of an array." if len(np.ravel(a)) < 2: return float(a[0]) else: top_edge = a[0] bottom_edge = a[-1] left_edge = a[1:-1,0] right_edge = a[1:-1,-1] edge_sum = np.sum(top_edge) + np.sum(bottom_edge) + ...
python
{ "resource": "" }
q56434
GenericImage._process_channels
train
def _process_channels(self,p,**params_to_override): """ Add the channel information to the channel_data attribute. """ orig_image = self._image for i in range(len(self._channel_data)): self._image = self._original_channel_data[i] self._channel_data[i] = s...
python
{ "resource": "" }
q56435
FileImage.set_matrix_dimensions
train
def set_matrix_dimensions(self, *args): """ Subclassed to delete the cached image when matrix dimensions are changed. """ self._image = None super(FileImage, self).set_matrix_dimensions(*args)
python
{ "resource": "" }
q56436
FileImage._load_pil_image
train
def _load_pil_image(self, filename): """ Load image using PIL. """ self._channel_data = [] self._original_channel_data = [] im = Image.open(filename) self._image = ImageOps.grayscale(im) im.load() file_data = np.asarray(im, float) file_da...
python
{ "resource": "" }
q56437
FileImage._load_npy
train
def _load_npy(self, filename): """ Load image using Numpy. """ self._channel_data = [] self._original_channel_data = [] file_channel_data = np.load(filename) file_channel_data = file_channel_data / file_channel_data.max() for i in range(file_channel_data....
python
{ "resource": "" }
q56438
kwargfetch.ok_kwarg
train
def ok_kwarg(val): """Helper method for screening keyword arguments""" import keyword try: return str.isidentifier(val) and not keyword.iskeyword(val) except TypeError: # Non-string values are never a valid keyword arg return False
python
{ "resource": "" }
q56439
run
train
def run(delayed, concurrency, version_type=None, queue=None, raise_on_error=True): """Run bulk record indexing.""" if delayed: celery_kwargs = { 'kwargs': { 'version_type': version_type, 'es_bulk_kwargs': {'raise_on_error': raise_on_error}, ...
python
{ "resource": "" }
q56440
reindex
train
def reindex(pid_type): """Reindex all records. :param pid_type: Pid type. """ click.secho('Sending records to indexing queue ...', fg='green') query = (x[0] for x in PersistentIdentifier.query.filter_by( object_type='rec', status=PIDStatus.REGISTERED ).filter( PersistentIdentif...
python
{ "resource": "" }
q56441
process_actions
train
def process_actions(actions): """Process queue actions.""" queue = current_app.config['INDEXER_MQ_QUEUE'] with establish_connection() as c: q = queue(c) for action in actions: q = action(q)
python
{ "resource": "" }
q56442
init_queue
train
def init_queue(): """Initialize indexing queue.""" def action(queue): queue.declare() click.secho('Indexing queue has been initialized.', fg='green') return queue return action
python
{ "resource": "" }
q56443
purge_queue
train
def purge_queue(): """Purge indexing queue.""" def action(queue): queue.purge() click.secho('Indexing queue has been purged.', fg='green') return queue return action
python
{ "resource": "" }
q56444
delete_queue
train
def delete_queue(): """Delete indexing queue.""" def action(queue): queue.delete() click.secho('Indexing queue has been deleted.', fg='green') return queue return action
python
{ "resource": "" }
q56445
variant_matches_reference_sequence
train
def variant_matches_reference_sequence(variant, ref_seq_on_transcript, strand): """ Make sure that reference nucleotides we expect to see on the reference transcript from a variant are the same ones we encounter. """ if strand == "-": ref_seq_on_transcript = reverse_complement_dna(ref_seq_on...
python
{ "resource": "" }
q56446
ReferenceSequenceKey.from_variant_and_transcript
train
def from_variant_and_transcript( cls, variant, transcript, context_size): """ Extracts the reference sequence around a variant locus on a particular transcript. Parameters ---------- variant : varcode.Variant transcript : pyensembl.Transcript ...
python
{ "resource": "" }
q56447
wrap
train
def wrap(lower, upper, x): """ Circularly alias the numeric value x into the range [lower,upper). Valid for cyclic quantities like orientations or hues. """ #I have no idea how I came up with this algorithm; it should be simplified. # # Note that Python's % operator works on floats and arra...
python
{ "resource": "" }
q56448
Line._pixelsize
train
def _pixelsize(self, p): """Calculate line width necessary to cover at least one pixel on all axes.""" xpixelsize = 1./float(p.xdensity) ypixelsize = 1./float(p.ydensity) return max([xpixelsize,ypixelsize])
python
{ "resource": "" }
q56449
Line._count_pixels_on_line
train
def _count_pixels_on_line(self, y, p): """Count the number of pixels rendered on this line.""" h = line(y, self._effective_thickness(p), 0.0) return h.sum()
python
{ "resource": "" }
q56450
Selector.num_channels
train
def num_channels(self): """ Get the number of channels in the input generators. """ if(self.inspect_value('index') is None): if(len(self.generators)>0): return self.generators[0].num_channels() return 0 return self.get_current_generator()....
python
{ "resource": "" }
q56451
PowerSpectrum._set_frequency_spacing
train
def _set_frequency_spacing(self, min_freq, max_freq): """ Frequency spacing to use, i.e. how to map the available frequency range to the discrete sheet rows. NOTE: We're calculating the spacing of a range between the highest and lowest frequencies, the actual segmentation and ...
python
{ "resource": "" }
q56452
get_postgres_encoding
train
def get_postgres_encoding(python_encoding: str) -> str: """Python to postgres encoding map.""" encoding = normalize_encoding(python_encoding.lower()) encoding_ = aliases.aliases[encoding.replace('_', '', 1)].upper() pg_encoding = PG_ENCODING_MAP[encoding_.replace('_', '')] return pg_encoding
python
{ "resource": "" }
q56453
OrcaOutput.en_last
train
def en_last(self): """ Report the energies from the last SCF present in the output. Returns a |dict| providing the various energy values from the last SCF cycle performed in the output. Keys are those of :attr:`~opan.output.OrcaOutput.p_en`. Any energy value not relevant to the ...
python
{ "resource": "" }
q56454
connect
train
def connect(host=None, database=None, user=None, password=None, **kwargs): """Create a database connection.""" host = host or os.environ['PGHOST'] database = database or os.environ['PGDATABASE'] user = user or os.environ['PGUSER'] password = password or os.environ['PGPASSWORD'] return psycopg2...
python
{ "resource": "" }
q56455
_setup
train
def _setup(): """ Set up module. Open a UDP socket, and listen in a thread. """ _SOCKET.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) _SOCKET.bind(('', PORT)) udp = threading.Thread(target=_listen, daemon=True) udp.start()
python
{ "resource": "" }
q56456
discover
train
def discover(timeout=DISCOVERY_TIMEOUT): """ Discover devices on the local network. :param timeout: Optional timeout in seconds. :returns: Set of discovered host addresses. """ hosts = {} payload = MAGIC + DISCOVERY for _ in range(RETRIES): _SOCKET.sendto(bytearray(payload), ('255.2...
python
{ "resource": "" }
q56457
S20._discover_mac
train
def _discover_mac(self): """ Discovers MAC address of device. Discovery is done by sending a UDP broadcast. All configured devices reply. The response contains the MAC address in both needed formats. Discovery of multiple switches must be done synchronously. :returns: ...
python
{ "resource": "" }
q56458
S20._subscribe
train
def _subscribe(self): """ Subscribe to the device. A subscription serves two purposes: - Returns state (on/off). - Enables state changes on the device for a short period of time. """ cmd = MAGIC + SUBSCRIBE + self._mac \ + PADDING_1 + self._mac_reve...
python
{ "resource": "" }
q56459
S20._control
train
def _control(self, state): """ Control device state. Possible states are ON or OFF. :param state: Switch to this state. """ # Renew subscription if necessary if not self._subscription_is_recent(): self._subscribe() cmd = MAGIC + CONTROL + self._mac...
python
{ "resource": "" }
q56460
S20._discovery_resp
train
def _discovery_resp(self, data): """ Handle a discovery response. :param data: Payload. :param addr: Address tuple. :returns: MAC and reversed MAC. """ if _is_discovery_response(data): _LOGGER.debug("Discovered MAC of %s: %s", self.host, ...
python
{ "resource": "" }
q56461
S20._subscribe_resp
train
def _subscribe_resp(self, data): """ Handle a subscribe response. :param data: Payload. :returns: State (ON/OFF) """ if _is_subscribe_response(data): status = bytes([data[23]]) _LOGGER.debug("Successfully subscribed to %s, state: %s", ...
python
{ "resource": "" }
q56462
S20._control_resp
train
def _control_resp(self, data, state): """ Handle a control response. :param data: Payload. :param state: Requested state. :returns: Acknowledged state. """ if _is_control_response(data): ack_state = bytes([data[22]]) if state == ack_state: ...
python
{ "resource": "" }
q56463
S20._udp_transact
train
def _udp_transact(self, payload, handler, *args, broadcast=False, timeout=TIMEOUT): """ Complete a UDP transaction. UDP is stateless and not guaranteed, so we have to take some mitigation steps: - Send payload multiple times. - Wait for awhile to receive re...
python
{ "resource": "" }
q56464
load
train
def load(source): """ Load OpenCorpora corpus. The ``source`` can be any of the following: - a file name/path - a file object - a file-like object - a URL using the HTTP or FTP protocol """ parser = get_xml_parser() return etree.parse(source, parser=parser).getroot()
python
{ "resource": "" }
q56465
translation_generator
train
def translation_generator( variant_sequences, reference_contexts, min_transcript_prefix_length, max_transcript_mismatches, include_mismatches_after_variant, protein_sequence_length=None): """ Given all detected VariantSequence objects for a particular variant ...
python
{ "resource": "" }
q56466
translate_variant_reads
train
def translate_variant_reads( variant, variant_reads, protein_sequence_length, transcript_id_whitelist=None, min_alt_rna_reads=MIN_ALT_RNA_READS, min_variant_sequence_coverage=MIN_VARIANT_SEQUENCE_COVERAGE, min_transcript_prefix_length=MIN_TRANSCRIPT_PREFIX_LENGTH,...
python
{ "resource": "" }
q56467
Translation.as_translation_key
train
def as_translation_key(self): """ Project Translation object or any other derived class into just a TranslationKey, which has fewer fields and can be used as a dictionary key. """ return TranslationKey(**{ name: getattr(self, name) for name in Tran...
python
{ "resource": "" }
q56468
Translation.from_variant_sequence_and_reference_context
train
def from_variant_sequence_and_reference_context( cls, variant_sequence, reference_context, min_transcript_prefix_length, max_transcript_mismatches, include_mismatches_after_variant, protein_sequence_length=None): """ Att...
python
{ "resource": "" }
q56469
Cachet.postComponents
train
def postComponents(self, name, status, **kwargs): '''Create a new component. :param name: Name of the component :param status: Status of the component; 1-4 :param description: (optional) Description of the component :param link: (optional) A hyperlink to the component :p...
python
{ "resource": "" }
q56470
Cachet.postIncidents
train
def postIncidents(self, name, message, status, visible, **kwargs): '''Create a new incident. :param name: Name of the incident :param message: A message (supporting Markdown) to explain more. :param status: Status of the incident. :param visible: Whether the incident is publicly...
python
{ "resource": "" }
q56471
Cachet.postMetrics
train
def postMetrics(self, name, suffix, description, default_value, **kwargs): '''Create a new metric. :param name: Name of metric :param suffix: Measurments in :param description: Description of what the metric is measuring :param default_value: The default value to use when a poin...
python
{ "resource": "" }
q56472
Cachet.postMetricsPointsByID
train
def postMetricsPointsByID(self, id, value, **kwargs): '''Add a metric point to a given metric. :param id: Metric ID :param value: Value to plot on the metric graph :param timestamp: Unix timestamp of the point was measured :return: :class:`Response <Response>` object :rt...
python
{ "resource": "" }
q56473
ctr_mass
train
def ctr_mass(geom, masses): """Calculate the center of mass of the indicated geometry. Take a geometry and atom masses and compute the location of the center of mass. Parameters ---------- geom length-3N |npfloat_| -- Coordinates of the atoms masses length-N OR len...
python
{ "resource": "" }
q56474
ctr_geom
train
def ctr_geom(geom, masses): """ Returns geometry shifted to center of mass. Helper function to automate / encapsulate translation of a geometry to its center of mass. Parameters ---------- geom length-3N |npfloat_| -- Original coordinates of the atoms masses length...
python
{ "resource": "" }
q56475
inertia_tensor
train
def inertia_tensor(geom, masses): """Generate the 3x3 moment-of-inertia tensor. Compute the 3x3 moment-of-inertia tensor for the provided geometry and atomic masses. Always recenters the geometry to the center of mass as the first step. Reference for inertia tensor: [Kro92]_, Eq. (2.26) .. t...
python
{ "resource": "" }
q56476
rot_consts
train
def rot_consts(geom, masses, units=_EURC.INV_INERTIA, on_tol=_DEF.ORTHONORM_TOL): """Rotational constants for a given molecular system. Calculates the rotational constants for the provided system with numerical value given in the units provided in `units`. The orthnormality tolerance `on_tol` is requi...
python
{ "resource": "" }
q56477
_fadn_orth
train
def _fadn_orth(vec, geom): """First non-zero Atomic Displacement Non-Orthogonal to Vec Utility function to identify the first atomic displacement in a geometry that is (a) not the zero vector; and (b) not normal to the reference vector. Parameters ---------- vec length-3 |npfloat_| -- ...
python
{ "resource": "" }
q56478
_fadn_par
train
def _fadn_par(vec, geom): """First non-zero Atomic Displacement that is Non-Parallel with Vec Utility function to identify the first atomic displacement in a geometry that is both (a) not the zero vector and (b) non-(anti-)parallel with a reference vector. Parameters ---------- vec ...
python
{ "resource": "" }
q56479
reference_contexts_for_variants
train
def reference_contexts_for_variants( variants, context_size, transcript_id_whitelist=None): """ Extract a set of reference contexts for each variant in the collection. Parameters ---------- variants : varcode.VariantCollection context_size : int Max of nucleotid...
python
{ "resource": "" }
q56480
variants_to_reference_contexts_dataframe
train
def variants_to_reference_contexts_dataframe( variants, context_size, transcript_id_whitelist=None): """ Given a collection of variants, find all reference sequence contexts around each variant. Parameters ---------- variants : varcode.VariantCollection context_size...
python
{ "resource": "" }
q56481
exponential
train
def exponential(x, y, xscale, yscale): """ Two-dimensional oriented exponential decay pattern. """ if xscale==0.0 or yscale==0.0: return x*0.0 with float_error_ignore(): x_w = np.divide(x,xscale) y_h = np.divide(y,yscale) return np.exp(-np.sqrt(x_w*x_w+y_h*y_h))
python
{ "resource": "" }
q56482
line
train
def line(y, thickness, gaussian_width): """ Infinite-length line with a solid central region, then Gaussian fall-off at the edges. """ distance_from_line = abs(y) gaussian_y_coord = distance_from_line - thickness/2.0 sigmasq = gaussian_width*gaussian_width if sigmasq==0.0: falloff =...
python
{ "resource": "" }
q56483
disk
train
def disk(x, y, height, gaussian_width): """ Circular disk with Gaussian fall-off after the solid central region. """ disk_radius = height/2.0 distance_from_origin = np.sqrt(x**2+y**2) distance_outside_disk = distance_from_origin - disk_radius sigmasq = gaussian_width*gaussian_width if ...
python
{ "resource": "" }
q56484
smooth_rectangle
train
def smooth_rectangle(x, y, rec_w, rec_h, gaussian_width_x, gaussian_width_y): """ Rectangle with a solid central region, then Gaussian fall-off at the edges. """ gaussian_x_coord = abs(x)-rec_w/2.0 gaussian_y_coord = abs(y)-rec_h/2.0 box_x=np.less(gaussian_x_coord,0.0) box_y=np.less(gaussi...
python
{ "resource": "" }
q56485
pack_tups
train
def pack_tups(*args): """Pack an arbitrary set of iterables and non-iterables into tuples. Function packs a set of inputs with arbitrary iterability into tuples. Iterability is tested with :func:`iterable`. Non-iterable inputs are repeated in each output tuple. Iterable inputs are expanded uniforml...
python
{ "resource": "" }
q56486
safe_cast
train
def safe_cast(invar, totype): """Performs a "safe" typecast. Ensures that `invar` properly casts to `totype`. Checks after casting that the result is actually of type `totype`. Any exceptions raised by the typecast itself are unhandled. Parameters ---------- invar (arbitrary) -- Va...
python
{ "resource": "" }
q56487
make_timestamp
train
def make_timestamp(el_time): """ Generate an hour-minutes-seconds timestamp from an interval in seconds. Assumes numeric input of a time interval in seconds. Converts this interval to a string of the format "#h #m #s", indicating the number of hours, minutes, and seconds in the interval. Intervals gr...
python
{ "resource": "" }
q56488
check_geom
train
def check_geom(c1, a1, c2, a2, tol=_DEF.XYZ_COORD_MATCH_TOL): """ Check for consistency of two geometries and atom symbol lists Cartesian coordinates are considered consistent with the input coords if each component matches to within `tol`. If coords or atoms vectors are passed that are of mismatched ...
python
{ "resource": "" }
q56489
template_subst
train
def template_subst(template, subs, delims=('<', '>')): """ Perform substitution of content into tagged string. For substitutions into template input files for external computational packages, no checks for valid syntax are performed. Each key in `subs` corresponds to a delimited substitution tag t...
python
{ "resource": "" }
q56490
assert_npfloatarray
train
def assert_npfloatarray(obj, varname, desc, exc, tc, errsrc): """ Assert a value is an |nparray| of NumPy floats. Pass |None| to `varname` if `obj` itself is to be checked. Otherwise, `varname` is the string name of the attribute of `obj` to check. In either case, `desc` is a string description of the...
python
{ "resource": "" }
q56491
tee_manager.advance
train
def advance(self): """Advance the base iterator, publish to constituent iterators.""" elem = next(self._iterable) for deque in self._deques: deque.append(elem)
python
{ "resource": "" }
q56492
SeparatedComposite._advance_pattern_generators
train
def _advance_pattern_generators(self,p): """ Advance the parameters for each generator for this presentation. Picks a position for each generator that is accepted by __distance_valid for all combinations. Returns a new list of the generators, with some potentially omitt...
python
{ "resource": "" }
q56493
Translator._advance_params
train
def _advance_params(self): """ Explicitly generate new values for these parameters only when appropriate. """ for p in ['x','y','direction']: self.force_new_dynamic_value(p) self.last_time = self.time_fn()
python
{ "resource": "" }
q56494
BaseSwitcher.register
train
def register(self, settings_class=NoSwitcher, *simple_checks, **conditions): """ Register a settings class with the switcher. Can be passed the settings class to register or be used as a decorator. :param settings_class: The class to register with the provided ...
python
{ "resource": "" }
q56495
Parser._peek_buffer
train
def _peek_buffer(self, i=0): """Get the next line without consuming it.""" while len(self._buffer) <= i: self._buffer.append(next(self._source)) return self._buffer[i]
python
{ "resource": "" }
q56496
Parser._make_readline_peeker
train
def _make_readline_peeker(self): """Make a readline-like function which peeks into the source.""" counter = itertools.count(0) def readline(): try: return self._peek_buffer(next(counter)) except StopIteration: return '' return readl...
python
{ "resource": "" }
q56497
Parser._add_node
train
def _add_node(self, node, depth): """Add a node to the graph, and the stack.""" self._topmost_node.add_child(node, bool(depth[1])) self._stack.append((depth, node))
python
{ "resource": "" }
q56498
OpanXYZ._load_data
train
def _load_data(self, atom_syms, coords, bohrs=True): """ Internal function for making XYZ object from explicit geom data. Parameters ---------- atom_syms Squeezes to array of N |str| -- Element symbols for the XYZ. Must be valid elements as defined in ...
python
{ "resource": "" }
q56499
OpanXYZ.geom_iter
train
def geom_iter(self, g_nums): """Iterator over a subset of geometries. The indices of the geometries to be returned are indicated by an iterable of |int|\\ s passed as `g_nums`. As with :meth:`geom_single`, each geometry is returned as a length-3N |npfloat_| with each atom's x/y...
python
{ "resource": "" }