content
stringlengths
42
6.51k
def add_params(default_params, extra_params): """ Add params from extra_params to default_params Parameters ---------- default_params : dict Original parameters extra_params : dict Extra parameters to add Returns ------ params : dict Merged parameters, where extra_params can overwrite default_params """ for k, v in extra_params.items(): default_params[k] = v return default_params
def get_iou(bboxes1, bboxes2): """ Adapted from https://gist.github.com/zacharybell/8d9b1b25749fe6494511f843361bb167 Calculates the intersection-over-union of two bounding boxes. Args: bbox1 (numpy.array, list of floats): bounding box in format x1,y1,x2,y2. bbox2 (numpy.array, list of floats): bounding box in format x1,y1,x2,y2. Returns: np array: intersection-over-onion of bboxes1 and bboxes2 """ ious = [] for bbox1, bbox2 in zip(bboxes1, bboxes2): bbox1 = [float(x) for x in bbox1] bbox2 = [float(x) for x in bbox2] (x0_1, y0_1, x1_1, y1_1) = bbox1 (x0_2, y0_2, x1_2, y1_2) = bbox2 # get the overlap rectangle overlap_x0 = max(x0_1, x0_2) overlap_y0 = max(y0_1, y0_2) overlap_x1 = min(x1_1, x1_2) overlap_y1 = min(y1_1, y1_2) # check if there is an overlap if overlap_x1 - overlap_x0 <= 0 or overlap_y1 - overlap_y0 <= 0: ious.append(0) continue # if yes, calculate the ratio of the overlap to each ROI size and the unified size size_1 = (x1_1 - x0_1) * (y1_1 - y0_1) size_2 = (x1_2 - x0_2) * (y1_2 - y0_2) size_intersection = (overlap_x1 - overlap_x0) * (overlap_y1 - overlap_y0) size_union = size_1 + size_2 - size_intersection iou = size_intersection / size_union ious.append(iou) return ious
def is_subdict(small, big): """ Check if one dict is a subset of another with matching keys and values. Used for 'flat' dictionary comparisons such as in comparing interface settings. This should work on both python 2 and 3. See: https://docs.python.org/2/reference/expressions.html#value-comparisons :rtype: bool """ return dict(big, **small) == big
def average(num_list): """Return the average for a list of numbers >>> average([1,2]) 1.5 """ return sum(num_list) / len(num_list)
def mib(num): """Return number of bytes for num MiB""" return int(num * 1024 * 1024)
def c_string_arguments(encoding='UTF-8', *strings): """ Convenience function intended to be passed to in_format which allows easy arguments which are lists of null-terminated strings. """ payload = b"" # Add each string, followed by a null character. for string in strings: payload += string.encode(encoding) payload += b"\0" return payload
def is_unicode_list(value): """Checks if a value's type is a list of Unicode strings.""" if value and isinstance(value, list): return isinstance(value[0], str) return False
def sdnv_decode(buffer): """Decodes a byte string (or any iterable over bytes) assumed to be a an SDNV and returns the non-negative integer representing the numeric value Args: buffer (bytes): Encoded SDNV Returns: int: Decoded non-negative integer Raises: ValueError: If the buffer contains insufficient bytes (not the complete SDNV) """ n = 0 for i, byte in enumerate(buffer, 1): n = (n << 7) | (byte & 0x7f) if byte >> 7 == 0: return n, i raise ValueError("Insufficient bytes")
def get_wind_direction(degree): """Convert wind degree to direction.""" DEGREES = [-11.25, 11.25, 33.75, 56.25, 78.75, 101.25, 123.75, 146.25, 168.75, 191.25, 213.75, 236.25, 258.75, 281.25, 303.75, 326.25, 348.75] DIRECTIONS = ['N', 'NNE', 'NE', 'ENE', 'E', 'ESE', 'SE', 'SSE', 'S', 'SSW', 'SW', 'WSW', 'W', 'WNW', 'NW', 'NNW'] # North wind correction. if degree > 348.75: degree -= 360 for i in range(len(DIRECTIONS)): left_border = DEGREES[i] right_border = DEGREES[i + 1] if left_border < degree <= right_border: return DIRECTIONS[i]
def create_names(instances, Ns, str_format): """ Create a list of names for spectra loaded from task instances. :param instances: A list of task instances where spectra were loaded. This should be length `N` long. :param Ns: A list containing the number of spectra loaded from each task instance. This should have the same length as `instances`. :param str_format: A string formatting for the names. The available keywords include all parameters associated with the task, as well as the `star_index` and the `spectrum_index`. :returns: A list with length `sum(Ns)` that contains the given names for all the spectra loaded. """ names = [] for star_index, (instance, N) in enumerate(zip(instances, Ns)): kwds = instance.parameters.copy() kwds.update(star_index=star_index) for index in range(N): kwds["spectrum_index"] = index names.append(str_format.format(**kwds)) return names
def startsWith(str, prefix): """Return true iff _str_ starts with _prefix_. >>> startsWith('unclear', 'un') 1 """ return str[:len(prefix)] == prefix
def pad_right_with(l: list, sz: int, pd) -> list: """ Return a new `sz`-sized list obtained by right padding `l` with `pd`. If the starting list is of size `sz` or greater, no change is applyed. @param l: The list to pad. No changes are made to this list. @param sz: The final size of the list if it needs to be padded. A negative value will result in no changes. @param pd: the element to ose as padding. @return: A new list of size `sz`, or greater if `l` was greater. """ if(sz < 0 or len(l) >= sz): return l.copy() return (l + sz * [pd])[:sz]
def std2scatteringRange(std): """Convert a standard deviation into scattering range (`TS` or `TN` in DIN 50100:2016-12). Parameters ---------- std : float standard deviation Returns ------- T : float inverted scattering range corresponding to `std` assuming a normal distribution Notes ----- Actually `10**(2*norm.ppf(0.9)*std` Inverse of `scatteringRange2std()` """ return 10**(2.5631031310892007*std)
def kind(n, ranks): """Return the first rank that this hand has exactly n-of-a-kind of. Return None if there is no n-of-a-kind in the hand.""" for r in ranks: if ranks.count(r) == n: return r return None
def filter_files(input, endings = [".js"]): """Filters a list of files for specific endings Args: input: The depset or list of files endings: The list of endings that should be filtered for Returns: Returns the filtered list of files """ # Convert input into list regardles of being a depset or list input_list = input.to_list() if type(input) == "depset" else input filtered = [] for file in input_list: for ending in endings: if file.path.endswith(ending): filtered.append(file) continue return filtered
def InstanceGroupName(deployment, zone): """Returns the name of the instance group. A consistent name is required to define references and dependencies. Assumes that only one instance group will be used for the entire deployment. Args: deployment: the name of this deployment. zone: the zone for this particular instance group Returns: The name of the instance group. """ return "{}-instance-group-{}".format(deployment, zone)
def is_balanced(node): """Check if a BST is balanced; returns (True/False, height of tree).""" # First we ensure the left subtree is balanced; then ensure the right subtree # is balanced too; and ensure the diff betw heights of left & right subtree <=1 if node is None: return True, 0 balanced_l, height_l = is_balanced(node.left) balanced_r, height_r = is_balanced(node.right) balanced = balanced_l and balanced_r and abs(height_l - height_r) <= 1 height = 1 + max(height_l, height_r) return balanced, height
def convert_string_AE2BE(string, AE_to_BE): """convert a text from American English to British English Parameters ---------- string: str text to convert Returns ------- str new text in British English """ string_new = " ".join([AE_to_BE[w] if w in AE_to_BE.keys() else w for w in string.split()]) return string_new
def user_id(uid): """Google user unique id to feedly ``:user_id`` format :param uid: Google unique account UUID :type uid: :class:`basestring` :returns: :rtype: :class:`basestring` >>> user_id('00000000-0000-0000-0000-000000000000') 'user/00000000-0000-0000-0000-000000000000' """ return 'user/%s' % uid
def _parse_nonbon_line( line ): """Parse an AMBER frcmod nonbon line and return relevant parameters in a dictionary. AMBER uses rmin_half and epsilon in angstroms and kilocalories per mole.""" tmp = line.split() params = {} params['smirks'] = tmp[0] params['rmin_half'] = tmp[1] params['epsilon'] = tmp[2] return params
def is_palindrome_recursive(s: str) -> bool: """ Return True if s is a palindrome otherwise return False. >>> all(is_palindrome_recursive(key) is value for key, value in test_data.items()) True """ if len(s) <= 1: return True if s[0] == s[len(s) - 1]: return is_palindrome_recursive(s[1:-1]) else: return False
def get_max_coordination_of_elem(single_elem_environments): """ For a given set of elemental environments, find the greatest number of each element in a site. Input: | single_elem_environments: list(dict), list of voronoi substructures, Returns: | max_num_elem: dict(int), greatest number of each element in a substruc. """ max_num_elem = {} for site_ind, site in enumerate(single_elem_environments): for elem, value in site: elem_len = len([val for val in site if val[0] == elem]) if elem not in max_num_elem: max_num_elem[elem] = 0 if elem_len > max_num_elem[elem]: max_num_elem[elem] = elem_len return max_num_elem
def input_block(config, section): """Return the input block as a string.""" block = '' if section not in config: return '' for key in config[section]: value = config[section][key].strip() if value: block += '{} {}\n'.format(key, value) else: block += key + '\n' return block
def round_to_mb(bts): """Returns Mb from b rounded to .xx""" return round((int(bts) / 1024 / 1024), 2)
def skeys(some_dict): """ Returns sorted keys Useful for converting dicts to lists consistently """ return sorted([*some_dict])
def wf_sum(window, *args, **kwargs): """ Returns sum of values within window :param window: :return: """ return float(sum(w[1] for w in window))
def hexstr(barray): """Print a string of hex digits""" return ":".join(f'{x:02x}' for x in barray)
def as_hex(value, bit_width): """ Creates a hexadecimal string of a given bit width from the value provided """ mask = (1 << bit_width) - 1 return "%x" % (value & mask)
def maxHeightTry2(d1, d2, d3): """ A method that calculates largest possible tower height of given boxes (optimized, but bad approach 2/2). Problem description: https://practice.geeksforgeeks.org/problems/box-stacking/1 time complexity: O(n*max(max_d1, max_d2, max_d3)^2) space complexity: O(max(max_d1, max_d2, max_d3)^2) Parameters ---------- d1 : int[] a list of int values representing the 1st dimension of a / multiple 3d-box(es) d2 : int[] a list of int values representing the 2nd dimension of a / multiple 3d-box(es) d3 : int[] a list of int values representing the 3rd dimension of a / multiple 3d-box(es) Returns ------- x : int the largest possible tower height """ assert(len(d1) >= 1) assert(len(d1) == len(d2) == len(d3)) max_dimension = max([ max(d1), max(d2), max(d3) ]) boxes = zip(d1, d2, d3) boxes = map(sorted, boxes) boxes = sorted(boxes, key=lambda e: e[2]) boxes = sorted(boxes, key=lambda e: e[1]) boxes = sorted(boxes, key=lambda e: e[0]) boxes = boxes + list(map(lambda e: [e[1], e[2], e[0]], boxes)) boxes = sorted(boxes, key=lambda e: e[2]) boxes = sorted(boxes, key=lambda e: e[1]) boxes = sorted(boxes, key=lambda e: e[0]) n = len(boxes) # dimension 1: x-coordinate left # dimension 2: y-coordinate left max_height = [[0 for _ in range(max_dimension + 1)] for _ in range(max_dimension + 1)] for i in range(n): box_x, box_y, box_z = boxes[i][0], boxes[i][1], boxes[i][2] for x in range(box_x, max_dimension + 1): for y in range(box_y, max_dimension + 1): max_tmp = max_height[x][y] if box_x <= x and box_y <= y: max_tmp = max( max_tmp, max_height[box_x-1][box_y-1] + box_z) if box_x <= x and box_z <= y: max_tmp = max( max_tmp, max_height[box_x-1][box_z-1] + box_y) if box_y <= x and box_z <= y: max_tmp = max( max_tmp, max_height[box_y-1][box_z-1] + box_x) max_height[x][y] = max_tmp return max_height[max_dimension][max_dimension]
def derive_end_activities_from_log(log, activity_key): """ Derive end activities from log Parameters ----------- log Log object activity_key Activity key Returns ----------- e End activities """ e = set() for t in log: if len(t) > 0: if activity_key in t[len(t) - 1]: e.add(t[len(t) - 1][activity_key]) return e
def Find_StemDensityGridPT(StemDensityTPHa, Dx, nxy, Dy): """ function [StemDensityGridPT]=Find_StemDensityGridPT(StemDensityTPHa,Dx,nxy,Dy) Calculate a rounded coarse mesh resolution (in integer mesh-point number) in which to place stems. 1 stem will be placed at each coarse mesh grid-cell Copyright: Gil Bohrer and Roni avissar, Duke University, 2006 """ StemDensityGridPT = 0 i = 1 while i < nxy: sizeHa = Dx * Dy * StemDensityTPHa / 10000 if sizeHa * (i * i + (i + 1) * (i + 1)) / 2 >= 1: StemDensityGridPT = i i = nxy i = i + 1 if StemDensityGridPT == 0: StemDensityGridPT = nxy return StemDensityGridPT
def calculate_score(s1, s2, l1, l2, startpoint): """calculate alignment score""" matched = "" # to hold string displaying alignements score = 0 for i in range(l2): # import ipdb; ipdb.set_trace() ## debug breakpoint added if (i + startpoint) < l1: if s1[i + startpoint] == s2[i]: # if the bases match matched = matched + "*" score = score + 1 else: matched = matched + "-" # some formatted output # print("." * startpoint + matched) # print("." * startpoint + s2) # print(s1) # print(score) return score
def remove_copies(data: list) -> list: """Creates a unique list of arrays given a list of arrays containing identical arrays. Param: data (list[list[float or int]]): a list of lists of comparable items Return arrays: the unique list with no repeated arrays """ arrays = [] for a in data: # Check if a is in arrays contained = False for array in arrays: # Check if 'a' and 'array' are equal equal = True for i in range(len(array)): if a[i] != array[i]: equal = False break if equal: contained = True if not contained: arrays.append(a) return arrays
def llen(x) -> int: """ Calculate the length of input if list, else give 1 :param x: list or non-container type :return: length or 1 """ return len(x) if type(x) is list else 1
def contains(collection, target, from_index=0): """Checks if a given value is present in a collection. If `from_index` is negative, it is used as the offset from the end of the collection. Args: collection (list|dict): Collection to iterate over. target (mixed): Target value to compare to. from_index (int, optional): Offset to start search from. Returns: bool: Whether `target` is in `collection`. Example: >>> contains([1, 2, 3, 4], 2) True >>> contains([1, 2, 3, 4], 2, from_index=2) False >>> contains({'a': 1, 'b': 2, 'c': 3, 'd': 4}, 2) True See Also: - :func:`contains` (main definition) - :func:`include` (alias) .. versionadded:: 1.0.0 """ if isinstance(collection, dict): collection = collection.values() else: # only makes sense to do this if `collection` is not a dict collection = collection[from_index:] return target in collection
def get_ndim_first(x, ndim): """Return the first element from the ndim-nested list x. """ return (x if ndim == 0 else get_ndim_first(x[0], ndim - 1))
def short(text): """:short: Changeset hash. Returns the short form of a changeset hash, i.e. a 12 hexadecimal digit string. """ return text[:12]
def url_string(s: str) -> bool: """ Verify the given string (s) is a URL. :param s: string :return: bool """ # ToDo: Verify url pattern return type(s) is str
def sum_all(grid_values): """ Calculates the sum of all grid values. Results in scores from :param grid_values: values of grid :return: metrics score """ score = sum(grid_values) return score
def get_correct(gold, guess): """ Args: gold (Iterable[T]): guess (Iterable[T]): Returns: Set[T] """ return set(gold) & set(guess)
def rr_duplicates(input_list): """ Input: list by list() type Output: list without duplicates by list() type """ return list(set(input_list))
def toJadenCase(string): """ to_jaden_case == PEP8 (forced mixedCase by CodeWars) """ return ' '.join(a.capitalize() for a in string.split())
def msgs_human(messages, header): """ Return messages, with optional header row. One pipe-delimited message per line in format: date | from | to | text Width of 'from' and 'to' columns is determined by widest column value in messages, so columns align. """ output = "" if messages: # Figure out column widths max_from = max([len(x['from']) for x in messages]) max_to = max([len(x['to']) for x in messages]) max_date = max([len(x['date']) for x in messages]) from_width = max(max_from, len('From')) to_width = max(max_to, len('To')) date_width = max(max_date, len('Date')) headers_width = from_width + to_width + date_width + 9 msgs = [] if header: htemplate = u"{0:{1}} | {2:{3}} | {4:{5}} | {6}" hrow = htemplate.format('Date', date_width, 'From', from_width, 'To', to_width, 'Text') msgs.append(hrow) for m in messages: text = m['text'].replace("\n","\n" + " " * headers_width) template = u"{0:{1}} | {2:>{3}} | {4:>{5}} | {6}" msg = template.format(m['date'], date_width, m['from'], from_width, m['to'], to_width, text) msgs.append(msg) msgs.append('') output = '\n'.join(msgs).encode('utf-8') return output
def find_url_piecewise(mapping, symbol): """ Match the requested symbol reverse piecewise (split on ``::``) against the tag names to ensure they match exactly (modulo ambiguity) So, if in the mapping there is ``PolyVox::Volume::FloatVolume`` and ``PolyVox::Volume`` they would be split into: .. code-block:: python ['PolyVox', 'Volume', 'FloatVolume'] and ['PolyVox', 'Volume'] and reversed: .. code-block:: python ['FloatVolume', 'Volume', 'PolyVox'] and ['Volume', 'PolyVox'] and truncated to the shorter of the two: .. code-block:: python ['FloatVolume', 'Volume'] and ['Volume', 'PolyVox'] If we're searching for the ``PolyVox::Volume`` symbol we would compare: .. code-block:: python ['Volume', 'PolyVox'] to ['FloatVolume', 'Volume', 'PolyVox']. That doesn't match so we look at the next in the mapping: .. code-block:: python ['Volume', 'PolyVox'] to ['Volume', 'PolyVox']. Good, so we add it to the list """ piecewise_list = {} for item, data in list(mapping.items()): split_symbol = symbol.split('::') split_item = item.split('::') split_symbol.reverse() split_item.reverse() min_length = min(len(split_symbol), len(split_item)) split_symbol = split_symbol[:min_length] split_item = split_item[:min_length] #print split_symbol, split_item if split_symbol == split_item: #print symbol + ' : ' + item piecewise_list[item] = data return piecewise_list
def get_spans_in_offsets(spans, start, end): """Return the list of spans (nlplingo.text.text_span.Span) that are within (start, end) offsets :type spans: list[nlplingo.text.text_span.Span] Returns: list[text.text_span.Span] """ ret = [] for span in spans: if start <= span.start_char_offset() and span.end_char_offset() <= end: ret.append(span) return ret
def to_ordinal(number): """Return the "ordinal" representation of a number""" assert isinstance(number, int) sr = str(number) # string representation ld = sr[-1] # last digit try: # Second to last digit stld = sr[-2] except IndexError: stld = None if stld != '1': if ld == '1': return sr + 'st' if ld == '2': return sr + 'nd' if ld == '3': return sr + 'rd' return sr + 'th'
def format_date(date): """Formats the given date (`datetime` object). :returns: `date` of the form ``'YYYY-MM-DD HH:MM:SS'``. If `date` is ``None``, it returns ``'-'``. """ return date.strftime('%Y-%m-%d %H:%M:%S') if date is not None else '-'
def judge_date_type(date: str) -> str: """judge_date_type. Using "date"(str) length, judge date type. Args: date (str): date Returns: str: """ if len(date) == 8: date_type = "day" elif len(date) == 6: date_type = "month" elif len(date) == 4: date_type = "year" else: raise Exception (f'{date} is not valid value.') return date_type
def get_task_id_service_name(service_name): """Converts the provided service name to a sanitized name as used in task ids. For example: /test/integration/foo => test.integration.foo""" return service_name.lstrip("/").replace("/", ".")
def _getind(x,x0): """Find the index of a point on a grid. Find the index k of x0 in a real array x, such that x[k] <= x0 < x[k+1]. To enable usage by the interpolation routine, the edge cases are x0 <= x[0]: k = 0 x0 >= x[-1]: k = len(x) - 2 so that expressions such as (x[k+1]-x[k]) are always valid. :arg x: Grid points, monotonically increasing. :type x: list[float] :arg float x0: Value to find the index of. :returns: Index of x0 in the array. """ if x0 <= x[0]: k = 0 elif x0 >= x[-1]: k = len(x) - 2 else: k = [(xk > x0) for xk in x].index(True) - 1 return k
def compile_hierarchy_req_str_list(geo_list: dict, str_list: list) -> list: """Recursively go through geo config to get list ids and combine with their str. An example of hierarchial required geo ids would be: county subdivision: { '<state id>': { '<county id>': { '<county subdivision id>': '<county subdivision name>' } } } Args: geo_list: Dict of geo ids required for a particular summary level. str_list: List API query prefix string for each level of dict. Returns: List of required geo strings to be added to API call. """ ret_list = [] for k, v in geo_list.items(): if isinstance(v, dict): new_list = str_list.copy() new_list[1] = f'{str_list[0]}{k}{str_list[1]}' ret_list.extend(compile_hierarchy_req_str_list(v, new_list[1:])) else: ret_list.append(f'{str_list[0]}{k}') return ret_list
def arbi_poly(x, *params): """ Parameters ---------- x : numpy.ndarray takes the values of x where the value of polynomial is needed *params: tuple, numpy.ndarray values of coefficients of the polynomial lowest degree first ---------- returns ---------- numpy.ndarray : values of polynomial at desired x-values """ return sum([p*(x**i) for i, p in enumerate(params)])
def bitxor(a,b): """ bitwise XOR: 110 ^ 101 eq 011 """ return int(a) ^ int(b)
def check_peptide(peptide:str, AAs:set)->bool: """ Check if the peptide contains non-AA letters. Args: peptide (str): peptide sequence. AAs (set): the set of legal amino acids. See alphapept.constants.AAs Returns: bool: True if all letters in the peptide is the subset of AAs, otherwise False """ if set([_ for _ in peptide if _.isupper()]).issubset(AAs): return True else: return False
def _tags_to_dict(tags): """ convert tags from list if dicts to embeded dict """ result = {} for tag in tags: result[tag["Key"]] = tag["Value"] return {"Tags": result}
def validate_percentage(form): """ Functions checks, whether percentage is valid. If not, portfolio gets equally weighted. :param form: :return: form validated """ len_percentage = len(form['percentage']) len_symbol = len(form['symbol']) # check if all given numbers are greater than 0 valid_percentage = True for i in range(len_symbol): if form['percentage'][i] < 0: valid_percentage = False break # given input is incorrect, initialize list # with length of ticker list and weight equally if not (valid_percentage is True and sum(form['percentage']) == 1.0) and \ len_symbol == len_percentage: form['percentage'] = [1] * len_symbol form['percentage'][:] = \ [1.0 / len_symbol for _ in range(len_percentage)] return form
def get_likesfiles(model, selpop, likesdir, allfreqs = True, likessuffix= "neut"): """ locates master likelihood files for CMS component scores """ if not allfreqs: hi_likesfile = likesdir + model + "/master/likes_" + str(selpop) + "_hi_vs_" + likessuffix + ".txt" mid_likesfile = likesdir + model + "/master/likes_" + str(selpop) + "_mid_vs_" + likessuffix + ".txt" low_likesfile = likesdir + model + "/master/likes_" + str(selpop) + "_low_vs_" + likessuffix + ".txt" return hi_likesfile, mid_likesfile, low_likesfile else: likesfile = likesdir + model + "/master/likes_" + str(selpop) + "_allfreq_vs_" + likessuffix + ".txt_2" return likesfile return
def round_off_embedding(start_time, float_embed_width=0.5): """Round a number to the closest half integer. round_off_embedding(1.3) 1.5 round_off_embedding(2.6) 2.5 round_off_embedding(3.0) 3.0 round_off_embedding(4.1) 4.0 round_off_embedding(4.1, 0.25) 4.0 """ reciprocal = int(1 / float_embed_width) embed_id = round(start_time * reciprocal) / reciprocal embed_id = round(start_time * reciprocal) return embed_id
def sortmarkers(crms,end): """ Sort markers into chromosomes """ i = 0 crms_o = [[] for r in range(len(end))] crms_fo = [[] for r in range(len(end))] for crm in crms: for marker in crm: # add the marker start position at each chromosome. crms_fo[i].append(marker[1]) crms_fo[i].sort() # Sort the marker positions. i += 1 i = 0 for order in crms_fo: # Using the marker order set in crms_fo, fill crms_o # with all the marker information for pos in order: for mark in crms[i]: if pos==mark[1]: crms_o[i].append(mark) i += 1 return crms_o
def old_str_format_to_new(string): """ convert old format style to new style. Works for digits only %05d is converted to {:05d} :param string: :return: """ import re return re.sub(r"%(\d*d)", r"{:\1}", string)
def get_phrases(ls): """Get the set of phrases made by combining the strings in the given list. A phrase is obtained by concatenating any number of words in given order and without skipping any of them. Thus, if the given list has n words, the number of "phrases" possible is (n(n+1))/2. """ r = set() len_ls = len(ls) for i in range(len_ls): phrase = "" for j in range(i, len_ls): if j != i: phrase += " " phrase += ls[j] r.add(phrase) return r
def clean_key(func): """Provides a clean, readable key from the funct name and module path. """ module = func.__module__.replace("formfactoryapp.", "") return "%s.%s" % (module, func.__name__)
def format_end2end_prompt(q, ans, info=False): """Formats prompt for fine-tuned end-to-end truth/info scores with GPT-3""" if info: prompt = 'Q: {0}\nA: {1}\nHelpful:'.format(q, ans) else: prompt = 'Q: {0}\nA: {1}\nTrue:'.format(q, ans) return prompt
def task_id(identifier: str, id_type: str, version: str) -> str: """Make a task ID for an extraction.""" return f"{id_type}::{identifier}::{version}"
def safe_isinstance(obj, cls_str): """ Checks whether a given obj implements the class who's name is in the cls_str parameter. This means that the isinstance check is performed without looking at the object's type hierarchy, but rather by class name. """ if cls_str and obj: return cls_str in str(type(obj)) return False
def repeat_str(s, num): """ Repeat string :param s: string :param num: repeat number :return: string """ output = '' for i in range(0, num): output += s if len(output) > 0: output += ' ' return output
def filter_return_dict(ret): """Filter return dict for non-None values.""" return {key: val for key, val in ret.items() if val is not None}
def calc_m(q_c1ncs): """ m parameter from CPT, Eq 2.15b """ m = 1.338 - 0.249 * q_c1ncs ** 0.264 if q_c1ncs >= 254: m = 0.263823991466759 if q_c1ncs <= 21: m = 0.781756126201587 return m
def internal_backend_api_query(request_type): """ Returns prometheus query for the apisonator_listener_internal_api_response_codes metric with the request type passed in the parameters """ return f"apisonator_listener_internal_api_response_codes{{request_type=\"{request_type}\"}}"
def stringify_date(date: str) -> str: """ returns date in appropriate way for agenda """ date_elements = date.split('/') string_date = date_elements[2] + date_elements[1] + date_elements[0] return string_date
def merge_two_dicts(dict_1, dict_2): """Given two dicts, merge them into a new dict as a shallow copy. :param dict_1: dictionary 1 :param dict_2: dictionary 2 :return: merged dictionary """ if not dict_1: return dict_2 if not dict_2: return dict_1 out_dict = dict_1.copy() out_dict.update(dict_2) return out_dict
def check_self_for_redirect(obj): """Check if object has a _redirect property and return it if found.""" redirect = getattr(obj, '_redirect', None) return redirect or False
def format_metrics(metrics, split): """Format metric in metric dict for logging.""" return " ".join( ["{}_{}: {:.4f}".format(split, metric_name, metric_val) for metric_name, metric_val in metrics.items()])
def factorial(number): """ This recursive function calculates the factorial of a number In math, the factorial function is represented by (!) exclamation mark. Example: 3! = 3 * 2 * 1 = (6) * 1 3! = 6 """ if not isinstance(number, int): raise Exception("Enter an integer number to find the factorial") if number == 1 or number == 0: return 1 else: return number * factorial(number - 1)
def last(seq): """Return seq[-1]""" return seq[-1]
def importobj(modpath, attrname): """imports a module, then resolves the attrname on it""" module = __import__(modpath, None, None, ['__doc__']) if not attrname: return module retval = module names = attrname.split(".") for x in names: retval = getattr(retval, x) return retval
def get_energy_diff(data): """ Compute the differences between data points in the time series of tuples (date, vt, mt). The result is a list of (date, vt_delta, mt_delta) with vt_delta and mt_delta being the amount of energy at date since the preceding date point. """ diff_data = [ [ d[0] for d in data[1:] ] ] for c in range(1, 3): diff = [ b[c] - a[c] for a, b in zip(data[:-1], data[1:]) ] diff_data.append(diff) return list(zip(diff_data[0], diff_data[1], diff_data[2]))
def get_longest_aligned_blocks_between_aligned_seqs(seq1, seq2, gap_char = '-', verbose = 0): """takes two aligned sequences and returns the longest aligned block between the two sequences the gap_char specifies the gap character in the alignment. parameters ---------- seq1: str first sequence in the alignment seq2: str second sequence in the alignment gap_char: str character that specifies a gap character in the alignment verbose: 0,1 set to 1 for debugging output return ------ int""" assert isinstance(seq1, str), 'the first sequence was not a string type' assert isinstance(seq1, str), 'the second sequence was not a string type' assert isinstance(gap_char, str), 'the gap character was not a string type' assert isinstance(verbose, int), 'your input for verbose was not an integer' assert verbose in [0,1], 'your input for verbose can only 0 or 1' segments = [] temp_str_pair = [] # creates a sequence of paired tuples, the # tuples contain the nucleotides as the ith position # of both sequences in the alignmend paired_seq_nucs = list(zip(seq1,seq2)) if verbose == 1: print('paired tuple sequence of ith positions of sequence pair: {}'.format(paired_seq_nucs)) # loops over the list of paired tuples # and appends the tuple to a temporary list, if a gap is encountered # in any of the tuples, temporary list is appended to another list then # emptied, note that the temporary list is consists of 1 aligned block. for pair in paired_seq_nucs: # presence of a gap means the previous if gap_char in pair: segments.append(temp_str_pair) if verbose == 1: print('aligned block to append: {}'.format(temp_str_pair)) print('current aligned blocks: {}'.format(segments)) temp_str_pair = [] else: temp_str_pair.append(pair) segments.append(temp_str_pair) if verbose == 1: print('current block list: {}'.format([i for i in segments if len(i) > 0])) print('current block total: {}'.format(len([i for i in segments if len(i) > 0]))) if verbose == 1: print('aligned blocks: {}'.format([i for i in segments if len(i) > 0])) print('aligned block lengths: {}'.format([len(i) for i in segments if len(i) > 0])) print('max aligned block length: {}'.format(max([len(i) for i in segments if len(i) > 0]))) return max([len(i) for i in segments if len(i) > 0])
def check_sum(data): """ checksum = 255 - ((id + length + data1 + data2 + ... + dataN) & 255) """ # print(data) return 255 - (sum(data) & 255)
def remove_from_qset_definition(qset_definition, node): """Return quorum set definition with the given node removed and the threshold reduced by 1""" threshold = qset_definition['threshold'] validators = qset_definition['validators'] if node in validators: validators = validators.copy() validators.remove(node) threshold -= 1 inner_quorum_sets = [ remove_from_qset_definition(inner_qset_definition, node) for inner_qset_definition in qset_definition['innerQuorumSets'] ] return { 'threshold': threshold, 'validators': validators, 'innerQuorumSets': inner_quorum_sets }
def _category_metrics(category_name, categories_list): """Auxiliary function returning all available metrics in a single category as a list of dicts """ cat_counts = [] for item in categories_list: if item.get('name') == category_name: cat_counts += item.get('count_types', []) return cat_counts
def extend_str(str_in, char, length, left=False): """Extends the string 'str_in' to the length 'length' with the given 'char'""" s = str(str_in) while len(s) < length: s = char + s if left else s + char return s
def or_default(value, default): """ Helps to avoid using a temporary variable in cases similiar to the following:: if slow_function() is not None: return slow_function() else: return default """ return value if value is not None else default
def std_var_norm (Spectrum , mean): """Compute normalisation coefficient for intensity normalisation""" norm=0 for i in range(len(Spectrum)): norm = norm + pow((Spectrum[i]-mean),2); norm = pow(norm, 0.5)/(len(Spectrum)-1) if norm == 0: norm = 1; return norm
def _is_image(shape: list) -> bool: """Whether the shape has 2 dimension that has rank larger than 1.""" return sum([1 for s in shape if s > 1]) == 2
def get_package_name_and_type(package, known_extensions): """Return package name and type. Package type must exists in known_extensions list. Otherwise None is returned. >>> extensions = ['tar.gz', 'zip'] >>> get_package_name_and_type('underscored_name.zip', extensions) ('underscored_name', 'zip') >>> get_package_name_and_type('unknown.extension.txt', extensions) """ for package_type in known_extensions: if package.endswith('.'+package_type): # Package name is name of package without file extension # (ex. twill-7.3). return package[:package.rfind('.'+package_type)], package_type
def table(context, table_rows): """ Template tag for TableRender class. """ return { 'headers': table_rows[0], 'rows': table_rows[1:], 'show_header': context.get('show_header', True) }
def decision_variable_to_array(x): """Generate "one-hot" 1d array designating selected action from DDM's scalar decision variable (used to generate value of OutputPort for action_selection Mechanism """ if x >= 0: return [x,0] else: return [0,x]
def ForwardTargetName(build_tool_version_name): """Returns the target name for a forward compatibility build tool name.""" make_target_name = 'RSTestForward_{}'.format(build_tool_version_name) make_target_name = make_target_name.replace('.', '_') return make_target_name
def clamp(val: float, minval: float, maxval: float) -> float: """ Clamp a value to within a range :param float val: The value to clamp :param float minval: The minimum value :param float maxval: The maximum value :returns: The value, clamped to the range specified """ if val < minval: return minval if val > maxval: return maxval return val
def get_errors(*args, **kwargs): """ Generate an error message given the actual message (msg) and a prefix (prefix) >>> get_errors('Coredumped', prefix='Error:') 'Error: Coredumped' >>> get_errors('Coredumped', prefix='(system)') 'Error: (system) Coredumped' """ prefix = kwargs.get('prefix', 'Error:') if prefix is not 'Error:': prefix = 'Error: '+ prefix msg = ' '.join(args) error_msg = prefix + ' ' + msg return error_msg
def evaluate_numeric_condition(target, reveal_response): """ Tests whether the reveal_response contains a numeric condition. If so, it will evaluate the numeric condition and return the results of that comparison. :param target: the questions value being tested against :param reveal_response: the numeric condition that will be evaluated against :return: boolean result of numeric condition evaluation or None if there is no numeric condition to evaluate. """ if target == '': # cannot evaluate if answer is blank return None if reveal_response.startswith('>='): return float(target) >= float(reveal_response[2:]) elif reveal_response.startswith('<='): return float(target) <= float(reveal_response[2:]) elif reveal_response.startswith('=='): return float(target) == float(reveal_response[2:]) elif reveal_response.startswith('<'): return float(target) < float(reveal_response[1:]) elif reveal_response.startswith('>'): return float(target) > float(reveal_response[1:]) return None
def drawmaze(maze, set1=[], set2=[], c='#', c2='*'): """returns an ascii maze, drawing eventually one (or 2) sets of positions. useful to draw the solution found by the astar algorithm """ set1 = list(set1) set2 = list(set2) lines = maze.strip().split('\n') width = len(lines[0]) height = len(lines) result = '' for j in range(height): for i in range(width): if (i, j) in set1: result = result + c elif (i, j) in set2: result = result + c2 else: result = result + lines[j][i] result = result + '\n' return result
def highest_knowledge(devices, devices_knowledge): """ Format: {shortDeviceId: knowledge_number} where 'shortDeviceId' = each *.ydevice file found and knowledge_number is the number after the hyphen where 'shortDeviceId' == knowledge_letter """ k = {} for shortDeviceId in devices: k[shortDeviceId] = devices_knowledge[shortDeviceId][shortDeviceId] return k
def format_udm_open(db_name, sequence_num, timestamp): """Return formatted opening <UDM ...> entity.""" return '<UDM DATABASE="{}" SEQUENCE="{}" TIMESTAMP="{}">\n'.format( db_name, sequence_num, timestamp)
def normalize_platform(platform, python2=True): """ Normalize the return of sys.platform between Python 2 and 3. On Python 2 on linux hosts, sys.platform was 'linux' appended with the current kernel version that Python was built on. In Python3, this was changed and sys.platform now returns 'linux' regardless of the kernel version. See https://bugs.python.org/issue12326 This function will normalize platform strings to always conform to Python2 or Python3 behavior. :param str platform: The platform string to normalize :param bool python2: The python version behavior to target. If True, a Python2-style platform string will be returned (i.e. 'linux2'), otherwise the modern 'linux' platform string will be returned. :returns: The normalized platform string. :rtype: str """ if python2: return "linux2" if platform.startswith("linux") else platform return "linux" if platform.startswith("linux") else platform
def render_srm(color_srm): """Convert the SRM to a valid HTML string (if known)""" if not color_srm: return '#ffffff' # round the color to an int and put it in the inclusive range [1, 30] int_color = min([int(color_srm), 30]) if int_color < 1: return '#ffffff' # source: # https://www.homebrewtalk.com/forum/threads/ebc-or-srm-to-color-rgb.78018/#post-820969 color_map = { 1: '#F3F993', 2: '#F5F75C', 3: '#F6F513', 4: '#EAE615', 5: '#E0D01B', 6: '#D5BC26', 7: '#CDAA37', 8: '#C1963C', 9: '#BE8C3A', 10: '#BE823A', 11: '#C17A37', 12: '#BF7138', 13: '#BC6733', 14: '#B26033', 15: '#A85839', 16: '#985336', 17: '#8D4C32', 18: '#7C452D', 19: '#6B3A1E', 20: '#5D341A', 21: '#4E2A0C', 22: '#4A2727', 23: '#361F1B', 24: '#261716', 25: '#231716', 26: '#19100F', 27: '#16100F', 28: '#120D0C', 29: '#100B0A', 30: '#050B0A', } return color_map[int_color]
def foo_2(a: int = 0, b: int = 0, c=0): """This is foo. It computes something""" return (a * b) + c
def bio2ot_ts(ts_tag_sequence): """ perform bio-->ot for ts tag sequence :param ts_tag_sequence: :return: """ new_ts_sequence = [] n_tags = len(ts_tag_sequence) for i in range(n_tags): ts_tag = ts_tag_sequence[i] if ts_tag == 'O' or ts_tag == 'EQ': new_ts_sequence.append('O') else: pos, sentiment = ts_tag.split('-') new_ts_sequence.append('T-%s' % sentiment) return new_ts_sequence
def _poker_build_player_dic(data: dict, matches: list) -> dict: """Updates Player Class""" player_dic = {} for match in matches: for player_index in data.keys(): for key in match.players_data[player_index].player_money_info.keys(): temp_df = match.players_data[player_index].player_money_info[key] if player_index in player_dic.keys(): if key not in player_dic[player_index]['Games']: val = player_dic[player_index] val['Player Names'] = list(set(val['Player Names'] + list(temp_df['Player Names'][0]))) val['Player Ids'] = list(set(val['Player Ids'] + [player_index])) val['Buy in Total'] += int(temp_df['Buy in Total']) val['Loss Count'] += int(temp_df['Loss Count'][0]) val['Leave Table Amount'] += temp_df['Leave Table Amount'][0] val['Game Count'] += 1 val['Games'].append(key) else: player_dic[player_index] = {'Player Names': list(temp_df['Player Names'][0]), 'Player Ids': [player_index], 'Buy in Total': int(temp_df['Buy in Total'][0]), 'Loss Count': int(temp_df['Loss Count'][0]), 'Leave Table Amount': temp_df['Leave Table Amount'][0], 'Game Count': 1, 'Games': [key]} return player_dic