content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def put_number(line_number, line): """ Return a string. The `line_number` is formatted as 3 digits number with a dot and a space preceding the `line`. The empty space before line number will be replaced by '0's. Example: >>> put_number(1, "Hello World!") '001. Hello World' """ retur...
25f8a34aa7de91060b852ba86df44b12019802b7
668,219
def flip_bit(bit: str) -> str: """returns the input bit flipped""" assert bit == "0" or bit =="1" return "0" if bit =="1" else "1"
52eb5f77c9787c529e185c8894259306150b38e5
668,222
def clamp(number, min, max): """Returns number limited to range specified by min and max, inclusive""" if number < min: return min elif number > max: return max else: return number
3f9b6cc60f4e5bad805c569b14adb3ef6a047943
668,232
import json def read_json(file_path: str) -> dict: """Reads a json file and returns the dict """ with open(file_path) as f: return json.load(f)
93df73379300052dbecc6706050b0779ac568b98
668,236
def username(user: dict): """ Returns the user's first and last name if they've seen set, else returns the user's email """ if user["first_name"]: return user["first_name"] + " " + user["last_name"] return user["email"]
19f7a4d47677fa1217c03f61f867c7704194f2bc
668,237
import torch def get_masks(slen, lengths, causal): """ Generate hidden states mask, and optionally an attention mask. """ assert lengths.max().item() <= slen bs = lengths.size(0) alen = torch.arange(slen, dtype=torch.long, device=lengths.device) mask = alen < lengths[:, None] # attent...
f71942a5d089372e8bbff6d08b8dab9df86e375a
668,238
import functools def middleware(f): """Function decorator for making WSGI middlewares.""" return functools.update_wrapper( lambda app: lambda wsgi_env, start_resp: f(app, wsgi_env, start_resp), f)
33576f9bc905e5abc673e442198a19db4b43539f
668,241
def conflateable(seg1, seg2, segment_pairs): """ Return True iff seg1 and seg2 are exactly one of the segment pairs in segment_pairs (ignoring ordering of either). seg1 and seg2 will never be identical in the input. Parameters ---------- seg1, seg2: Segment Two segments on which m...
8444f5e0811bf410675e2bae300f9f58e400c31c
668,244
def norm3d(x, y, z): """Calculate norm of vector [x, y, z].""" return (x * x + y * y + z * z) ** 0.5
c61e9e1fb53986b20da60899a4464e8b914f0068
668,246
def vel_final_dist_helper(initial_velocity, acceleration, dist): """ Calculates the final velocity given the initial velocity, acceleration and the distance traveled. And is a helper function to be called by vel_final_dist() :param initial_velocity: Integer initial velocity :param acceleration:...
74cc521b37a58ffc766bb3fc1a9a7ad80fcfe35e
668,256
def with_metaclass(metaclass, *bases): """ Construct a base class with metaclass compatible with python2 and python3. Usage: ``` class(with_metaclass(metaclass, base1, base2...)): .... ``` """ class InterposedMetaClass(metaclass): def __new__(mcls, name, new_bases, attr...
731d40d481c4f9b18ba5dbfa0bf42cf5e9d019d3
668,264
import pickle def _read_results(pickle_file_name): """Reads results from Pickle file. :param pickle_file_name: Path to input file. :return: monte_carlo_dict: Dictionary in format created by `monte_carlo.run_monte_carlo_test`. """ pickle_file_handle = open(pickle_file_name, 'rb') mont...
604a2f5eb99e00d33d9262c5680ae67f2be488b4
668,271
def _no_stop_codon(aa_seq): """ Returns True if a sequence does not contain a stop codon, otherwise returns False """ if '*' not in aa_seq: return True else: return False
b48d3169d6403bc69782dede504af3962ee7d6bf
668,272
def get_categories_used_ordered(ordered_categories, used_categories) -> list: """Returns an ordered list of categories that appear in used_categories. * ordered_categories: manually defined ordered list * used_categories: a list or set of categories actually used in the data frame """ used_set = set...
0b436235aa2a82963bdde170d07b8a4d6a9d74cf
668,273
def RK4n(diffeq, y0, t, h): # non-vectorized with lists """ RK4 method for n ODEs: Given y0 at t, returns y1 at t+h """ n, y1 = len(y0), [0.0]*len(y0) k1 = diffeq(y0, t) # dy/dt at t for i in range(n): # loop thru n ODEs y1[i] = y0[i] + 0....
d3f34ddf84b3326de86ee62c04793ace4a841105
668,275
import re def get_new_version(version): """ Get new version by bumping only the last digit group in the string. Args: version (): Version: like 2.7.epic14859_9 Returns: New version: like 2.7.epic14859_10 Original credit: https://stackoverflow.com/questions/23820883/incrementing-the-last-d...
7c3bd2fe08852b75b543fb59f33aaa1af876743c
668,276
def motif_factors(m, M): """ Generates the set of non redundant motif sizes to be checked for division rule. Parameters ---------- m : <int> minimum motif size M : <int> maximum motif size Returns ------- factors : <list> sorted(descending) list of non-redundant motifs. ""...
f2dd9eaebc4db7d947031b49d9c494a47dd4ce9f
668,279
def parse_id(arg): """ Parses an ID from a discord @ :param arg: @ or ID passed :return: ID """ if "<" in arg: for i, c in enumerate(arg): if c.isdigit(): return int(arg[i:-1]) # Using ID else: return int(arg)
3171c4a9ae0a06d674109b50d7fc806905ef03ee
668,283
def dict_merge(base, override): """Recursively merge two dictionaries Parameters ---------- base : dict Base dictionary for merge override : dict dictionary to override values from base with Returns ------- dict Merged dictionary of base and overrides """ ...
ab35c0e4f9f72bd31855212354d6d91402dcd651
668,284
def get_eids_from_op2_vector(vector): """Obtain the element ids for a given op2 vector Parameters ---------- vector : op2 vector An op2 vector obtained, for example, doing:: vector = op2.cquad4_force[1] vector = op2.cquad8_stress[1] vector = op2.ctriar_force...
248a7b19829a59438ca74cc3fbdaf89dd8b7e240
668,288
def get_index_basename() -> str: """Get the basename for a streaming dataset index. Returns: str: Basename of file. """ return 'index.mds'
7dee083f01693c3bc64260f2b67f619425661eb0
668,289
def convert_subscripts(old_sub, symbol_map): """Convert user custom subscripts list to subscript string according to `symbol_map`. Examples -------- >>> oe.parser.convert_subscripts(['abc', 'def'], {'abc':'a', 'def':'b'}) 'ab' >>> oe.parser.convert_subscripts([Ellipsis, object], {object:'a'}) ...
4a97647cb14726ba3b0bc109c626b8c8cc1b5815
668,294
from typing import Dict from typing import Any def _str_none(dct: Dict[str, Any]) -> Dict[str, Any]: """Make all the None value to string 'none'.""" return {key: "none" if value is None else value for key, value in dct.items()}
2306e9d1e82715cddc228654aed557d8c05947d3
668,302
import re def re_filter(text, regexps): """Filter text using regular expressions.""" if not regexps: return text matched_text = [] compiled_regexps = [re.compile(x) for x in regexps] for line in text: if line in matched_text: continue for regexp in compiled_re...
fda62371c36ac43e1a6186a7f4ae4ca1a809f73a
668,309
def getAddressSuggestions(connection, pattern, limit): """Fetching address suggestions for a given search pattern Parameters ---------- connection : psygopg2.connection psycopg2 connection object pattern : str search pattern limit : int maximum number of suggestions to r...
a699a8368f3dbfda51fe42aaaff848938c5d8361
668,312
def _cvtfield(f): """ If str passed in via 'f' parameter is '-' then return empty string otherwise return value of 'f' :param f: :return: empty string if 'f' is '-' otherwise return 'f' :rtype: str """ if f is None or f != '-': return f return ''
f7e953cb856824cb9f8cc720bac90a60874bb3d8
668,314
def to_power_three(number): """ Returns the number to the power of three. :param number: The number :return: The number to the power of three """ return number ** 3
7adb7ccaee8027d26f0e49b86755242b0df599e1
668,315
def VARIANCE(src_column): """ Builtin variance aggregator for groupby. Synonym for tc.aggregate.VAR Example: Get the rating variance of each user. >>> sf.groupby("user", ... {'rating_var':tc.aggregate.VARIANCE('rating')}) """ return ("__builtin__var__", [src_column])
28b92e302b2c20fa5bc34e84ad2bf86721ad9724
668,316
def _trim_ds(ds, epochs): """Trim a Dataset to account for rejected epochs. If no epochs were rejected, the original ds is rturned. Parameters ---------- ds : Dataset Dataset that was used to construct epochs. epochs : Epochs Epochs loaded with mne_epochs() """ if len(e...
0e08273d86188b8572d0b26feea992771694feb8
668,317
def PIsA (inImage): """ Tells if input really a Python Obit ImageMF return True, False * inImage = Python Image object """ ################################################################ try: return inImage.ImageMFIsA()!=0 except: return False # end PIsA
6b87c13bf7a6404fc8faa215c9605fb4e9f31463
668,318
def linear_sieve(max_n): """Computes all primes < max_n and lits of all smallest factors in O(max_n) time Returns ------- primes: list of all primes < max_n smallest_factors: list such that if q = smallest_factors[n], then n % q == 0 and q is minimal. """ smallest_factors = [0] ...
5a368ac0bca50cbdf82f9c41db689e1536ab463a
668,322
def apply_threshold(heatmap, threshold): """ Apply threshold to the heatmap to remove false positives. Parameters: heatmap: Input heatmap. threshold: Selected threshold. """ heatmap[heatmap < threshold] = 0 return heatmap
a62a5bba0606f2b9b1ca42e3360cbbb6e4f85c78
668,329
def get_number_rows(ai_settings,ship_height,alien_height): """determine the number of rows of aliens that fits on a screen""" available_space_y=(ai_settings.screen_height - (5 * alien_height)-ship_height) number_rows=int(available_space_y/(2 * alien_height)) return number_rows
b0b7b59456c24969b03b5996c8e6dc54bc2c2077
668,331
def split_schema_obj(obj, sch=None): """Return a (schema, object) tuple given a possibly schema-qualified name :param obj: object name or schema.object :param sch: schema name (defaults to 'public') :return: tuple """ qualsch = sch if sch is None: qualsch = 'public' if '.' in ob...
050900ce3bbe761dfde3ae131bf2576354a7b536
668,332
from functools import reduce def a2bits(chars: str) -> str: """Converts a string to its bits representation as a string of 0's and 1's. >>> a2bits("Hello World!") '010010000110010101101100011011000110111100100000010101110110111101110010011011000110010000100001' """ return bin(reduce(lambda x, y: ...
c155a9ad2b0e704d1cc3a981d10d9be1ac2e905a
668,333
def get_all_combinations(node_lists): """ Generate a list of all possible combinations of items in the list of lists `node_lists`. Each combination takes one item from each list contained within `node_lists`. The order of items in the returned lists reflects the order of lists in `node_lists`. For e...
31531dfc77e6ccda9c9c26b62193669d9c346a34
668,334
def recover_flattened(flat_params, indices, model): """ Gives a list of recovered parameters from their flattened form :param flat_params: [#params, 1] :param indices: a list detaling the start and end index of each param [(start, end) for param] :param model: the model that gives the params with co...
13f264cd16a43da9cae0e0967340e95d2ae4f647
668,337
def make_dict(keys, values): """ Returns a dictionary that maps keys to values correspondingly. Assume inputs are of same length. """ return dict(zip(keys,values))
cdf80e785d21b665250ec8b902721f6db8b48baf
668,338
import re def extract_phrases(text): """ extract phrases, i.e. group of continuous words, from text """ return re.findall('\w[\w ]+', text, re.UNICODE)
a0016b40b1b9a16d5928f3314a7db8de1e20bfd2
668,339
def dict_reorder(item: dict) -> dict: """ Sorts dict by keys, including nested dicts :param item: dict to sort """ if isinstance(item, dict): item = {k: item[k] for k in sorted(item.keys())} for k, v in item.items(): if isinstance(v, dict): item[k] = dict_...
8d756a5c19b62294db6369ae2a5b007ad33cc297
668,340
def normalize_name(name): """Capitalize all words in name.""" words = name.split() res = "" for w in words: if res != "": res += " " res += w.capitalize() return res
8cd80a37e0fc8efe89dbbb30309c74e63395351b
668,345
def get_date_formatted(date): """ Return the date in the format: 'YEAR-MONTH-DAY' """ year = str(date.year) month = str(date.month) day = str(date.day) single_digits = range(1, 10) if date.month in single_digits: month = '0' + month if date.day in single_digits: d...
6b4699460150b2d90326f29d6a22617e4e3ffdfe
668,347
import jinja2 def render_happi_template_arg(template, happi_item): """Fill a Jinja2 template using information from a happi item.""" return jinja2.Template(template).render(**happi_item)
79aa02a9a37bf23806abc527f0f896a365db72b9
668,349
def getParentPath(path): """Get the parent path from C{path}. @param path: A fully-qualified C{unicode} path. @return: The C{unicode} parent path or C{None} if C{path} represents a root-level entity. """ unpackedPath = path.rsplit(u'/', 1) return None if len(unpackedPath) == 1 else unpa...
3b844b80b716e7dac482a891bc83245f1163f5bb
668,350
def two2one(x, y): """Maps a positive (x,y) to an element in the naturals.""" diag = x + y bottom = diag * (diag + 1) / 2 return bottom + y
352b514579de48128ef1abe97dfce37b8a0fff5c
668,352
def get_complementary_orientation(orientation): """Used to find the outcoming orientation given the incoming one (e.g. N -> S; E-> W; S -> N; W -> E).""" return (orientation + 2) % 4
98331ecddffd39041aaa2d3086e0f3dc21d7061f
668,354
import requests def send_token_request(form_values, add_headers={}): """Sends a request for an authorization token to the EVE SSO. Args: form_values: A dict containing the form encoded values that should be sent with the request add_headers: A dict containing additional h...
f9c00e7f598db20c69fe6bf44f3df7100ef974b8
668,355
def _get_previous_month(month, year): """Returns previous month. :param month: Month (integer from 1...12). :param year: Year (integer). :return: previous_month: Previous month (integer from 1...12). :return: previous_year: Previous year (integer). """ previous_month = month - 1 if pr...
958775c5ce23e6550f54104c1390673a913f7ff1
668,357
import math def get_rows_cols_for_subplot(num_subplots:int)->tuple: """ This function calculates the rows and cols required for the subplot.. Args: num_subplots:int Returns: nrows:int ncols:int odd:bool """ try: nrows=ncols=0 o...
3572c31b988dbec99d339039edfacc7ed246a008
668,359
def strip_surrounding(word): """ Strip spaces in the front or back of word. :param word: A word (or sentence) of which we want to strip the surrounding spaces. :return: A string that doesn't start or end with a space. """ while word and (word[0] != ' ' or word[-1] != ' '): if word[0] ==...
eacb57971e0c4ada9b7ed16c70e084cc855210f4
668,360
import itertools def run_length_encode(tags_to_encode): """Perform run length encoding. Args: tags_to_encode: A string, usually of DeletionTags. Returns: the RLE string. For example, if the input was NNNNNCNNTTC, the function would return 5N1C2N2T1C """ rle_list = [(...
737b574618761f5a56a2390055b935beec8bbc6b
668,361
def assign_x_coord(row): """ Assigns an x-coordinate to Statcast's strike zone numbers. Zones 11, 12, 13, and 14 are ignored for plotting simplicity. """ # left third of strik zone if row.zone in [1,4,7]: return 1 # middle third of strike zone if row.zone in [2,5,8]: ret...
76a7e3957e945803fe2b7467ca776586d5c74580
668,364
def dsf_func(d50, theta ): """ Calculate sheet flow thickess Input: d50 - median grain size (m) Theta - maximum (crest or trough) Shields paramter Returns: dsf - thickness of sheet flow layer (m) Based on Janssen (1999) in van der A et al. (2013), Appendix C. See also Do...
711f64bb1de1112dc8da9d3b1e37bbf9405e9f8d
668,377
import torch def MM_mult(x, y): """A function that returns x*y, where x and y are complex tensors. :param x: A complex matrix. :type x: torch.doubleTensor :param y: A complex matrix. :type y: torch.doubleTensor :raises ValueError: If x and y do not have 3 dimensions or their first dimens...
82c8ca0e808209b3b5826345574842350496d641
668,380
def id(left_padding=None, right_padding=None, offset=None): """Constructs an implicit-duration spec dictionary.""" result = {} if left_padding is not None: result['left_padding'] = left_padding if right_padding is not None: result['right_padding'] = right_padding if offset is no...
a6b729fa8bdda22ef660854abb0e5ffcb5dec85d
668,382
def isac(c): """ A simple function, which determine whether the string element char c is belong to a decimal number :param c: a string element type of char :return: a bool type of determination """ try: int(c) return True except: if c == '.' or c == '-' or c == 'e...
a88d6f22db61c13858edda4efddfa9bbcb7e31c6
668,387
import math def rhs(y1, y2): """ RHS function. Here y1 = u, y2 = u' This means that our original system is: y2' = u'' = -0.25*pi**2 (u+1) """ dy1dx = y2 dy2dx = -0.25*math.pi**2 * (y1 + 1.0) return dy1dx, dy2dx
8b17eceafcc28918e4c3b7e45be9d43b0a156b84
668,388
from typing import Optional def load_current_user(request_context) -> Optional[str]: """Load the current user from the request.""" if (authorizer := request_context.get("authorizer")) is not None: claims = authorizer.get("claims", {}) return claims.get("sub") return None
5d2631f21c458711b51a935ecef6f4a827c49dab
668,393
def process_subset(subset, separator="\t"): """Processes the given subset. Extracts the input tokens (words) and labels for each sequence in the subset. Forms a representation string for each sample in the following format: SEQ_LEN [SEPARATOR] INPUT_TOKENS [SEPARATOR] LABELS where: ...
2058b8094ee4384950838ec4344c95e10ee5c409
668,394
def fibonacci(count:int)->list: """ This function takes a count an input and generated Fibonacci series element count equal to count # input: count : int # Returns list # Funcationality: Calcualtes the sum of last two list elements and appends it to the list until ...
f34e3ec56e3252991ab707d54bcda8c8cc371cdd
668,397
def parse_row(row, cols, sheet): """ parse a row into a dict :param int row: row index :param dict cols: dict of header, column index :param Sheet sheet: sheet to parse data from :return: dict of values key'ed by their column name :rtype: dict[str, str] """ vals = {} for header, ...
580afc8d38f1ea2ce13fa9ccdc5c75e56860a97c
668,398
from typing import Mapping from typing import Any from typing import Tuple def gate_boundaries(gate_map: Mapping[str, Any]) -> Mapping[str, Tuple[float, float]]: """ Return gate boundaries Args: gate_map: Map from gate names to instrument handle Returns: Dictionary with gate boundaries ...
4c9c8e8c3f7a5f2591c73de2f97da74321c02e1f
668,399
def get_name(s, isconj=False): """Parse variable names of form 'var_' as 'var' + conjugation.""" if not type(s) is str: if isconj: return str(s), False else: return str(s) if isconj: return s.rstrip("_"), s.endswith("_") # tag names ending in '_' for conj ...
9648a8b206a107f91784bd2caea1f7b9d312c5e3
668,400
def hide_string_content(s): """ Replace contents of string literals with '____'. """ if (not isinstance(s, str)): return s if ('"' not in s): return s r = "" start = 0 while ('"' in s[start:]): # Out of string. Add in as-is. end = s[start:].index('"')...
331c80b314a5644190aec6f9031a2df4b5f61f85
668,401
from pathlib import Path def get_files_by_pattern(directory: str, glob_pattern: str) -> list[Path]: """Return list of files matching pattern""" path = Path(directory) return [file for file in path.glob(glob_pattern) if file.is_file()]
be1ce3e9e92cf5694e8ac1ee1c8fde9e7fada835
668,405
def calc_num_beats(rpeak_locs, metrics): """Calculates the number of beats in an ECG This function takes an array of the ECG R-peaks. The number of R-peaks is equivalent to the number of beats in the ECG. Args: rpeak_locs (1D numpy array): index locations of R-peaks in an ECG. metrics ...
41399a0629aa8b527b46c5eeb3dd76d696ad304f
668,407
def _get_revision(config): """ Extracts branch and revision number from the given config parameter. @return: (branch, revision number) """ if config.revision: tokens = config.revision.split(":") svn_branch = tokens[0] if len(tokens) > 1: revision = config.revision...
f6ca9df0c80727fa449e6aafdf1132113a7e9c43
668,408
def get_header(token): """ Return a header with authorization info, given the token. """ return { 'Authorization': 'token %s' % token, 'Content-Type': 'application/json; charset=UTF-8' }
1b693a758eb33343d390f8f5b0dee49a195bbce4
668,409
def determine_color(memory_limit_gb, memory_usage_gb, dark_background=False): """Determine a display color based on percent memory usage Parameters ---------- memory_limit_gb : int Overall memory limit in gigabytes memory_usage_gb : int Memory usage value in gigabytes dark_b...
066b8aad7e413a391e6e8c50eae12863e09f7a7b
668,410
from typing import List def count_user_type(user_type_list:List[str]) -> List[int]: """ Calcula a quantidade de Clientes e Assinantes. Por meio de uma lista calcula a quantidade de clientes "Customer" e assinantes "Subscriber". :param data_list: Lista contendo os tipos de usuário. :returns: Lista de ...
1b1007da0e0d75bc5cf795359bc5199c6215c078
668,413
def datetime_to_float(datetime): """ SOPC_DateTime* (the number of 100 nanosecond intervals since January 1, 1601) to Python time (the floating point number of seconds since 01/01/1970, see help(time)). """ nsec = datetime[0] # (datetime.date(1970,1,1) - datetime.date(1601,1,1)).total_seconds() ...
6698c6cc02c8c34394bcf960d540f417e6422def
668,418
def regularize_reliability(rel_1, rel_2): """ Regularizes the reliability estimates for a pair of graders. Parameters ---------- rel_1 : float. Estimated reliability of grader 1. rel_2 : float. Estimated reliability of grader 2. Returns ------- t_1 : float...
b62fb831c3ccbd9bb232d75b4b9ee0b802f89f14
668,419
def cs_rad(altitude, ext_rad): """ Estimate clear sky radiation from altitude and extraterrestrial radiation. Based on equation 37 in Allen et al (1998) which is recommended when calibrated Angstrom values are not available. :param altitude: Elevation above sea level [m] :param ext_rad: Extrat...
fbe5cf144b3ecf0b34e55522ca87dd49bf74dd5e
668,425
from typing import List import pathlib def get_core_lists() -> List[pathlib.Path]: """Return a list of paths for all rutrivia lists packaged with the bot.""" core_lists_path = pathlib.Path(__file__).parent.resolve() / "data/lists" return list(core_lists_path.glob("*.yaml"))
5466290d98bc42e8198ad49686224f4f36bbd650
668,427
def is_string_type(thetype): """Returns true if the type is one of: STRING, TIMESTAMP, DATE, or TIME.""" return thetype in [ 'STRING', 'TIMESTAMP', 'DATE', 'TIME', 'QINTEGER', 'QFLOAT', 'QBOOLEAN' ]
b6f010d0b12bf5452635be81d11b89fde074af39
668,430
import hashlib def convert_data_set(data_set, data_set_writer, transformation=None, count_dist=False, prime_wise=False, remove_duplicities=False): """ Convert data set to a different format. If transformation is provided, compute features and add them to the key key that gets sav...
d3e4fd627f8ce2328fafa63021291ab260a16efe
668,433
def get_picam(c): """ Return a dict of the attributes in a PiCamera""" d = {} if type(c).__name__ == "PiCamera": all_settings = ['analog_gain', 'awb_mode', 'awb_gains', 'contrast', 'drc_strength', 'digital_gain', 'exposure_mode', 'exposure_speed', 'framerate', 'hflip', 'iso',...
f24b87e81fe094dc0df874585ef890d76453a7f7
668,434
def get_engine_turbo(t): """ Function to get turbo or regular for engine type """ tt = t.split(" ")[-1] if "turbo" in tt: return "turbo" return "regular"
faae5a1e3005c54591366306869e9d22bd5f500c
668,438
def _getMultiElemText(parentElem, elemName, topKey, bottomKey): """ XML parsing helper function to return a 2-level :py:class:`dict` of multiple elements by a specified name, using ``topKey`` as the first key, and ``bottomKey`` as the second key. :param SubElement parentElem: the :py:class:`XML SubElem...
59b886995189e3b1a8fbf0d50e3dbb4fe6af3474
668,446
def is_point_in_range(p, p_min=None, p_max=None) -> bool: """Check if point lays between two other points. Args: p: tuple (x, y) p_min (optional): min border point p_max (optional): max border point Returns: True if p_max >= p >= p_min """ if p_min is None and p_max...
5c86a40a936bb5e979edc63add5cc0415ff5d444
668,449
def even(x): """ even :: Integral a => a -> Bool Returns True if the integral value is even, and False otherwise. """ return x % 2 == 0
b298173d03658bbc5be7df5b343e363dcdd93647
668,450
def split_estimates(df, org): """Split the passed dataframe into either Sakai or DH10B subsets""" if org == 'dh10b': subset = df.loc[df['locus_tag'].str.startswith('ECDH10B')] else: subset = df.loc[~df['locus_tag'].str.startswith('ECDH10B')] return subset
a4a13c29f6f5729d57003a5b45af99c57f34949c
668,451
def only_true(*elts): """Returns the sublist of elements that evaluate to True.""" return [elt for elt in elts if elt]
48e84744946dad669fae2312682fe938dd118d9f
668,455
def is_prime(n: int) -> bool: """ Checks if n is a prime number """ if n < 1: return False for i in range(2, n // 2): if n % i == 0: return False return True
ba2f14cdf1d18d34a1e19060b8e0cfa5c121dde4
668,465
def valid_ipv4_host_address(host): """Determine if the given host is a valid IPv4 address.""" # If the host exists, and it might be IPv4, check each byte in the # address. return all([0 <= int(byte, base=10) <= 255 for byte in host.split('.')])
e0796d4334ee1985391f21ea421a34faf0d3bfc7
668,469
def format_sex_string(sex_str): """ Converts 'M', 'F', or else to 'male', 'female', or empty string (e.g. ''). Args: sex_str (str): String consisting of 'M', 'F', '', or None. Returns: str: 'M', 'F', or '' """ if sex_str == "M": sex = "male" elif sex_str == "F": ...
415aab0d3fd38e6bfb18e658564faeb51f852a4a
668,470
def mandel(x, y, max_iters): """ Given the real and imaginary parts of a complex number, determine if it is a candidate for membership in the Mandelbrot set given a fixed number of iterations. """ c = complex(x, y) z = 0.0j for i in range(max_iters): z = z*z + c if (z.r...
988f34156365551631eb926da2e1d5e08faff4f0
668,473
def one_or_more(string): """ A regex wrapper for an arbitrary string. Allows an arbitrary number of successive valid matches (at least one) to be matched. """ return r'(?:{:s}){{1,}}'.format(string)
45397b292b1f472138c9b757458d7743a13b3d93
668,478
def get_explict_dest(pdf, dest_list): """ Find explict destination page number and rectangle. :param pdf: pdfplumber.pdf.PDF object :param dest_list: A explict destination list, e.g. [page, /XYZ, left, top, zoom] :return: A list of destination contains page number and rectangle coordinates """ ...
e6f2abebc2c036ad3f1b3f8a42259b3805b64f02
668,482
def get_elev_abbrev(cell): """ Parse elevation and station abbreviation. """ tc = cell.text_content().strip() return int(tc[:-6]), tc[-4:-1]
01c32c5e57a4f8a55fe0eae8b1525f0eb2941d9d
668,484
import json def str_format_dict(jdict, **kwargs): """Pretty-format a dictionary into a nice looking string using the `json` package. Arguments --------- jdict : dict, Input dictionary to be formatted. Returns ------- jstr : str, Nicely formatted string. """ kwarg...
15c24c57c9d59bfa01a914755165a00c9922bbff
668,489
from typing import Optional import re def _normalize(x: Optional[str]) -> Optional[str]: """ Normalize string to lowercase, no whitespace, and no underscores. Examples -------- >>> _normalize('Offshore Wind') 'offshorewind' >>> _normalize('OffshoreWind') 'offshorewind' >>> _normal...
3b5daf8bda7708e9fa2b5124c4738a4d469e8ddc
668,491
def AddAssay(adata, data, key, slot="obsm"): """Add a new data as a key to the specified slot Parameters ---------- adata: :AnnData AnnData object data: `pd.DataFrame` The data (in pandas DataFrame format) that will be added to adata. key: `str` T...
1f34fc40b338e755983bbc551a565b4af23dfb9b
668,495
def create_mosaic_pars(mosaic_wcs): """Return dict of values to use with AstroDrizzle to specify output mosaic Parameters ----------- mosaic_wcs : object WCS as generated by make_mosaic_wcs Returns -------- mosaic_pars : dict This dictionary can be used as input to astrodri...
e9a8a499ce3a9196fcaf4f57c4bda4aa25905655
668,496
import math def cent_diff(freq1, freq2): """Returns the difference between 2 frequencies in cents Parameters ---------- freq1 : float The first frequency freq2 : float The second frequency Returns ------- float The difference between the 2 frequencies """...
e08a8579afaf534c99d772e8e098f13d4b8ed371
668,497
def class_in_closure(x): """ >>> C1, c0 = class_in_closure(5) >>> C1().smeth1() (5, ()) >>> C1.smeth1(1,2) (5, (1, 2)) >>> C1.smeth1() (5, ()) >>> c0.smeth0() 1 >>> c0.__class__.smeth0() 1 """ class ClosureClass1(object): @staticmethod def smeth1(*...
94c203f2d6b8cfcccc6ac5b1234000dd6fca65d0
668,500
def _get_obj_file(ctx, src): """Returns the obj file for the given src.""" extension_index = src.short_path.rindex(".c") obj_file = src.short_path[0:extension_index] + ".o" return ctx.new_file(obj_file)
3b36875c0d87be630077017163ffd3900c7d87b3
668,505
def find_nested_parentheses(string): """ An equation that could contain nested parentheses :param str string: An equation to parse :return: A dict with the indexes of opening/closing parentheses per nest level :rtype: dict """ indexes = {} nested_level = 0 for i, char in enumerate(st...
cdf8bf428e396c087a7d0e0caa33651653007373
668,510
def _append_ns(in_ns, suffix): """ Append a sub-namespace (suffix) to the input namespace :param in_ns Input namespace :type in_ns str :return: Suffix namespace :rtype: str """ ns = in_ns if ns[-1] != '/': ns += '/' ns += suffix return ns
fdd6378538cc3045463fbe981acaa3d03a7f7adc
668,512
def render(line, prefix_arg=None, color=-1): """ Turn a line of text into a ready-to-display string. If prefix_arg is set, prepend it to the line. If color is set, change to that color at the beginning of the rendered line and change out before the newline (if there is a newline). :param str lin...
c2526f48def3fb528d87b47dd38aa88b8e08b2ba
668,517