content
stringlengths
42
6.51k
def _drop_decimals(decimal): """Decimal.normalize gives 2E+1 for 20...""" decimal = str(decimal) if "." in decimal: decimal = decimal.rstrip("0").rstrip(".") return decimal
def cycles2perm(cycles): """ Convert permutation in cycle notation to permutation in one-line notation :param cycles: Permutation in cycle notation :type cycles: list :return: Returns permutation in one-line notation :rtype: list """ n = max([item for sublist in cycles for item in subl...
def valid_recipient_dict(recipient): """Check the recipient dict has a good email address :param recipient: dict type with a key of e_mail in it :returns: boolean True if valid """ if recipient is None: return False if "e_mail" not in recipient: return False if recipient.get...
def get_api_auth_headers(api_key): """ Return HTTP Authorization header using WDL API key WDL follows the Authorization: <type> <credentials> pattern that was introduced by the W3C in HTTP 1.0. That means the value of your Authorization header must be set to: "Bearer <API Key>". The API K...
def is_empty(value: object) -> bool: """ Check if value is None or not empty in case if not None. """ return (value is None) or (not value)
def get_armstrong_value(num): """Return Armstrong value of a number, this is the sum of n**k for each digit, where k is the length of the numeral. I.e 54 -> 5**2 + 4**2 -> 41. Related to narcisstic numbers and pluperfect digital invariants. """ num = str(num) length = len(num) armstrong_...
def check_upload_file(file_path, upload_info): """Check that the file is already in the upload list. Args: file_path (str): File path. upload_info (dict): Upload json info. Returns: bool. """ for one_file in upload_info.get("asset"): if one_file["local"] == file_pa...
def flatten_list(lst_of_lsts): """ Flattens the list of lists lst_of_lsts. :param lst_of_lsts: a list of lists :return: flattened list """ if all([isinstance(e, (list, tuple)) for e in lst_of_lsts]): return [e for l1 in lst_of_lsts for e in l1] elif any([isinstance(e, (list, tuple)) ...
def wrap(text, width): """ A word-wrap function that preserves existing line breaks. Expects that existing line breaks are posix newlines. Preserve all white space except added line breaks consume the space on which they break the line. Don't wrap long words, thus the output text may have line...
def sizeof_fmt(num): """Display bytes as human readable.""" if num == 0: return '0 byte' for x in ['bytes','KB','MB','GB']: if num < 1024.0 and num > -1024.0: return "%3.1f %s" % (num, x) num /= 1024.0 return "%3.1f %s" % (num, 'TB')
def format_iterable(iterable, format_char="'"): """Adds a format char around the members of an iterable""" def _add_char(sub): return '{char}{sub}{char}'.format(char=format_char, sub=sub) return ', '.join(map(_add_char, iterable))
def binary_search_iterative(array, item): """Time Complexity: O(log*n) because you are constantly dividing the length of array by 2 until array length is 1 Space Complexity: O(1) """ left, right = 0, len(array) - 1 if len(array) == 0: return None while left <= right: middle = ...
def env_error(key: str) -> str: """ Return error message """ return (f"Not found \"{key}\" in environments, using python " + "-m torch.distributed.launch to launch the command")
def norm_histogram(hist): """ takes a histogram of counts and creates a histogram of probabilities :param hist: list :return: list """ j = 0; hist_sum = 0; hist_new = []; while j < len(hist): hist_sum = hist_sum + hist[j]; j += 1; for i in hist: p...
def typename_from_type(t): """ """ if issubclass(t, dict): return "dictionary" if issubclass(t, list): return "list" if issubclass(t, str): return "string" if hasattr(t, "__name__"): return t.__name__ return "object"
def _trim_bounds(arr): """ Returns the bounds which would be used in numpy.trim_zeros """ first = 0 for i in arr: if i != 0.0: break else: first = first + 1 last = len(arr) for i in arr[::-1]: if i != 0.0: break else: la...
def generate_name(fname): """ generate a proper guard name """ ret = fname.upper() ret = ret.replace("\\", "_") ret = ret.replace("/", "_") ret = ret.replace(".", "_") ret = ret.replace("-", "_") return "_%s_" % (ret) return ret
def _min(*args): """"Returns the minimum value.""" return min(*args)
def next_highest_power_of_2(n): """Ugh, this implementation is so dumb. We also assume that we are being called in a tiling context, in which case numbers less than 256 should be bumped up to 256 (the number of pixels in a single tile). """ p = 256 while p < n: p *= 2 return p
def parse_file_tags(filetags): """ Parse list of filetags from commandline. :param filetags: list of strings with filepath. optionally appended by the first letter that should be used for read and mate :return: annotate_with, tag_prefix, tag_prefix_mate >>> filetags = ('file_a...
def make_table(t): """Make a reStructured Text Table Returns ------- A string containing a reStructured Text table. """ column_widths = [] table = "\n" if len(t) <= 0: return table # Figure out how wide to make each column for col in t[0]: column_widths.append...
def sqrt(x): """ give square root """ if x >= 0: """ if x is positive""" return x ** 0.5 return (x + 0j) ** 0.5
def get_clean_name(name): """ A convenience function for naming the output files. :param name: A name of the target file. :returns: The name suffixed with "_clean" and the file extension. """ name = name.split(".") name = name[0] + "_clean." + name[1] return name
def is_deletion(hgvs): """ This function takes an hgvs formatted string and returns True if the hgvs string indicates there was a deletion. Parameters ---------- hgvs : string hgvs formatted string Returns ------- deletion : bool True if hgvs string is indicates a d...
def get_small_portion(h, w, grid = (2, 3)): """ in a grid, how many pixels are consider small? """ grid_r, grid_c = grid grid_h = int(h / grid_r) grid_w = int(w / grid_c) grid_n = grid_h * grid_w threshold = int(grid_n * 0.05) print('(h = {}, w= {}), grid = ({})'.format(h, w...
def printable(id): """ Turn a Python identifier into something fit for human consumption. >>> printable('author') 'Author' >>> printable('all_dependencies') 'All Dependencies' """ return ' '.join(word.capitalize() for word in id.split('_'))
def partition(section, low, high): """Partition step of quickstep (the meat of it, does the sorting). The pivot point is selected as the median of three, because this has good performance with already sorted data -- and ya know, most of the time you need to sort something, it's mostly sorted. ...
def sorted_by_precedence(values): """ Return ``values`` sorted ascending by their ``precedence`` property. :param values: Sequence of values to sort (each value must have a ``precedence`` property) :return: Sorted list of values :rtype: :class:`list` """ return sorted(val...
def pascal_triangle(n): """Pascal Triangle""" triangle = [] if n <= 0: return triangle triangle = [[1]] for i in range(n - 1): line = triangle[-1] aux = [1] for i in range(len(line) - 1): aux.append(line[i] + line[i + 1]) aux.append(1) tr...
def birthdays(string): """ Takes a multiline string and returns the numbers that represent the same dates.""" # Break the string up into an array, sort it and filter out the junk. kt_list = string.split() kt_sorted = sorted(kt_list) kt_filtered = [x for x in kt_sorted if x != ''] # Here we a...
def median(iterable): """ Compute the median value in the given iterable - which must be finite and non-empty. """ values = sorted(iterable) le = len(values) assert le if le % 2 == 1: return values[le // 2] else: return (values[le // 2 - 1] + values[le // 2]) / 2
def flatten_dict(d: dict) -> dict: """Flatten dictionary d Example >>> flatten_dict(d={"a":{1}, "b":{"yes":{"more detail"}, "no": "level below" }}) returns {'a': {1}, 'b.yes': {'more detail'}, 'b.no': 'level below'} """ def items(): for key, value in d.items(): if i...
def get_omnipresent_at_pos(fragFreqCounters, n, **kwargs): """ Find patterns in ``fragFreqCounters`` for which the frequency is ``n``. fragFreqCounters is a dictionary (usually keyed on 'fragments') of whose values are dictionaries mapping positions to frequencies. For example:: { ...
def remove_file_prefix(file_path, prefix): """ Remove a file path prefix from a give path. leftover directory separators at the beginning of a file after the removal are also stripped. Example: '/remove/this/path/file.c' with a prefix of: '/remove/this/path' becomes: ...
def patient_eval_before_2015(patient_eval_date, patient_phen): """Gets an updated dictionary of patient phenotype, with patients before 2015 with no negative \ values (cf paper for explanation of possible bias) Parameters: patient_eval_date (dict): dict with patient as key, evaluation date as value ...
def make_text_labels(hover_labels): """ Take hover lables and remove all except the first and the last label (excluding None) Turns [None, None, 30%, 29%, 28%, 34%] into [None, None, '30%', None, None, '34%'] """ hover_len = len(hover_labels) text_labels = [None] * hover_len i = 0 while...
def fibonacci(n: int) -> int: """ Calculate the nth Fibonacci number using naive recursive implementation. :param n: the index into the sequence :return: The nth Fibonacci number is returned. """ if n == 1 or n == 2: return 1 else: return fibonacci(n - 1) + fibonacci(n - 2)
def one_hot_encode(label): """ Given a label - "red", "green", or "yellow". Returns a one-hot encoded label """ if label == "red": return [1, 0, 0] if label == "green": return [0, 0, 1] return [0, 1, 0]
def join(a, *p): """Join two or more pathname components, inserting '/' as needed. If any component is an absolute path, all previous path components will be discarded. """ path = a for b in p: if b.startswith('/'): path = b elif path == '' or path.endswith('/'): ...
def correct_date(date): """ Converts the date format to one accepted by SWA SWA form cannot accept slashes for dates and is in the format YYYY-MM-DD :param date: Date string to correct :return: Corrected date string """ if date is None: return "" else: a, b, c = date.s...
def shorten_string(input_string: str, length: int) -> str: """Shorten a string in a nice way: >>> shorten_string("foobar", 5) 'fo...' """ if len(input_string) < length: return input_string if length > 3: return input_string[: length - 3] + "..." if length == 3: retur...
def isInt(x) -> bool: """Decide whether or not something is either an integer, or is castable to integer. :param x: The object to type-check :return: True if x is an integer or if x can be casted to integer. False otherwise :rtype: bool """ try: int(x) except (TypeError, ValueError)...
def is_candidate(wordlist, word): """True if word is a candidate for the homophone problem, in that it's five letters long, and removing either of the first two letters also results in a word. wordlist: dictionary of words word: string """ word1 = word[1:] word2 = word[0]+word[2:] # ...
def parse_function_path_string(string): """ takes in the function string and splits it into the module path and function path. :param string: :return: """ list_ = string.split('.') module_path = '.'.join(list_[:-1]) function_path = list_[-1] return module_path, function_path
def prettyPrintLength( n ): """ takes an integer with a number of bases, returns a string with the number displayed nicely with units. """ if float( n ) / 1000000000.0 >= 1: v = '%.2f' % ( float(n) / 1000000000.0 ) v = v.strip('0').strip('.') units = 'Gb' elif float( n ) ...
def sanitize_prefix(prefix): """ Sanitizes a prefix to be used for TiKz coordinates. Allowed characters are lower case ASCII letters, digits and the hyphen. """ import string as s allowed = s.ascii_lowercase + s.digits + '-' return ''.join(c for c in prefix.lower() if c in allowed)
def get_offset(x: int) -> int: """ :param x: :return: """ return int(x) if x else 0
def column(matrix, i): #select i columns of array. """Select ith column of np.array object""" return [row[i] for row in matrix]
def find_range(nums): """Calculate the range of a given set of numbers.""" lowest = min(nums) highest = max(nums) r = highest - lowest return lowest, highest, r
def get_sessid(rsp: bytes): """Search session ID from RTSP strings""" for line in rsp.decode().split("\r\n"): ss = line.split() if ss[0].strip() == "Session:": return int(ss[1].split(";")[0].strip())
def one_rgba(c): """ convert a single color value to (r, g, b, a) input can be an rgb string 'rgb(r,g,b)', '#rrggbb' if we decide we want more we can make more, but for now this is just to convert plotly colorscales to pyqtgraph tuples """ if c[0] == "#" and len(c) == 7: return (int(...
def transform_sex(value): """Transform helix sex/geslacht value to lims sex/geslacht value.""" if value.strip(): if value.upper() == 'M': return 'Man' elif value.upper() == 'V': return 'Vrouw' elif value.upper() == 'O': return 'Onbekend' else: ...
def degreesToDottedDecimal(deg, mnt=0, sec=0): """ Accepts dms and converts to dd :param int deg: degrees :param int mnt: minutes :param int sec: seconds :return: dotted decimal format :rtype: float """ return float(round(deg + (mnt / 60) + (sec / 3600), 6))
def bytes_to_int(hex_string) -> int: """ :param hex_string: a string formatted like 3f:8d:1a:35:a8:ff :return: integer value of the hex string """ return int.from_bytes(hex_string, "big")
def sql_sanitize(sql_name): """ Return a SQL name (table or column) that has been cleaned of problematic characters. ex. punctuation )(][; whitespace This is not to be used with values, which can be properly escaped with parameterization. Ideally retaining only alphanumeric char. Credits: Donald...
def convert_branch(branch): """ Convert release branch to MediaSDK and Media-driver branches :param branch: Branch name :type branch: String :return: MediaSDK branch, Media-driver branch :rtype: tuple """ if branch == 'mss2018_r2': return branch, 'master' if 'sdk' in bran...
def _get_file_paths(cur): """Retrieve a list of file paths, recursively traversing the """ out = [] if isinstance(cur, (list, tuple)): for x in cur: new = _get_file_paths(x) if new: out.extend(new) elif isinstance(cur, dict): if "class" in cur:...
def get_variable(env, localenv, key): """Searchs for a variable in the bash env or in a file env.""" if key in env: return env[key] if key in localenv: return localenv[key] raise SystemExit("Variable {} has no value".format(key))
def and_(left, right): """:yaql:operator and Returns left operand if it evaluates to false. Otherwise evaluates right operand and returns it. :signature: left and right :arg left: left operand :argType left: any :arg right: right operand :argType right: any :returnType: any (left o...
def getCoord(percentX, percentY, image_size): """ Returns the width and height coordinates given the percentage of the image size you want percentX - percentage along x axis percentY - percentage along y axis image_size - tuple (width, height) of the total size of the image @return - tuple f...
def get_blob_size(keypoints): """Find the size of biggest keypoint """ max_size = 0 for keys in keypoints: if keys.size >= max_size: max_size = keys.size print('Diameter is------------------>', round(max_size)) # to confirm the blob size detection return ma...
def convert_lat(lat): """Convert a single latitude value to a floating point number. Input latitude can be string or float and in -24 or 24S format. """ lat = str(lat) if 'N' in lat.upper(): lat = float(lat[:-1]) elif 'S' in lat.upper(): lat = float('-'+lat[:-1]) else: ...
def parse_records(cmd_output: list, record_type: str) -> list: """ Parse command output for A records Arguments: cmd_output(list): Command output Returns: list: List of data containing dicts """ if not cmd_output: return [] return [ rec for rec...
def get_drop_down_xml(name, command, labels, help='', values=None): """Get the XML content for a drop down menu when making a ParaView plugin.""" def _enum(labels, values=None): if values is None: values = range(len(labels)) els = [] for i, lab in enumerate(labels): ...
def dscp_class(bits_0_2, bit_3, bit_4): """ Takes values of DSCP bits and computes dscp class Bits 0-2 decide major class Bit 3-4 decide drop precedence :param bits_0_2: int: decimal value of bits 0-2 :param bit_3: int: value of bit 3 :param bit_4: int: value of bit 4 :return: DSCP cla...
def camel_to_snake_case(snake_str: str) -> str: """ Convert a `CamelCase` string to `snake_case`. .. code-block:: python >>> camel_to_snake_case("CamelCase") "camel_case" Args: snake_str (str): String formatted in CamelCase Returns: str: String formatted in snake_...
def all_rpc_url(live_server): """Return the default RPC test endpoint URL. See 'testsite.urls' for additional info.""" return live_server + '/all-rpc/'
def processing_lines( lines: list, skip_lines: list = ["# Databricks notebook source\n"] ): """Apply logic to transform databricks specific lines to jupyter lines. Args: lines (list): contains each line of code skip_lines (list, optional): Lines to be skipped. Defaults to ["# Databricks not...
def _get_filter_list(filter_header): """Returns a cleaned list from the provided header string.""" if filter_header is None: return [] filters = [item.strip() for item in filter_header.rstrip(",").split(",")] return filters
def is_palindrome(my_str): """ Recursive palindrome validator :param my_str: String :return: Boolean """ my_str = my_str.lower() if len(my_str) <= 1: return True else: if my_str[0] != my_str[-1]: return False else: return is_palindr...
def lon(source): """Convert source bytes to longitude (deg, mim) pair. Longitude: 08014.5267 = DDDMM.MMMM >>> lon(b'08014.5267') (80, 14.5267) """ if len(source) == 0: return None, None dd= int(source[:3]) mm= float(source[3:]) return int(dd), float(mm)
def linkable_latitude(value): """ Append proper direction to a float represented latitude. Example: In: 45.06112 Out: 45.06112N """ value = float(value) direction = 'N' if value > 0 else 'S' value = abs(value) return '{0}{1}'.format(value, direction)
def __to_sentence(sentence): """ Convert a sentence annotation to a gloss. """ ret = "" for tok in sentence['tokens']: ret += tok['originalText'] + tok['after'] return ret
def formatTypes(types): """ returns a string "type1;type2;" for the database """ res = "" for i in range (len(types) - 1, -1, -1): res += types[i]["type"]["name"] + ";" return res
def jerarquia(operador): """retorna el la jerarquia de un operador""" if operador == "+" or operador == "-": return 1 else: return 2
def _GetMsgId(msg_start, line_number, msg_start_table): """Construct the meessage id given the msg_start and the line number.""" hex_str = '%x%04x' % (msg_start_table[msg_start], line_number) return int(hex_str, 16)
def get_dict_value_deep(adict, key, prefix=None, as_array=False, splitter='.'): """Used to get value from hierarhic dicts in python with params with dots as splitter""" if prefix is None: prefix = key.split(splitter) if len(prefix) == 1: if type(adict) == type({}): if not prefix[...
def ascii(text): """Convert text to ascii-only characters""" try: return ''.join(i if ord(i) < 128 else '' for i in text) except: return str(text)
def _validate_unique_msg(dialect, msg, constraint_name=None): """ Does the heavy lifting for validate_unique_exception(). Broken out separately for easier unit testing. This function takes string args. """ if constraint_name is not None and dialect != 'sqlite' and constraint_name not in ms...
def swap(lst, idx1, idx2): """ >>> swap([0, 1, 2], 0, 1) [1, 0, 2] >>> swap([0, 1, 2], 0, 0) [0, 1, 2] """ # print("Swapping [{}, {}] from {}".format(idx1, idx2, lst)) lst[idx1], lst[idx2] = lst[idx2], lst[idx1] # print("resulting to {}".format(lst)) return lst
def RekallStringRenderer(x): """Function used to render Rekall 'str' objects.""" try: return x["str"] except KeyError: return x["b64"]
def get_items(source): """Retrieve all the items from the given dataset and put them into a list. Args: source: input dataset Returns: list of items """ items = [el for el in source] return sorted(items)
def get_server_cloud(server_name): """Get the server cloud from the server name.""" if "." in server_name: server_name, server_domain = server_name.split(".", 1) return (server_name, server_domain) else: return (server_name, None)
def command(cmd, print_out = False): """ Runs a command in the underlying shell Parameters: ----------- cmd : str string containing the command to run print_out : bool if True prints out stdout and stderr after capturing it Returns: -------- code: int ret...
def check_all_st_are_eq(line, pattern): """ A function that: - retrieve all column values that are just after any column containing the pattern. - check that all those values are exactly the same. """ size = len(line) l = [] for i in range(0, size): if pattern...
def return_route_str(node_index_list): """This method converts routes (node_index_list) to string-format :param node_index_list: list of node indices :type: list :return: "-" separated string :rtype: str """ return "-".join([str(x) for x in node_index_list])
def unique_contributors(nodes, node): """ Projects in New and Noteworthy should not have common contributors """ for added_node in nodes: if set(added_node['contributors']).intersection(node['contributors']) != set(): return False return True
def resize_dims_from_str(resize_dims_str): """ Parses a command line argument string for the resize parameters. :param resize_dims_str: comma-separated integers, e.g. "600,1000". :return: list of integers. """ return [int(dim) for dim in resize_dims_str.split(',')]
def get_per_page(request): """ :param user: User instance :return: """ if hasattr(request, 'user_rbac'): user_rbac = request.user_rbac if user_rbac is not None: user = user_rbac.user if hasattr(user, 'userinfo'): return user.userinfo.per_page i...
def build_merged_index(merged_modules, quadrilaterals): """Creates a mapping (dict) of the form {module_id: merged_module_id}. Here, `module_id` is the original module ID as in the quadrilaterals dict. The `merged_module_id` corresponds to the module ID of the first module the module is merged with. If ...
def large_intervals(genotype, max_interval=9, weight=20): """takes genotype and gives fitness penalty for large intervals Args: genotype ((int, int)[]): list of tuples (pitch, dur) representing genotype of a chromosome max_interval (int, optional): Defaults at 9. Defines max interval befo...
def longest_common_subsequence_dp(s1, s2): """Longest common subsequence by dynamic programming. Time complexity: O(n1*n2). Space complexity: O(n1*n2). """ n1, n2 = len(s1), len(s2) M = [[0] * (n2 + 1) for _ in range(n1 + 1)] for r in range(1, n1 + 1): for c in range(1, n2 + 1): ...
def calculate_run_metrics(accuracies): """Calculates average accuracy, forgetting, and learning accuracy given accuracies on each task for model after every task. """ average_accuracy = 0 forgetting = 0 learning_accuracy = 0 for task_id in accuracies: average_accuracy += accuracies[t...
def encapsulate(key, data): """ encapsulate the data with a key, and wrap with code, data :param key: :param data: :return: """ return { 'code': 200, 'data': { key: data } }
def format_date(date_dict): """Format a date to "standard" Oxford format :param date_dict: date dict :return: String """ return "%(day_name)s, %(week)d%(ordinal)s week, %(term_long)s %(year)d (%(day_number)d %(month)s)" % date_dict
def if_unicode_to_bytes(string, codec='UTF-8'): """Encode if Unicode to Bytes UTF8. Args: string (bytes): Bytes String codec (str): codec type Returns: UTF8 encoded string """ try: return string.encode(codec) except Exception: return string
def atfile_ivm(filename): """ Return the filename of the IVM file which is assumed to be the second word in the atfile the user gave. """ return filename.split()[1]
def is_source(cur_ind, graph, list_deg): """Check if the variable modified in the current command is used as a source for any other command in the loop """ used = False var_out = [] deg_max = 0 for (source_ind, target_ind, used_var) in graph: if source_ind == cur_ind and not used: ...
def get_url(search_term): """ Generate a url for search term """ template = 'https://www.amazon.com/s?k={}&ref=nb_sb_noss_1' search_term = search_term.replace(' ', '+') url = template.format(search_term) url += '&page={}' return url
def str_repr(string): """ >>> print(str_repr('test')) 'test' >>> print(str_repr(u'test')) 'test' """ result = repr(string) if result.startswith('u'): return result[1:] else: return result