content
stringlengths
42
6.51k
def count_capital_letters(x): """ Extract number of captial letters in a string """ try: return sum([s.isupper() for s in list(str(x))]) except Exception as e: print(f"Exception raised:\n{e}") return 0
def filter_plot_layout(num_of_filters): """Calculate a nice layout for a set of filters to be plotted with `plot_filters`. This function returns a tuple containing the number of plots per row in each of the rows that are produced via a call to `plot_filters`. >>> filter_plot_layout(7) (4, 3) ...
def compute_r_precision(real_gains, predicted_gains, k=5, positive_only=False): """This function computes R-precision, which is the ratio between all the relevant documents retrieved until the rank that equals the number of relevant documents you have in your collection in total (r), to the total number o...
def merge_vcfs(vcf_file, merged_mut_file): """ This module will accept the vcf files for mutect and radia read into memory in a dict object VCF_FILE and will merge the calls. Merged calls are printed to MERGED_MUT_FILE. VCF_FILE is a dict with key : mutation caller (mutect or radia) value : di...
def len_tweet(tweet): """calcule la longueur d'un tweet""" return(len(tweet["text"]))
def strip_hidden(key_tuples, visibilities): """Filter each tuple according to visibility. Args: key_tuples: A sequence of tuples of equal length (i.e. rectangular) visibilities: A sequence of booleans equal in length to the tuples contained in key_tuples. Returns: A sequence equal ...
def is_native(s): """Return True for native strings, i.e. for str on Py2 and Py3.""" return isinstance(s, str)
def prime_factor(obj): """ Get the primary factor on the `obj`, returns None if none. """ f = getattr(obj, '_e_factors', None) if f: return f[0], getattr(obj, f[0], None)
def bfmt(num, size=8): """ Returns the printable string version of a binary number <num> that's length <size> """ if num > 2**size: return format((num >> size) & (2**size - 1), 'b').zfill(size) try: return format(num, 'b').zfill(size) except ValueError: return num
def jmap(s, f, *l): """Shorthand for the join+map operation""" return s.join(map(f, *l))
def make_exception_message(exc): """ An exception is passed in and this function returns the proper string depending on the result so it is readable enough. """ if str(exc): return '%s: %s' % (exc.__class__.__name__, exc) else: return '%s' % (exc.__class__.__name__)
def decode(line): """Make treatment of stdout Python 2/3 compatible.""" if isinstance(line, bytes): return line.decode('utf-8') return line
def to_bytes(binary_string: str) -> bytes: """Change a string, like "00000011" to a bytestring :param str binary_string: The string :returns: The bytestring :rtype: bytes """ if len(binary_string) % 8 != 0: binary_string += "0" * ( 8 - len(binary_string) % 8 ) # fill...
def isomid(d) -> str: """Returns 2020-08-01T00:00:00+00:00""" return f"{d}T00:00:00+00:00"
def karatsuba(a, b): """ >>> karatsuba(15463, 23489) == 15463 * 23489 True >>> karatsuba(3, 9) == 3 * 9 True """ if len(str(a)) == 1 or len(str(b)) == 1: return (a * b) else: m1 = max(len(str(a)), len(str(b))) m2 = m1 // 2 a1, a2 = divmod(a, 10**m2) ...
def valfilterfalse(predicate, d, factory=dict): """ Filter items in dictionary by values which are false. >>> iseven = lambda x: x % 2 == 0 >>> d = {1: 2, 2: 3, 3: 4, 4: 5} >>> valfilterfalse(iseven, d) {2: 3, 4: 5} See Also: valfilter """ rv = factory() for k, v in d.items...
def check_blank(text, ref): """Formats a data-reference pair and avoids references being given to blank data items""" if text == None or text == '': return [] return [[text, ref]]
def capitalize_every_word(random_str): """ Returns a tokenized string Args: random_str : a given sentence Returns: a string with every word capitalized """ return random_str.title()
def compute_downcomer_area_fraction(F_LV): """ Return the ratio of downcomer area to net (total) area, `A_dn`. Parameters ---------- F_LV : float Flow parameter. Notes ----- The fraction of downcomer area is given by [3]_. See source code for details. """ if F_LV <...
def is_list_of_float(value): """ Check if an object is a liat of floats :param value: :return: """ return bool(value) and isinstance(value, list) and all(isinstance(elem, float) for elem in value)
def is_instance(obj, klass): """Version of is_instance that doesn't access __class__""" return issubclass(type(obj), klass)
def unparse_header(name, value): """Parse a name value tuple to a header string. Args: name: The header name. value: the header value. Returns: The header as a string. """ return ": ".join([name, value]) + "\r\n"
def _group_logic(x): """Label multi biomarker groups. Some biomarkers correspond to multiple clusters. This sets up the logic to assign these clusters to individual groups. """ if x == "G|EPS": return "G|EPS" elif ( (x == "G|EPS|MPS|LPS") | (x == "G|EPS|MPS") | ...
def smooth_counts(counts, smoothing): """Apply smoothing to inital and transition counts. Args: counts: arrays (scount, tcount) where scount[i] is the count of i at sequence start and tcount[i][j] the count of i followed by j. Returns: arrays (scount, tcount) with smoothed coun...
def unpad(data): """ ccavenue method to unpad data. :param data: encrypted data :return: plain data """ return data[0:-data[-1]]
def write_size(size_in_bytes): """Return size in appropriate measure.""" try: size = round(float(size_in_bytes)) except (TypeError, ValueError): raise ValueError('Invalid size measure.') if size < 0: raise ValueError('Size must be positive.') kib = size / 1024 if kib <=...
def convert_list_to_matrix(in_matrix, n_rows, n_columns): """converts a list into a list of lists (a matrix like) with n_rows and n_columns.""" return [in_matrix[j:j + n_rows] for j in range(0, n_rows * n_columns, n_rows)]
def remove_adjacent_nums(n): """Make sure we don't insert in adjacent locations, otherwise the numbers will join together and our created ordering will be invalid, failing test. """ output = [] for e in n: if len(output) == 0 or output[-1][0] <= e[0] - 2: output.append(e) ret...
def get_title(song): """Tite of song""" return song['title']
def all_lines_at_idx(mm, idx_list): """ return a list of lines given a list of memory locations follow up on all_lines_with_tag e.g. all_lines_at_idx(mm, all_lines_with_tag(mm, 'Atom') ) reads ''' Atom 0 0 0 0 Atom 1 1 1 1 Atom 2 2 2 2 ''' Args: mm (mmap.mmap): memory map to file idx_list (li...
def diff_possible(numbers, k): """ Given a list of sorted integers and a non negative integer k, find if there exists 2 indicies i and j such that A[i] - A[j] = k, i != j """ if k < 0: raise ValueError('k can not be non negative') # Find k since as long as i is not larger than k ...
def findnone(vec): """return the index of the first occurence of item in vec""" for i in range(len(vec)): if vec[i] is None: return i return -1
def map_cscc_data(mappings, data, logger, data_type, subtype): """Filter the raw data and returns the filtered data, which will be further pushed to GCP. :param mappings: List of fields to be pushed to GCP (read from cscc_mappings.json) :param data: Data to be mapped (retrieved from Netskope) :param lo...
def quaternion_inner_product_dist(q1, q2): """Quaternion distance based on innerproduct. See comparisons at: https://link.springer.com/content/pdf/10.1007%2Fs10851-009-0161-2.pdf""" return 1.0 - abs(q1[0]*q2[0] + q1[1]*q2[1] + q1[2]*q2[2] + q1[3]*q2[3])
def check_auth(username, password): """This function is called to check if a username / password combination is valid. """ # Get username from config file or so if username == 'admin' and password == 'secret': return True else: return False
def any_is_float(data): """ are any of the items floats """ for item in data: if isinstance(item, float): return True return False
def _resolve_extracted_playlist(playlist): """Resolve a playlist and its nested generators""" playlist_data, videos, has_user_list, user_list_title = playlist return (playlist_data, list(videos), has_user_list, user_list_title)
def from_gm_timestamp(timestamp): """Convert timestamp in microseconds to timestamp in seconds.""" return int(timestamp) // 1000000
def hex2int(hex_str): """ Convert 2 hex characters (e.g. "23") to int (35) :param hex_str: hex character string :return: int integer """ return int(hex_str, 16)
def binary_search(alist, item): """list -> bool binary search using a while loop """ first = 0 last = len(alist) - 1 found = False while first<=last and not found: midpoint = (first + last) // 2 if alist[midpoint] == item: found = True else: ...
def parse_definition(line: str) -> tuple: """ Parse function definition line to get: - input_types_default for each argument - output_type for the function Parameters ---------- line: str A function definition code line. Returns ------- Two dicts: input_types_def...
def firstline(text): """Any text. Returns the first line of text.""" try: return text.splitlines(True)[0].rstrip(b'\r\n') except IndexError: return b''
def __xml_dict_replace(s, d): """Replace substrings of a string using a dictionary.""" for key, value in d.items(): s = s.replace(key, value) return s
def _panoids_url(lat, lon): """ Builds the URL of the script on Google's servers that returns the closest panoramas (ids) to a give GPS coordinate. """ url = "https://maps.googleapis.com/maps/api/js/GeoPhotoService.SingleImageSearch?pb=!1m5!1sapiv3!5sUS!11m2!1m1!1b0!2m4!1m2!3d{0:}!4d{1:}!2d50!3m10!2...
def append_value_for_timestamp(existing_ts, new_ts): """ Appending timeseries assuming start and end of both timeseries are same :param existing_ts: list of [timestamp, value1, value2, .., valuen] lists (note: this might include several values) :param new_ts: list of [timestamp, VALUE] list (note: this...
def remove_close_peaks(n_peaks, ir_valley_locs, x, min_dist): """ Remove peaks separated by less than MIN_DISTANCE """ # should be equal to maxim_sort_indices_descend # order peaks from large to small # should ignore index:0 sorted_indices = sorted(ir_valley_locs, key=lambda i: x[i]) so...
def xml_represent(type_, val): """XML Representation""" if val is None: return val if type_ is bool: return val is True and "true" or "false" else: return type_.to_string(val)
def _platform(*args): """ Helper to format the platform string in a filename compatible format e.g. "system-version-machine". """ # Format the platform string platform = '-'.join(x.strip() for x in filter(len, args)) # Cleanup some possible filename obstacles... platform = pla...
def _apply_map(edges, source_mapping, target_mapping): """ Maps edges according to new node names specified by source and target maps. edges : List[Tuple[str, str]] source_mapping : Dict[str, int] target_mapping : Dict[str, int] """ source_nodes = [edge[0] for edge in edges] target_node...
def approx_equal(val1: float, val2: float, tolerance: float = 1.0e-4) -> bool: """ Returns wether two values are approximately equal e.g. if they are less than 4 orders of magnitude apart. """ eq: bool = abs(val1 - val2) <= tolerance return eq
def retry_login(value): """Return True if value is None""" return value == 'retry'
def adapters(text): """ Parse lines of text into a list of adapters (represented by their joltage), supplemented by the outlet (0) and your device (maximum + 3). """ adapters = list(sorted(map(int, text.splitlines()))) adapters = [0] + adapters + [max(adapters) + 3] return adapters
def _beautify(name: str) -> str: """Concert variable name to a user friendly string.""" return name.replace("_", " ").title()
def round_up_to_power_of_two(n): """Rounds up the arg to a power of two (or zero if n was zero). This is done very inefficiently.""" assert isinstance(n, int) while n & (n-1) != 0: ## '&' is bitwise and n = n + 1 return n
def generate_footer(caption: str = '', complete_document: bool = False) -> str: """ Generate table footer. args: caption (str, optional): table caption, blank if not specified returns: str: table footer """ if not complete_document: return '''\\end{tabular}\n\\caption{...
def celcius_to_fahrenheit(celcius): """Convert a Celsius temperature to Fahrenheit.""" return celcius * 1.8 + 32.0
def build_node(type: str, name: str, content: str) -> str: """ Wrap up content in to a html node. :param type: content type (e.g., doc, section, text, figure) :type path: str :param name: content name (e.g., the name of the section) :type path: str :param name: actual content :type path...
def valid_pid(pid): """pid (Passport ID) - a nine-digit number, including leading zeroes.""" if len(pid) == 9: if pid.isnumeric(): return True return False
def os_cli(os_secrets): """ Return full OpenStack CLI command """ cmd = ( "openstack " "--os-auth-type password " "--os-placement-api-version {api_ver} " "--os-username {username} " "--os-password {password} " "--os-project-domain-id {proj_id} " "--os-use...
def copy(object): """ Returns a clone of object Note: From cloujure Language http://docs.oracle.com/javase/6/docs/api/java/util/Vector.html#indexOf%28java.lang.Object%29 """ if hasattr(object, "copy"): return object.copy() else: return object
def linear(data): """Completes data records with missing data (0 or None) using linear interpolation. Works only if first and last data points have valid data""" data = list(data) last_data_pt = 0 i = 0 interpolate = False for i in range(len(data)): dt = data[i] if not dt['d...
def keyvalue(dict, key): """ takes a dictionary key and returns the value Usage: {{dictionary|keyvalue:key_variable}} {{dictionary|keyvalue:key_variable|keyvalue:another_key}} the latter is theoretical at this point for nested dictionaries. """ try: return dict[key] excep...
def prepend_to_lines(text, prepend_str): """Prepends a string to every line of a given text. Args: text: The text whose lines the string is prepended to. prepend_str: The prepended string. Returns: The text with each line prepended by string. """ return '\n'.join(map(lambda...
def refbasis(reading,ref): """Argument: raw ADC reading, raw ADC basis. Returns an absolute potential based on the ADC reading against the 2.5 V reference (reading from pot as a value between 0 and 1023, reference value in V (e.g. 2.5))""" return round((float(reading)/float(ref))*2.5,3)
def xtf_runner_exit_status(state): """ Convert a xtf-runner exit code to a test result. """ return { 0: "SUCCESS", 1: "sys.exit 1", 2: "sys.exit 2", 3: "SKIP", 4: "ERROR", 5: "FAILURE", 6: "CRASH", }[state]
def generate_manifest_table_name( database_name, base_table_name, import_source, export_source ): """Returns the qualified manifest table name. Arguments: database_name (string): The name of the database base_table_name (string): The base name of the table import_source (string): "s...
def to_str(bytes_or_str): """ Convert supplied value to a string. If supplied value of type str, this will return the value untouched :param bytes_or_str: bytes_or_str :return: value """ if isinstance(bytes_or_str, bytes): return bytes_or_str.decode() return bytes_or_str
def toMath(x): """Convert the expression to a math-latex readable expression.""" x = x.replace(" ", "") x = x.replace("**", "^") x = x.replace("^2.0", "^{2.0}") x = x.replace("^0.5", "^{0.5}") x = x.replace("^nexp", "^{n}") x = x.replace("^cexp", "^{c}") x = x.replace("gamma", "\\gamma ...
def _process(proc_data): """ Final processing to conform to the schema. Parameters: proc_data: (Dictionary) raw structured data to process Returns: Dictionary. Structured data to conform to the schema. """ # nothing to process return proc_data
def createFeatureTree(features): """ Return list where each element contains each previous element """ subFeatures = {} treeSoFar = [] for feature in features: treeSoFar.append(feature) subFeatures[feature] = treeSoFar[:] return subFeatures
def _build_xpath_expr(attrs) -> str: """ Build an xpath expression to simulate bs4's ability to pass in kwargs to search for attributes when using the lxml parser. Parameters ---------- attrs : dict A dict of HTML attributes. These are NOT checked for validity. Returns ------- ...
def parse_range(range_text): """ Split a range text such as '3-5' into [3, 4, 5] """ sep = '-' if sep in range_text: start, end = (int(n) for n in range_text.split(sep)) return list(range(start, end + 1)) else: return [int(range_text)]
def clean_path(path, strip = None, **kwargs): """ Cleans a path **Arguments:** :*path*: Initial path string :*strip*: Potential endings to remove from path **Returns: :*cleaned*: Cleaned path """ cleaned = path if strip is None: strip = [] elif is...
def session_to_viscode(session_name): """Replace the session label 'bl' with 'M00' or capitalize the session name passed as input. Args: session_name: MXX Returns: M00 if is the baseline session or the original session name capitalized """ if session_name == "M00": return "...
def _create_ca_file(anchor_list, filename): """ Concatenate all the certificates (PEM format for the export) in 'anchor_list' and write the result to file 'filename'. On success 'filename' is returned, None otherwise. If you are used to OpenSSL tools, this function builds a CAfile that can be u...
def title2url(title): """Markdown title to url""" table = str.maketrans('', '', '~`!@#$%^&*()+=[]{}:;\'"<>,.?/\\|') title_url = '-'.join(title.lower().split()) return title_url.translate(table)
def linear_search(item, my_list): """ Searching position by position :param item: the number to look for :param my_list: a list of integers :return: either True or False if the item is in the list or not. """ found = False for i in range(len(my_list)): if item == my_list[i]:...
def find_gcov(f, possible_gcovs): """ Find .gcov files that could be of interest for us """ try: return possible_gcovs[f] except: return []
def _prune_instance_label(label): """Deletes everything after the year, which ends in a closed parenthesis.""" sep = ")" return label.split(sep, 1)[0] + sep
def mat_mul(mat_a, mat_b): """ Function that multiplies two matrices, mat_a and mat_b. Each entry of the resulting matrix, mat_c, is a "dot-product" of a row of mat_a with a column of mat_b, i.e. C_{ij} = Sum_{k} A_{ik} * B_{kj}, where index {i} iterates through rows of mat_a, index {j} iterates thr...
def path_subst(path, mapping): """Replace the sort sting elements by real values. Non-elements are copied literally. path = the sort string mapping = array of tuples that maps all elements to their values """ # Added ugly hack to prevent %ext from being masked by %e newpath = [] plen = l...
def solve(dependencies, required_technologies): """ Topological sorting. Starting from each required technology, each dependency will be visited -- and only each dependency will be visited. Therefore, in the end, `order` will be exactly the technologies that need to be developed to satisfy `req...
def filter_empty_list_dict(items): """A special helper function, which is removing any item which contains empty list/dict value. It is used by ``FHIRAbstractModel::json``""" if not isinstance(items, (list, dict)): return items if len(items) == 0: return None if isinstance(item...
def bitfield_count(bitfield): """Count bits from golang Bitfield object. s0nik42 reverse engineering https://github.com/filecoin-project/go-bitfield/blob/master/rle/rleplus.go#L88""" count = 0 if len(bitfield) < 2: return 0 for i in range(0, len(bitfield), 2): count += bitfield[...
def is_tachycardic(hr, age): """Evaluates if posted heart rate is tachycardic Method curated by Braden Garrison Tachycardia is defined as a heart rate that is above normal resting rate. Specific tachycardic values are dependent upon patient age. More info about tachycardia and its diagnosis can be...
def transpose(input_list): """ Transpose a two dimensinal list. Arguments: input_list -- a two dimensional list for transposing. Returns: result -- transposed two dimensinal list. """ result = [] for i in range(len(input_list[0])): new_line = [new_list[i] for new_l...
def _get_filters(conf): """Get and construct AWS Tag Filters Args: conf (dict): yaml dict with tag configuraiton Returns: list: list of filters for AWS API consumption """ filters = [] tags = conf.get('tags') if tags: for tag in tags: filters.append( ...
def cap_text(text): """ Capitalize first letter of a string :param text: input string :return: capitalized string """ return text.title()
def sizeof_fmt(num, suffix='B'): """ https://stackoverflow.com/a/1094933 answer by Sridhar Ratnakumar """ for unit in ['','Ki','Mi','Gi','Ti','Pi','Ei','Zi']: if abs(num) < 1024.0: return "%3.1f%s%s" % (num, unit, suffix) num /= 1024.0 return "%.1f%s%s" % (num, 'Yi', suff...
def validateClips(cmodel, layers, gmused): """ Ensures coefficients provided in model description are valid and outputs a dictionary of the coefficients. Args: cmodel (dict): Sub-dictionary from config for specific model, for example: .. code-block:: python ...
def read_lineconf(str): """ Return the argument parsed as a memery-specific line-parsed file, where empty lines and lines starting with # are ignored. Examples: adminlist, userblacklist, commands """ return [l for l in str.splitlines() if l and not l.startswith('#')]
def sum_int(values) : """Sum of integer values""" sum = 0 for v in values : sum += int(v) return sum
def _get_context_info_from_url(url_string): """Examine a url for helpful info for use in a note :param url_string: The url to examine :returns: String of helpful information Strings returned should include a leading space. """ if url_string.endswith("/builddata"): return " - builddata" ...
def noam_schedule(step, warmup_step=4000): """ original Transformer schedule""" if step <= warmup_step: return step / warmup_step return (warmup_step ** 0.5) * (step ** -0.5)
def is_ascii(string): """ Returns true if the string only contains ASCII characters, False otherwise. """ try: string.encode('ascii') except UnicodeEncodeError: return False return True
def get_postgres_type(type_name): """converts json schema type to PostgreSQL type""" return { 'STRING': 'text', 'INT': 'integer', 'BOOLEAN': 'boolean', 'LONG': 'bigint', 'TIMESTAMP': 'timestamp', 'DOUBLE': 'double precision', 'BIGINT': 'bigint', 'T...
def create_url(index, source): """ Return the valid URL for download :param variable: string :param level: string :param date: datetime :return: sring """ if source == 'NOAA': if 'nina' in index: base_url = 'https://psl.noaa.gov/data/correlation/{index}.anom.data' ...
def build_category_filters(team_size): """ Generate category_filters because easier.""" category_filters = {} for category in ( "All", "Arabia", "Arena", "Others", ): category_filters[ "{} {}".format(team_size, category) ] = "AND map_category =...
def doublef(p, q, n, jp): """Double jp in projective (jacobian) coordinates""" if not jp: return None x1, y1, z1, z1p2, z1p3 = jp y1p2 = (y1 * y1) % n a = (4 * x1 * y1p2) % n b = (3 * x1 * x1 - p * z1p3 * z1) % n x3 = (b * b - 2 * a) % n y3 = (b * (a - x3) - 8 * y1p2 * y1p2) % n...
def _attr_list_to_dict(attr_list): """ _attr_list_to_dict -- parse a string like: host:ami, ..., host:ami into a dictionary of the form: { host: ami host: ami } if the string is in the form "ami" then parse to format { default: ami } raises ValueError if lis...