content
stringlengths
42
6.51k
def makeReadable(t): """squeeze text for readability helper for print lines... """ t = t.strip() t = t.replace('\n', '\\\\') if len(t) > 100: return t[:50] + ' ... ' + t[-50:] else: return t
def merge_two_dicts(data_1, data_2): """Function: merge_two_dicts Description: Merges two dictionaries. Note: Any duplicate keys between the two dictionaries will be overwritten by data_2 keys. Arguments: (input) data_1 -> Dictionary. (input) data_2 -> Dictionary. ...
def get_average_item(index, lst, take_back=False): """ this function calculates the average of the element in a list, and his sequential indexes :param index: the index :param lst: list of elements :return: the average of the needed elements """ if take_back: return [ ...
def add_init_area_data_body(settings): """returns init_area_data body Parameters ---------- settings: dict Returns ------- string """ s = "" for cohort in settings["cohort-area-files"]: s += "- " + cohort + "\n" return s
def fib(n: int) -> int: """ This is a Fibonacci number getter, optimized with a caching decorator :param n: The desired Fibonacci number in the sequence :return: The nth Fibonacci number """ if n <= 1: return 1 else: return fib(n-1) + fib(n-2)
def show_pagination(items): """ {% show_pagination items %} :param items: QuerySet object :return: """ return {'items': items}
def calculate_enrichment(coverage_values): """Calculate TSS enrichment value for a dataset Parameters ---------- coverage_values iterable of tuples (tss_center_depth, flank_depth) per TSS Returns ------- float the TSS enrichment value """ tss_depth, flank_depth...
def histogram(values, mode=0, bin_function=None): """Return a list of (value, count) pairs, summarizing the input values. Sorted by increasing value, or if mode=1, by decreasing count. If bin_function is given, map it over values first.""" if bin_function: values = map(bin_function, values) ...
def atmospheric_pressure(z, temp = 293.15, lb = 6.5e-3): """ Calculates atmospheric pressure at a given height. Parameters ---------- z : float Altitude above sea level [m]. temp : float, optional Meam atmospheric temperature [K]. The default is 288.15. lb : float,...
def get_table_titles(data, primary_key, primary_key_title): """Detect and build the table titles tuple from ORM object. .. note:: Currently only support SQLAlchemy. """ if not data: return [] titles = [] for k in data[0].__table__.columns.keys(): if not k.startswith("_")...
def process_domain_assoc(url, domain_map): """ Replace domain name with a more fitting tag for that domain. User defined. Mapping comes from provided config file Mapping in yml file is as follows: tag: - url to map to tag - ... A small example domain_assoc.yml is included "...
def test_incidence(description, list_of_keywords): """ Determines whether at least one of keyword from list_of_keywords is in description. :param description: description of CVE. :param list_of_keywords: keywords function searches for :return: true if one of keywords is in description. """ ...
def find_workspace(workspace_wrapper, workspace_name): """Search through a collection of workspaces and return the workspace with the given name :param workspace_wrapper: A collection of workspaces in the Google Tag Manager List Response format :type workspace_wrapper: dic...
def tail(text, places=50): """ Get the last part of a string, prepend '...' if it was truncated. """ if len(text) <= places: return text short = ' '.join(text[-places + 2:].split(' ')[1:]) if len(short) < max(places * 0.8, places - 10): short = text[-places + 3:] return '...' + short
def is_autovacuum(func): """ Return whether ``func`` is an autovacuum method. """ return callable(func) and getattr(func, '_autovacuum', False)
def validate_columns(board: list): """ validates whether columns of the board comply ot the rules """ vals = {x for x in range(1, 10)} for idx1 in range(9): chars = vals.copy() for idx2 in range(9): if board[idx2][idx1] != '*' and board[idx2][idx1] != ' ': ...
def _get_picks(raw): """Get picks.""" return [0, 1, 2, 6, 7, 8, 12, 13, 14]
def write_to_file(data: bytes, filepath: str) -> int: """ Writes arbitrary bytes to a file given `data` and `filepath` Returns number of `bytes` written """ if not isinstance(data, bytes): raise TypeError("data expecting type bytes, got {0}".format(type(data))) if not isinstance(filepa...
def recursive_example(x: int) -> bool: """ pre: x >= 0 post[]: __old__.x >= 0 # just to confirm __old__ works in recursive cases _ == True """ if x == 0: return True else: return recursive_example(x - 1)
def topological_sort(graph): """ topological sort python implementation """ stack = [] visited = set() def topological_sort_util(vertex): """ modified depth-first search recursive algorithm """ visited.add(vertex) for node in graph[vertex]: if node not in visited: ...
def to_bytes(string): """Converts a string with a human-readable byte size to a number of bytes. Takes strings like '7536 kB', in the format of proc.""" num, units = string.split() num = int(num) powers = {'kb': 10, 'mb': 20, 'gb': 30} if units and units.lower() in powers: num <<= power...
def _find_qubit_id(cmd): """Find qubit id in openqasm cmd.""" left = [] right = [] for i, j in enumerate(cmd): if j == '[': left.append(i) elif j == ']': right.append(i) if len(left) != len(right): raise ValueError(f"Parsing failed for cmd {cmd}") ...
def closer(a, b): """ >>> closer(1, 1) 0 >>> closer(1, 5) 1 >>> closer(-7, -11) -1 >>> closer(5, 1) -1 >>> closer(1, 2) 1 """ if a > b: return -1 elif a < b: return 1 else: return 0
def rev_comp(str): """ Given a DNA string, returns the reverse complement >>> rev_comp("AATTGGCC") 'GGCCAATT' """ rev_dic = {'A':'T','G':'C','C':'G','T':'A'} return ''.join([rev_dic[i] for i in str[::-1]])
def _image_member_format(member_ref): """Format a member ref for consumption outside of this module.""" return { 'id': member_ref['id'], 'image_id': member_ref['image_id'], 'member': member_ref['member'], 'can_share': member_ref['can_share'], 'status': member_ref['status'...
def add_mappings(mappings): """Returns a dict with additional es mappings.""" # return mappings since we are not adding any new index fields return mappings
def get_switch_criteria( enduse, sector, crit_switch_happening, base_yr=False, curr_yr=False ): """Test if switch is happending """ if base_yr == curr_yr and (base_yr != False or curr_yr != False): crit_switch_service = False else: if enduse in...
def mini_help(n): """ => Exibe a docstring do comando que recebe :param n: o comando a ser pesquisado :return: a ajuda interactiva (help) do parametro """ r = len('Acedendo ao manual do comando')+len(n)+6 #este trecho print('~'*r) #de codigo print(f' Acedendo ao manual do comando {n}') #pode ser print...
def get_user_dict_from_table(user_from_query): """ Returns a dict representation of a user given a result from the table query :param user_from_query: a signle result from a query to the users table :return: dict representation of the user """ user_data = dict( user=user_from_query["User...
def _get_default_args(args, defaults): """ returns a dictionary of arg_name:default_values for the input function """ if not defaults: return {} return dict(zip(args[-len(defaults):], defaults))
def total_variation_distance(u_values, v_values): """Compute the total variation distance between two 1D distributions. :param u_values: probability distribution :param v_values: probability distrbution :return: total variation distance between u_values and v_values """ dist = sum([abs(p-q) for...
def sanitize_lbl(label): """sanitize_lbl(label): Makes labels latex friendly.""" import re out = label.split('$') for i in range(0, len(out), 2): out[i] = re.sub('_', r'\_', out[i]) return '$'.join(out)
def bdict2dict(bdict, key=None): """ @bdict: bytes dict like b{'keys': val}" @key: key bytes or str, if is None no need key @return Python dict %% byte dict --> str --> dict """ try: if bdict is None: return None if key is None: return eval(str(bdict, "utf-8")) key =...
def check_preference(energies, energy_cutoff): """ Check if cis isomer is preferred based on relative energetics. Parameters ---------- energies : :class:`dict` Dictionary of isomer energies. energy_cutoff : :class:`float` Energy threshold for preference. Returns -----...
def remove_duplicates(list1): """ Eliminate duplicates in a sorted list. Returns a new sorted list with the same elements in list1, but with no duplicates. This function can be iterative. """ if len(list1) == 0: return list1 else: list2 = [] for idx in range(len...
def compare_ver(a, b): """Logically compare two Firefox version strings. Split the string into pieces, and compare each piece numerically. Returns -1, 0, or 1 depending on whether a is less than, equal to, or greater than b. """ if a == b: return 0 ap = [int(p) for p in a.split("."...
def apply_template(template, keywords): """Return a list of strings of form ``template`` with values in ``keywords`` inserted. Args: template (``str``): a string containing keywords (``{kw_name}``). keywords (``dict``-like): dict with keys of appropriate keyword names and values as equal length...
def is_bit_set(int_type, offset): """ >>> is_bit_set(1, 0) True >>> is_bit_set(2, 0) False >>> is_bit_set(0xFF, 2) True """ mask = 1 << offset return not 0 == (int_type & mask)
def is_ugly(num, factors=(2, 3, 5)): """ Check whether a given number is an ugly number :param num: given number :type num: int :param factors: prime factors for ugly number :type factors: list[int] or tuple[int] :return: whether a given number is an ugly number :rtype: bool """ ...
def round_rating(number): """Round a number to the closest half integer. >>> round_of_rating(1.3) 1.5 >>> round_of_rating(2.6) 2.5 >>> round_of_rating(3.0) 3.0 >>> round_of_rating(4.1) 4.0""" return round(number * 2) / 2
def uniquify(iterable): """Uniquify the elements of an iterable.""" elements = {element: None for element in iterable} return list(elements.keys())
def generate_comic_html(comic={}): """Generates part HTML for the qotd supplied""" return """ <h3>Dilbert by Scott Adams -</h3> <a href="{0}"><img alt="{1} - Dilbert by Scott Adams" src="{2}"></a> """.format(comic['url'], comic['title'], comic['image'])
def gf_rshift(f, n): """Efficiently divide f by x**n. """ if not n: return f, [] else: return f[:-n], f[-n:]
def conditional_prob_dec(x, y, dist, cliques, separators): """ Conditional probability of x given y, p(x | y). Args: x (dict): """ prob = 1.0 active_cliques = [] active_separators = [] for i, clique in enumerate(cliques): for node in x: if node in clique: ...
def _size_proportional(width, height): """Performs a proportional resize.""" return ("-vf", r"scale=min({height}*(iw/ih)\,{width}):min({width}/(iw/ih)\,{height})".format(width=width, height=height))
def num(s): """Convert a string to an integer or float """ try: return int(s) except ValueError: return float(s)
def evaluateExpression(expression): """Evaluates the contents of an expression using eval().""" try: if expression == "": return "0" else: return str(eval(expression)) except: pass
def stock_prices_2_greedy(stock_prices): """ Solution: Iterate through stock prices once, keeping track of the highest profit and lowest buy. Complexity: Time: O(n) Space: O(1) """ if len(stock_prices) < 2: raise ValueError('stock price list must be at least 2 items long') lowest_buy = None highest_profi...
def fb_rss(fbid): """Return the url for the rss format.""" if fbid is None: raise TypeError("fbid can't be None") return "http://www.facebook.com/feeds/page.php?format=rss20&id={0}".format(fbid)
def FoP_initialisation(S, source): """ 'L' initialisation for FoP :param S: :param source: :return: """ L, R = {}, {} L[source[1]] = source[0] # (a_u) R[source[1]] = source[0] return L, R
def get_modal_state(sequences): """ Computes the modal states for each position in a collection of sequences, returning a sequence of tuples containing the modal element and its number of occurances at that position. Example -------- >>> s1 = [1,1,1,2,2,3,3] >>> s2 = [1,2,2,2,2,3,3] >>> s3 = [1,1,1,1,2,2,3] >>...
def find_seperation(arg): """ Helper Function for decompose @param: arg is a string corresponding to two function statement sepereated by a comma Example: "and(and(a,c),b),or(ab,b)" @return: return the index of the comma seperating the functions or -1 if no such comma exi...
def compute_iou(rec1, rec2): """ computing IoU :param rec1: (y0, x0, y1, x1), which reflects (top, left, bottom, right) :param rec2: (y0, x0, y1, x1) :return: scala value of IoU """ # computing area of each rectangles S_rec1 = (rec1[2]) * (rec1[3] ) S_rec2 = (rec2[2] ) * ...
def is_named_tuple(cls): """Return True if cls is a namedtuple and False otherwise.""" b = cls.__bases__ if len(b) != 1 or b[0] != tuple: return False f = getattr(cls, "_fields", None) if not isinstance(f, tuple): return False return all(type(n) == str for n in f)
def is_unique(x): """Tells if a there are duplicate items in a list or not Args: x (List): The list we check Returns: Boolean : True if there is no duplicate items in the list """ for i in range(len(x)): for j in range(i + 1, len(x)): if x[i] == x[j]: ...
def sink_container(_tuple): """ This function... :param _tuple: :return: """ import os.path return os.path.join(*_tuple)
def reverseBetween2(head, m, n): """ :type head: ListNode :type m: int :type n: int :rtype: ListNode """ if not head : return None pre, current = None, head while m > 1 : pre = current current = current.next n,m = n - 1, m -1 con, tail = pre,curren...
def get_tags(f): """Breaks down a file name into its tags and returns them as a list.""" if "/" in f: f = f.split("/")[-1] if "." in f: f = f.split(".")[0] if "_" in f: f = f.split("_") if ":" in f: f = f.split(":") return f
def to_data_string_with_default(value, arg=''): """ Given a Python boolean value converts it to string representation so we can use it in HTML data attributes. If value is None use given default or '' if default is not provided. ----- ------ Value Output ----- ------ True ...
def dVdc_calc(Vdc,Ppv,S,C): """Calculate derivative of Vdc""" dVdc = (Ppv - S.real)/(Vdc*C) return dVdc
def _create_users(users): """ Returns the section of the user data script to create a single Linux user and their SSH key pair on the EC2 instance. """ user_data_script_section = '' for user in users: login = user.login ssh_key = user.ssh_key ssh_key_dir = f'~{login}/.s...
def _get_from_nest(nest, path): """Return element from a dictionary-only nest using path specified as list. Args: nest: A nested dictionary. path: A list of strings specifying a nested element. Returns: An leaf or subnest of the input nest. """ if not path or not nest: return nest return _g...
def standardize_role(role): """Convert role text into standardized form.""" role = role.lower() if any(c in role for c in {'synthesis', 'give', 'yield', 'afford', 'product', 'preparation of'}): return 'product' return role
def human_readable_file_size(size): """ Returns a human readable file size string for a size in bytes. Adapted from https://stackoverflow.com/a/25613067) """ from math import log2 _suffixes = ['bytes', 'KB', 'MB', 'GB', 'TB', 'PB'] # determine binary order in steps of size 10 ...
def gldg(x): """Return numbers with digit grouping as per international system.""" return '{:,d}'.format(x)
def flatten(dct, sep='.'): """Flatten a nested dictionary. :param dct: Dictionary to flatten. :param sep: Separator used when concatenating keys. """ def _flatten(dct, prefix=''): """Inner recursive function.""" items = [] for key, value in dct.items(): new_prefix = '%s%s%s' % (prefix, sep...
def paren_matcher(s: str, open_index: int) -> int: """ Solution: Iterate through the s from the open_paren index, keeping track of how many remaining open parens there are. When we get to 0, return the index. Complexity: Time: O(n) - Iterate through our string once Space: O(n) - We take a slice of the input s ...
def release_from_branch(ver): """Parse the release version from the provided 'branch'. For example, if --group=openshift-3.9 then runtime.group_config.branch will have the value rhaos-3.9-rhel-7. When passed to this function the return value would be the number 3.9, where in considering '3.9' then '3.9' is the REL...
def head_of_list(x): """Takes a list, returns the first item in that list. If x is empty, return None >>> head_of_list([1, 2, 3, 4]) 1 >>> head_of_list([]) is None True """ return x[0] if x else None
def get_numbers(text): """Finds valid numeric values in text and return in a list""" s = [] if isinstance(text, list): text = " ".join(text) for t in text.split(): ok = True for c in t: if c not in list("0123456789.-"): ok = False break...
def validateTime(time): """ Helper function that checks the value the user entered for time :param time: the inputted time from the user :return: the time the user entered, or 0 """ response = time if (time > 59 and time < 100) or \ (time > 159 and time < 200) or \ (tim...
def terms_to_clauses(terms): """Split list of search terms and the 'or' keyword into list of lists of search terms.""" clauses = [[]] for term in terms: if term == 'or': clauses.append([]) else: clauses[-1].append(term) return clauses
def use_shadow(to_backup, windows_volume): """ add the shadow path to the backup directory """ return to_backup.replace(windows_volume, '{0}freezer_shadowcopy\\' .format(windows_volume))
def classCss(indents): """return Casscation Style Sheet.""" css = 'li, ul, o, p{padding: 0; margin: 0;}\nul{margin:0.5em 0 0.5em 0}\nh' css += '1, h2{text-align: center; font-family:Time; font-weight: normal}\n' css += 'h1{ font-size: 18pt; }\nh2{ font-size: 14pt; }\nli, p{ font-family' css += ': Co...
def cint(obj): """ Interprets an object as a integer value. :param obj: :return: """ if isinstance(obj, str): obj = obj.strip().lower() try: return int(obj) except ValueError: raise ValueError('Unable to interpret value "%s" as integer' % obj) elif obj is None: return obj re...
def print_test(a): """ Added for get_input parameter injection testing. :param a: input :type a: int :return: len(a) as str """ return str(len(a))
def sanitize(time_string): """ :param time_string: Input time string, which may have mins and seconds separated by either ':', '-' or '.' :return: Uniformly formatted time string with mins and secs separated by '.' """ if "-" in time_string: splitter = "-" elif ":" in time_str...
def _matches_range(range, value): """ range is (min, max). Return true if min <= value <= max. If range is None, there's no filter, so the value always matches. min and max can be None. """ if range is None: return True if range[0] is not None and range[0] > value: return Fals...
def replace_text_comment(comments, new_text): """Replace "# text = " comment (if any) with one using new_text instead.""" new_text = new_text.replace('\n', ' ') # newlines cannot be represented new_text = new_text.strip(' ') new_comments, replaced = [], False for comment in comments: if c...
def split_line(line): """all_abracts.csv has file_name, abstract let's just grab abstracts for now""" try: strings = line.split(',', 1) return str(strings[1]) except: pass
def amortization_schedule_iof( amortizations, return_days, daily_iof_aliquot=0.000082 ): """IOF tax over an amortization schedule. If :math:`A_1,A_2\\ldots,A_k` are the amortizations, :math:`n_1,n_2,\\ldots,n_k` the return days and :math:`I^*` the daily IOF aliquot, then the due...
def list_in_list(a, l): """Checks if a list is in a list and returns its index if it is (otherwise returns -1). Parameters ---------- a : list() List to search for. l : list() List to search through. """ return next((i for i, elem in enumerate(l) if elem == a), -1)
def compare_pivot(pivot1, pivot2): """ Compare pivot1 and pivot2 regardless of the sequence """ if pivot1 == pivot2 or pivot1 == [pivot2[-1], pivot2[0]]: return True else: return False
def split_data(line): """ Return the temperature of each line """ data = str.split(line, ',') return float(data[2])
def findRelativeRanks(nums): """ :type nums: List[int] :rtype: List[str] """ nums_sort = sorted(nums)[::-1] ranks = ['Gold Medal', 'Silver Medal', 'Bronze Medal'] + [str(i + 1) for i in range(3, len(nums_sort))] d = {n: r for n, r in zip(nums_sort, ranks)} return [d[n] for n in nums]
def is_symspec(symspec): """ returns True if `symspec` can be used as a symbol specification. """ if not hasattr(symspec, 'name'): return False if not hasattr(symspec, 'prec'): return False return True
def zigzagLevelOrder(root): """ :type root: TreeNode :rtype: List[List[int]] """ to_return = [] if not root: return to_return level = [root] ltor = True while level: level_val, next_level = [], [] for node in lev...
def nested_get(dic, path, delimiter='.'): """Get from dictionary by path :dic dict Source dictionaly. :path string Path withing dictionary :delimiter string Path delimiter :return: Value at path :rtype: unknown """ try: keys = path.split(delimiter) for key in keys[:-1]: ...
def subst_title(title): """ Safe substitute for string """ return title.replace(' ', '_').replace('/', '_')
def checkIsHours(value): """ checkIsHours tries to distinguish if the value describes hours or degrees :param value: string :return: """ if not isinstance(value, str): return False if '*' in value: return False elif '+' in value: return False elif '-' in va...
def truncate_string_end(string, length=40): """ If a string is longer than "length" then snip out the middle and replace with an ellipsis. """ if len(string) <= length: return string return f"{string[:length-3]}..."
def file_requires_unicode(x): """ Return whether the given writable file-like object requires Unicode to be written to it. """ try: x.write(b'') except TypeError: return True else: return False
def response(speech_response, attributes={}): """ create a simple json response """ return { 'version': '1.0', 'sessionAttributes': attributes, 'response': speech_response }
def strip_monotonic_pitch_content(pitch_content): """ The pitch content extracted in the :obj:`decitala.search` module consists of lists of tuples. This functions strips monotonic pitch content to a single list. If non-monotonic pitch content is provided, the function chooses the lowest pitch. :param list pitch_c...
def myDihedralFunctionAirliner(Epsilon): """User-defined function describing the variation of dihedral as a function of the leading edge coordinate""" BaseDihedral = 7 # A simple model of a loaded wing shape: return BaseDihedral + Epsilon*Epsilon*10
def recursive_to_cuda(tensors, device): """ Recursively iterates nested lists in depth-first order and transfers all tensors to specified cuda device. Parameters: tensors (list or Tensor): objects to move to specified device (can be nested) """ if device is None: # keep on cpu r...
def get_portchannel_members(pchannel): """Gets the members of an existing portchannel Args: pchannel (dict): port-channel dict Returns: list: empty if currently no members, otherwise list of Ethernet interfaces that make up the given port-channel Note: ...
def pid_tuning(data): """gains for the pid-controller""" Pgain = float(data["pid-tuning"]["Pgain"]) Igain = float(data["pid-tuning"]["Igain"]) Dgain = float(data["pid-tuning"]["Dgain"]) Imax = float(data["pid-tuning"]["Imax"]) Imin = float(data["pid-tuning"]["Imin...
def split_list(n): """will return the list index""" return [(x+1) for x,y in zip(n, n[1:]) if y-x != 1]
def _subexon_ranks(strand, transcript_len): """ Return a list of the subexon ranks. NOTE: Rank starts in 0 to make this compatible with end_phase_previous_exon that expect exon_pos(ition) to start in 0. >>> _subexon_ranks(-1, 10) [9, 8, 7, 6, 5, 4, 3, 2, 1, 0] >>> _subexon_ranks(1, 10) ...