content
stringlengths
42
6.51k
def GetTestName(test, sep='#'): """Gets the name of the given test. Note that this may return the same name for more than one test, e.g. if a test is being run multiple times with different parameters. Args: test: the instrumentation test dict. sep: the character(s) that should join the class name and the method name. Returns: The test name as a string. """ test_name = '%s%s%s' % (test['class'], sep, test['method']) assert ' *-:' not in test_name, ( 'The test name must not contain any of the characters in " *-:". See ' 'https://crbug.com/912199') return test_name
def is_anagram(word1, word2): """Takes 2 strings, returns True if words are anagrams, otherwise False""" w1 = list(word1) w2 = list(word2) w1.sort() w2.sort() return w1 == w2
def extract_app_version(lines): """ Extracts version string from array of lines (content of version.txt file) :param lines: :return: version string """ for line in lines: parts = [elem.strip() for elem in line.split('=')] if len(parts) == 2 and parts[0].lower() == 'version_str': return parts[1].strip("'") return ''
def _check_supported(label, support_dict): """ See if we can handle it. """ if label in support_dict: return True else: return False
def merge_dicts(*dict_args): """ Given any number of dicts, shallow copy and merge into a new dict, precedence goes to key value pairs in latter dicts. Taken from https://stackoverflow.com/a/26853961/6326903 """ result = {} for dictionary in dict_args: result.update(dictionary) return result
def is_in_strs(src): """ Return a list with an element for each boundary in `src`, where each element is `True` if it's "inside a string" and `False` otherwise. The beginning of a string section in `src` should be marked with `(` and the end marked with `)`. However, note that the difference between the two markers is purely stylistic, and the same result will be produced regardless of the marker being used. >>> is_in_strs("") [False] >>> is_in_strs("x") [False, False] >>> is_in_strs("'(") [False, True] >>> is_in_strs("'()'") [False, True, False] >>> is_in_strs("'(a)'") [False, True, True, False] >>> is_in_strs("x = '(a)'") [False, False, False, False, False, True, True, False] """ in_str = False in_strs = [in_str] for substr in src.replace(")", "(").split("("): mod = 1 if in_str else -1 in_strs += [in_str] * (len(substr) + mod) in_str = not in_str if len(src) != 0 and in_str: in_strs += [False] return in_strs
def find_upper_bound(x): """ find_upper_bound returns an integer n with n >= len(x), without using the len() function. The complexity is O(log(len(x)). """ n = 1 while True: try: v = x[n] except IndexError: return n n *= 2
def get_product_position(x, y): """Find the product's position in the recall announcment based on the label. Otherwise return 0,0, '' to signify that the product does not exist.""" if str(y) in str(x): result_start = x.index(y) result_end = result_start + len(y) return result_start, result_end, 'PRODUCT' else: return 0, 0, ""
def check_structure(struct): """ Return True if the monophyly structure represented by struct is considered "meaningful", i.e. encodes something other than an unstructured polytomy. """ # First, transform e.g. [['foo'], [['bar']], [[[['baz']]]]], into simply # ['foo','bar','baz']. def denester(l): if type(l) != list: return l if len(l) == 1: return denester(l[0]) return [denester(x) for x in l] struct = denester(struct) # Now check for internal structure if not any([type(x) == list for x in struct]): # Struct is just a list of language names, with no internal structure return False return True
def pred_seq_max_conf(detector_output_images_entries): """ Surface the max_detection_conf field, include detections of all classes. """ return max([entry['max_detection_conf'] for entry in detector_output_images_entries])
def pos_to_linecol(text, pos): """Return a tuple of line and column for offset pos in text. Lines are one-based, columns zero-based. This is how Jedi wants it. Don't ask me why. """ line_start = text.rfind("\n", 0, pos) + 1 line = text.count("\n", 0, line_start) + 1 col = pos - line_start return line, col
def assign_flag(pred: float, t_rouge: float, t_orange: float) -> str: """Turns a prediction score pred into an alert level. Args: pred: A predicted risk score between 0 and 1 t_rouge: A threshold, between 0 and 1, used for selecting "high risk" records. t_orange: A threshold, between 0 and t_rouge, used for selecting "moderate risk" records. `t_orange` should not be greater than `t_rouge`. If `t_orange == t_rouge`, there will indeed be a single risk level (high risk). """ assert 0 <= t_rouge <= 1, "t_rouge must be a number between 0 and 1" assert 0 <= t_orange <= 1, "t_orange must be a number between 0 and 1" assert t_orange <= t_rouge, "t_rouge should be greater than t_orange" if pred > t_rouge: return "Alerte seuil F1" if pred > t_orange: return "Alerte seuil F2" return "Pas d'alerte"
def solve_me_first(a: int, b: int) -> int: """ >>> solve_me_first(2, 3) 5 """ ret = a + b return ret
def intersection(list1, list2): """ Returns the intersection and then the items in list2 that are not in list 1. """ int_dict = {} not_int_dict = {} list1_dict = {} for e in list1: list1_dict[e] = 1 for e in list2: if e in list1_dict: int_dict[e] = 1 else: not_int_dict[e] = 1 return [list(int_dict.keys()), list(not_int_dict.keys())]
def dblp_doi_page_filter(url): #http://dx.doi.org/10.1109/SP.2015.9 """ This function is used to filter doi_page links Input is: value (url) Output is: True (match result), False(not match) """ if 'http://dx.doi.org' in url: return True return False
def guess_format(text): """Guess YANG/YIN format If the first non-whitespace character is '<' then it is XML. Return 'yang' or 'yin'""" format = 'yang' i = 0 while i < len(text) and text[i].isspace(): i += 1 if i < len(text): if text[i] == '<': format = 'yin' return format
def climb_stairs_optimized(steps): """ :type steps: int :rtype: int """ a_steps = b_steps = 1 for _ in range(steps): a_steps, b_steps = b_steps, a_steps + b_steps return a_steps
def max_subarray1(sequence): """ Find sub-sequence in sequence having maximum sum """ # this is the version before the final version for testing purposes max_sum, max_sub = 0, [] for i in range(len(sequence)): for j in range(i+1, len(sequence)): sub_seq = sequence[i:j+1] sum_s = sum(sub_seq) if sum_s > max_sum: max_sum, max_sub = sum_s, sub_seq return max_sum, max_sub
def sort(_list): """ quick_sort algorithm :param _list: list of integers to sort :return: sorted list """ if len(_list) <= 1: return list(_list) pivot = _list[len(_list) // 2] left = [x for x in _list if x < pivot] middle = [x for x in _list if x == pivot] right = [x for x in _list if x > pivot] return sort(left) + middle + sort(right)
def bits_to_dec(arr): """ [False, True, True] --> 3 [1, 0, 1, 0] --> 6 "0111" --> 7 [1, '0', 0, False, '1', True] --> 35 """ return int("".join([str(int(x)) for x in arr]), 2)
def BasinOrderToBasinRenameList(basin_order_list): """When we take data from the basins they will be numbered accoring to their junction rank, which is controlled by flow routing. The result is often numbered basins that have something that appears random to human eyes. We have developed a routine to renumber these basins. However, the way this works is to find a basin number and rename in the profile plots, such that when it finds a basin number it will rename that. So if you want to rename the seventh basin 0, you need to give a list where the seventh element is 0. This is a pain because how one would normally order basins would be to look at the image of the basin numbers, and then write the order in which you want those basins to appear. This function converts between these two lists. You give the function the order you want the basins to appear, and it gives a renaming list. Args: basin_order_list (int): the list of basins in which you want them to appear in the numbering scheme Return: The index into the returned basins Author: SMM """ #basin_dict = {} max_basin = max(basin_order_list) basin_rename_list = [0] * max_basin basin_rename_list.append(0) print(("length is: "+str(len(basin_rename_list)))) # Swap the keys for idx,basin in enumerate(basin_order_list): print(("Index: "+str(idx)+", basin: "+str(basin))) basin_rename_list[basin] = idx #print basin_rename_list return basin_rename_list
def wind_format(speed, direction): """Converts a wind speed and direction into a string formatted for user display. Args: speed: wind speed direction: window direction (in degrees: 0 is north, 90 is east, etc.) Returns: A string containing the speed and direction, such as "25 NW". """ wind = str(int(speed)) + " " if 22.5 < direction <= 67.5: wind += "NE" if 67.5 < direction <= 112.5: wind += "E" if 112.5 < direction <= 157.5: wind += "SE" if 157.5 < direction <= 202.5: wind += "S" if 202.5 < direction <= 247.5: wind += "SW" if 247.5 < direction <= 292.5: wind += "W" if 292.5 < direction <= 337.5: wind += "NW" else: wind += "N" return wind
def __filter_vertices(k, coreness, *args, **kwargs): """ .. function filter_vertices(k, coreness) Filters coreness mapping for vertex ids in k-core >= k. :param k: minimum k-core :param list coreness: vertex -> k-core mapping :return: vertices in k-core """ return list(filter(lambda i: coreness[i] >= k, range(len(coreness))))
def parse_other_violated_policy(raw_other_violated_policy_list: list) -> list: """ Parses a list of policies to context paths :param raw_other_violated_policy_list: the raw policies list :return: the parsed policies list """ other_violated_policy_list: list = [] for raw_other_violated_policy in raw_other_violated_policy_list: other_violated_policy: dict = { 'Name': raw_other_violated_policy.get('name'), 'Version': raw_other_violated_policy.get('version'), 'Label': raw_other_violated_policy.get('label'), 'ID': raw_other_violated_policy.get('policyId') } other_violated_policy_list.append({key: val for key, val in other_violated_policy.items() if val}) return other_violated_policy_list
def fullname(_o): """return fqn of this module""" # _o.__module__ + "." + _o.__class__.__qualname__ is an example in # this context of H.L. Mencken's "neat, plausible, and wrong." # Python makes no guarantees as to whether the __module__ special # attribute is defined, so we take a more circumspect approach. # Alas, the module name is explicitly excluded from __qualname__ # in Python 3. module = _o.__class__.__module__ if module is None or module == str.__class__.__module__: return _o.__class__.__name__ # Avoid reporting __builtin__ return module + '.' + _o.__class__.__name__
def _board_to_cartesian(x, y, z): """Translate from logical board coordinates (x, y, z) into cartesian coordinates for printing hexagons. Example coordinates:: ___ ___ /-15\___/1 5\___ \___/0 4\___/3 4\ /-13\___/1 3\___/ \___/0 2\___/2 2\___ \___/1 1\___/3 1\ /0 0\___/2 0\___/ \___/ \___/ Parameters ---------- x, y, z : int The logical board coordinates. Returns ------- x, y : int Equivalent Cartesian coordinates. """ cx = (2*x) - y + (1 if z == 1 else 0) cy = (3*y) + z return (cx, cy)
def interpolate_tuple( startcolor, goalcolor, percentage ): """ Take two RGB color sets and mix them at a specific percentage """ # white R = startcolor[0] G = startcolor[1] B = startcolor[2] targetR = goalcolor[0] targetG = goalcolor[1] targetB = goalcolor[2] DiffR = targetR - R DiffG = targetG - G DiffB = targetB - B buffer = [] steps = 100 iR = R + (DiffR * percentage / steps) iG = G + (DiffG * percentage / steps) iB = B + (DiffB * percentage / steps) print(iR) hR = ("%s"%hex(int(iR))).replace("0x", "") hG = ("%s"%hex(int(iG))).replace("0x", "") hB = ("%s"%hex(int(iB))).replace("0x", "") if len(hR) == 1: hR = "0" + hR if len(hB) == 1: hB = "0" + hB if len(hG) == 1: hG = "0" + hG color = "#"+hR+hG+hB return color
def tokenize(string): """ Split the input into the constituent elements that comprise it for example convert the string '2 3 +' into a list [2, 3, '+'] """ tokens = string.split(' ') # Create a list to hold the results to return # A list is a bit like a growable array of things results = [] # Loop through each of the elements in the tokens. If the 'token' # is actually an integer convert it to an int and add it to the results # otherwise just add it for token in tokens: if token.isdigit(): results.append(int(token)) else: results.append(token) return results
def add_spaces_to_lines(count, string): """Adds a number of spaces to the start of each line""" all_lines = string.splitlines(True) new_string = all_lines[0] for i in range(1, len(all_lines)): new_string += ' ' * count + all_lines[i] return new_string
def warmup_lr(init_lr, step, iter_num): """ Warm up learning rate """ return step/iter_num*init_lr
def octagonalNum(n): """Returns the nth octagonal number.""" return int(n * (3*n - 2))
def isglobalelement(domains): """ Check whether all domains are negations.""" for domain in domains.split(","): if domain and not domain.startswith("~"): return False return True
def ipv4(address): """ Check if valid IPv4 address `Required` :param str address: string to check Returns True if input is valid IPv4 address, otherwise False """ import socket try: if socket.inet_aton(str(address)): return True except: return False
def miller_rabin_base_2(n): """Perform the Miller Rabin primality test base 2""" d, s = n - 1, 0 while not d & 1: d, s = d >> 1, s + 1 x = pow(2, d, n) if (x == 1) or (x == n - 1): return True for i in range(s - 1): x = pow(x, 2, n) if x == 1: return False elif x == n - 1: return True return False
def get_file_id(fp): """ Split string to get wave id in DNS challenge dataset.""" return fp.split("_")[-1].split(".")[0]
def Legendre( x, n ): """ Function used to compute the Legendre polynomials. Args: x (any): variable. n (int): polynomials order Returns: any: returns the value of the polynomials at a given order for a given variable value. Testing: Already tested in some functions of the "functions.py" library. """ if n == 0: return 1 elif n == 1: return x else: return ( ( ( 2 * n ) - 1 ) * x * Legendre( n - 1, x ) - ( n - 1 ) * Legendre( n-2, x ) ) / float( n )
def get_name_for_predict_column(columns): """ Get a unique name for predicted column. """ # As of now, the predicted column will take the form # constant string + number # The constant string is fixed as '_predicted' k = '_predicted' i = 0 # Try attribute name of the form "_id", "_id0", "_id1", ... and # return the first available name while True: if k not in columns: break else: k = '_predicted' + str(i) i += 1 # Finally, return the column name return k
def confopt_list(confstr, list=[], default=None): """Return an element from list or default.""" ret = default for elem in list: if confstr.lower() == elem.lower(): ret = elem break return ret
def check_name(name, name_list): """ Check the validity of name. :param name: test name :type name: str :param name_list: players names :type name_list: list :return: validity as bool """ if len(name) != 0 and name not in name_list: return True return False
def convolution_math(in_channels, filter_size, out_channels): """ Convolution math: Implement how parameters scale as a function of feature maps and filter size in convolution vs depthwise separable convolution. Args: in_channels : number of input channels filter_size : size of the filter out_channels : number of output channels """ # calculate the number of parameters for regular convolution conv_parameters = in_channels * filter_size * filter_size * out_channels # calculate the number of parameters for depthwise separable convolution depthwise_conv_parameters = in_channels * filter_size * filter_size + in_channels * out_channels print(f"Depthwise separable: {depthwise_conv_parameters} parameters") print(f"Regular convolution: {conv_parameters} parameters") return None
def normalizeGlyphTopMargin(value): """ Normalizes glyph top margin. * **value** must be a :ref:`type-int-float` or `None`. * Returned value is the same type as the input value. """ if not isinstance(value, (int, float)) and value is not None: raise TypeError("Glyph top margin must be an :ref:`type-int-float`, " "not %s." % type(value).__name__) return value
def verify_error(error: Exception, v_error: Exception): """error verifier""" return isinstance(error, v_error.__class__)\ and error.__dict__ == v_error.__dict__
def xgcd(a, b): """ Extended Euclidean Distance return (g, x, y) such that a*x + b*y = g = gcd(x, y) """ x0, x1, y0, y1 = 0, 1, 1, 0 while a != 0: q, b, a = b // a, a, b % a y0, y1 = y1, y0 - q * y1 x0, x1 = x1, x0 - q * x1 return b, x0, y0
def calculate_same_padding(kernel_size, dilation, stride): """Calculates the amount of padding to use to get the "SAME" functionality in Tensorflow.""" return ((stride - 1) + dilation * (kernel_size - 1)) // 2
def is_branch(v): """ Check wether a variable is branch length or weight parameter :param v: variable :return: True/False """ return str(v)[0] == 't'
def user_display_name(user): """ Returns the preferred display name for the given user object: the result of user.get_full_name() if implemented and non-empty, or user.get_username() otherwise. """ try: full_name = user.get_full_name().strip() if full_name: return full_name except AttributeError: pass try: return user.get_username() except AttributeError: # we were passed None or something else that isn't a valid user object; return # empty string to replicate the behaviour of {{ user.get_full_name|default:user.get_username }} return ''
def _get_dict_elements(npk, hu, ele_a, ele_b): """Return the appropriate hookup elements for node_info.""" e_ret = {ele_a.lower(): '', ele_b.lower(): ''} try: e_hookup = hu[npk].hookup['@<middle'] except KeyError: return e_ret for element in e_hookup: if element.upstream_part.startswith(ele_a.upper()): e_ret[ele_a.lower()] = element.upstream_part e_ret[ele_b.lower()] = element.downstream_part break elif element.upstream_part.startswith(ele_b.upper()): e_ret[ele_b.lower()] = element.upstream_part return e_ret
def hamming(first, second): """ hamming distance between two strings """ return len(list(filter(lambda x : ord(x[0])^ord(x[1]), zip(first, second))))
def num_to_chrom(chrom): """Return a chromsome in the format chr# even if is number.""" chrom = str(chrom) return chrom if chrom.startswith('chr') else 'chr' + chrom
def filter_function(file_name): """ Internal function to check if the file_name contains 'scisweeper.h5' Args: file_name (str): name of the current file Returns: bool: [True/ False] """ return "scisweeper.h5" in file_name
def diff(df): """ Assuming col1 and col2 are lists, return set difference between list1 & list2 """ return list(set(df[0]) - set(df[1]))
def remove_duplicados(lista_a, lista_b): """Remove itens duplicados""" primeira_lista = set(lista_a) segunda_lista = set(lista_b) return primeira_lista | segunda_lista
def set_pos(x,y, printing=True): """x,y: int, <printng>: Boolean (True)""" if printing: print(f"\033[{x};{y}H", end="") else: return f"\033[{x};{y}H"
def quote_string(arg: str) -> str: """Quote a string""" if '"' in arg: quote = "'" else: quote = '"' return quote + arg + quote
def calc_mean_score(movies): """Helper method to calculate mean of list of Movie namedtuples, round the mean to 1 decimal place""" ratings = [m.score for m in movies] mean = sum(ratings) / max(1, len(ratings)) return round(mean, 1)
def permutation_rank(p): """Given a permutation of {0,..,n-1} find its rank according to lexicographical order :param p: list of length n containing all integers from 0 to n-1 :returns: rank between 0 and n! -1 :beware: computation with big numbers :complexity: `O(n^2)` """ n = len(p) fact = 1 # compute (n-1) factorial for i in range(2, n): fact *= i r = 0 # compute rank of p digits = list(range(n)) # all yet unused digits for i in range(n-1): # for all digits except last one q = digits.index(p[i]) r += fact * q del digits[q] # remove this digit p[i] fact //= (n - 1 - i) # weight of next digit return r
def range_truncate(s, max_len=8) : """Truncate a string to assist debug traces.""" if len(s) > max_len : return s[0:2] + "..." + s[-2:] return s
def errno_from_exception(e): """Provides the errno from an Exception object. There are cases that the errno attribute was not set so we pull the errno out of the args but if someone instatiates an Exception without any args you will get a tuple error. So this function abstracts all that behavior to give you a safe way to get the errno. """ if hasattr(e, 'errno'): return e.errno elif e.args: return e.args[0] else: return None
def getLineNumber(lines, phrases, debug=False): """Returns the line numbers containing the provided phrases after searching for the previous phrases sequentially. Search starts with the first phrase, once it is found, search starts with the 2nd phrase from that line, until the last phrase is found. Ignores early matches of the final phrase.""" nums = [] for i, line in enumerate(lines): if phrases[len(nums)] in line: if debug: print("found '{}' on line {}.".format(phrases[len(nums)], i)) nums.append(i) if len(phrases) == len(nums): return nums return nums
def prime_factors(no)->list: """ Return the list of prime factors of the number. """ prime=[i for i in range(no+1)] factors=[] for i in range(2,no+1): if prime[i]==i: for j in range(i*i,no+1,i): prime[j]=i while(no>=2): factors.append(prime[no]) no=no//prime[no] return factors
def get_multiplexer(num): """ Get max decimal multiplexer. """ m = 1 while num % 10 == 0: num = num / 10 m *= 10 return m
def is_exist_protected_branch_exclude_master(repo_name, repos): """ check there exist other protected branches exclude master """ for repo in repos: if repo_name == repo['name']: if len(repo['branches']) == 1: return False return True return False
def _func_annotation_for(func): """Retrieve the function annotation for a given function or create it""" current = getattr(func,'__annotations__',None) if current is None: current = func.__annotations__ = {} return current
def calc_conformance(results): """Returns a tuple with the number of total and failed testcase variations and the conformance as percentage.""" total = len(results) failed = sum(1 for status, _ in results.values() if status != 'PASS') conformance = (total - failed) * 100 / total return total, failed, conformance
def download_sequences(): """Downloads the requested sequences from the VOT dataset. :param list subsets: An optional list of subsets of VOT to download. If this is ``None``, all subsets will be downloaded. :param str root_directory: The root directory into which to download the sequences. *vot* is appended to this; so sequences are ultimately downloaded to *root_directory/vot*. :param bool force: If ``True``, sequences will be downloaded even if they already exists in ``root_directory``. If ``False``, existing sequences will not be downloaded again. :param list sequences: Specific sequences to download. The sequence names must match exactly. If this is ``None``, all sequences are downloaded. :return: Nothing """ print("Downloading vot") # os.makedirs(os.path.join(root_directory, "vot"), exist_ok=True) return 0
def encode_chrom(chrom): """Encodes the chromosome.""" if str(chrom) == "23": return "X" if str(chrom) == "24": return "Y" if str(chrom) == "26": return "M" return str(chrom)
def time_duration_formatter(x): """Format time duration in seconds """ mm, ss = divmod(x, 60) hh, mm = divmod(mm, 60) dd, hh = divmod(hh, 24) res = '' if dd: res += '%dd ' % dd if dd or hh: res += '%dh ' % hh if dd or hh or mm: res += '%dm ' % mm res += '%ds' % ss return res
def check_saturation(vol1: int, vol2: int) -> bool: """Check if percentage of orders received is acceptable""" acceptance = 0.95 try: if vol2/vol1 >= acceptance: return True else: return False except ZeroDivisionError: return False
def _hex64(n: int) -> str: """Formats a 64-bit unsigned integer.""" return f'0x{n:016x}'
def choose(n, r): """The number of ways of choosing r items from n All calculations done as integer. Parameters ---------- n number of items to choose from r number of items to choose Returns ------- combin The number if ways of making the choice """ if n < 0 or r < 0: print('Negative values not allowed') return 0 if r > n: print('r must not be greater than n') return 0 combin = 1 r1 = min(r, n-r) for k in range(r1): combin = combin * (n - k) // (k + 1) return combin
def reverse_one_hot(y_): """ Function to reverse one-hot coding E.g.: [[0, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0]] --> [[5], [0], [3]] """ flat_y = [] for index, entry in enumerate(y_, start=0): # print("--- y_ [", index, "]:", entry) for bit, code in enumerate(entry): if(code > 0): flat_y.append(bit) return flat_y
def format_macrofunction(function): """Format the fully qualified name of a macro function, for error messages.""" # Catch broken bindings due to erroneous imports in user code # (e.g. accidentally to a module object instead of to a function object) if not (hasattr(function, "__module__") and hasattr(function, "__qualname__")): return repr(function) if not function.__module__: # Macros defined in the REPL have `__module__=None`. return function.__qualname__ return f"{function.__module__}.{function.__qualname__}"
def solution(xs): """ Boring case analysis. In this problem the pain is just to not miss any case. """ if len(xs)==1: return str(xs[0]) count_neg = 0 count_pos = 0 count_zero = 0 prod_pos = 1 prod_neg = 1 max_neg = -float("inf") for x in xs: if x ==0: count_zero+=1 elif x < 0: pos_or_neg = True count_neg+=1 prod_neg *= x max_neg = max(max_neg,x) elif x > 0: count_pos+=1 pos_or_neg = True prod_pos *= x if (count_pos == 0 and count_neg == 0) or (count_zero > 0 and count_neg == 1 and count_pos == 0): return str(0) if count_neg%2!=0: count_neg-=1 prod_neg //=max_neg if not (count_pos == 0 and count_neg == 0): return str(prod_neg*prod_pos) return str(0)
def add_to_inventory(inventory, items): """sorts items argument so that they become a dictionary with values depending on the number of repetitions of a given item in the items argument. Then the newly created dictionary is merged to the inventory argument.""" new_items = (dict((item, items.count(item)) for item in set(items))) for key, value in new_items.items(): if key in inventory: inventory[key] += value elif key not in inventory: inventory.setdefault(key, value) else: print("woot woot send help") print("Loot was added :3") return inventory
def ranks(x, reverse=False): """ Returns a tuple containing the rank of each element of the iterable `x`. The ranks start at `0`. If `reverse` is `False`, the elements of `x` are ranked in ascending order, and in descending order otherwise. Equal elements will all be assigned the same (lowest-possible) rank. >>> ranks(["d", "a", "c", "b"]) (3, 0, 2, 1) >>> ranks(["d", "a", "c", "b"], reverse=True) (0, 3, 1, 2) >>> ranks(["d", "a", "c", "b", "c"]) (4, 0, 2, 1, 2) """ s = sorted(x, reverse=reverse) return tuple(s.index(item) for item in x)
def pretty_stacktrace(stacktrace): """Prettifies stacktrace""" if not stacktrace: return "<No stacktrace>" return stacktrace
def get_histogram_units(histogram_data): """ Function takes dictionary of histogram data. Checks for units key which indicates it is newer format or older and return unit. """ units = None units_present = False units_absent = False for k1, v1 in histogram_data.items(): if not v1 or isinstance(v1, Exception): continue for k2, v2 in v1.items(): if not v2 or isinstance(v2, Exception): continue if "units" in v2: units_present = True units = v2["units"] else: units_absent = True if units_absent and units_present: raise Exception("Different histogram formats on different nodes") return units
def _unpad(padded): """ Remove the padding applied by _pad() """ return padded[:-ord(padded[len(padded) - 1:])]
def _format_dataset_name(name, term): """Returns name with colour codes and length w/o them for datasets.""" return (name, len(name))
def pysolr_formatter(credentials): """ Returns formatted Solr credentials for a pysolr-Solr connection. Args: credentials (dict): The credentials dictionary from the relationships. Returns: (string) A formatted pysolr credential. """ return "http://{0}:{1}/{2}".format(credentials['ip'], credentials['port'], credentials['path'])
def _collect_lines(data): """ Split lines from data into an array, trimming them """ matches = [] for line in data.splitlines(): match = line.strip() matches.append(match) return matches
def _get_range_squared(range_instru): """Returns range (m), squared and converted to km.""" m2km = 0.001 return (range_instru*m2km)**2
def adjust_probabilities(p_list): """ Adjust a list of probabilties to ensure that they sum to 1 """ if p_list is None or len(p_list) == 0: out = None else: total = sum(p_list) if total == 1: out = p_list elif total == 0: raise ValueError('Probabilities may not sum to zero') else: out = [x / total for x in p_list] return out
def max_and_min_product_subarray(arr): """ Assumption: Output is always greater than or equal to 1. :param arr: :return: """ curr_max = curr_min = global_max = global_min = 1 for elt in arr: # If this element is positive, update curr_max. # Update curr_min only if curr_min is negative if elt > 0: curr_max = curr_max * elt curr_min = min(curr_min * elt, 1) elif elt < 0: prev_max = curr_max curr_max = max(curr_min * elt, 1) curr_min = prev_max * elt # If this element is 0, then the maximum product can't end here, make both curr_max and curr_min 0 # Assumption: Output is always greater than or equal to 1. else: curr_max, curr_min = 1,1 if curr_max > global_max: global_max = curr_max if curr_min < global_min: global_min = curr_min return global_max, global_min
def get_file_name(path): """Get the file name without .csv postfix. Args: path: A string for the absolute path to the file. Returns: A string for the path without .csv postfix """ filename = path.strip('\n').strip('.csv') return filename
def is_image(filename): """ Check if filename has valid extension :param filename: :return: boolean indicating whether filename is a valid image filename """ filename = filename.lower() return filename.endswith(".jpg") \ or filename.endswith(".png") \ or filename.endswith(".jpeg") \ or filename.endswith(".gif") \ or filename.endswith(".bmp")
def calc_c02_emission(n_persons=0, emission_rate=0, internal_source=0, time=0): """ :param n_persons: # number of persons in the zone :param emission_rate: # CO2 emission rate per person [mg/h] :param internal_source: # emission rate of interal sources [mg/h] :param time: # simulation time :return: """ e = n_persons * emission_rate + internal_source return e
def determine_atts(desc, targ, miss): """ Determine the entire list of attributes. """ atts = list(set(desc).union(targ).union(miss)) atts.sort() return atts
def best_model_compare_fn(best_eval_result, current_eval_result, key): """Compares two evaluation results and returns true if the second one is greater. Both evaluation results should have the value for key, used for comparison. Args: best_eval_result: best eval metrics. current_eval_result: current eval metrics. key: key to value used for comparison. Returns: True if the loss of current_eval_result is smaller; otherwise, False. Raises: ValueError: If input eval result is None or no loss is available. """ file = 'best_f1_two_conv_no_antacent_bert_debug' if not best_eval_result or key not in best_eval_result: raise ValueError('best_eval_result cannot be empty or key "%s" is not found.' % key) if not current_eval_result or key not in current_eval_result: raise ValueError('best_eval_result cannot be empty or key "%s" is not found.' % key) if best_eval_result[key] < current_eval_result[key]: with open(file+'.txt', 'w') as wf: print(str(best_eval_result[key]) + '->'+ str(current_eval_result[key])+"\n") wf.write(str(best_eval_result[key]) + '->'+ str(current_eval_result[key])+"\n") return best_eval_result[key] < current_eval_result[key]
def match(text, pattern, limit = -1): """ Matches all or first "limit" number of occurrences of the specified pattern in the provided text :param text: A String of characters. This is the text in which we want to find the pattern. :param pattern: The pattern to look for. Expected to be a regular expression. :param limit: The number of occurrences of the pattern to be returned. If specified, the method returns the first "limit" number of occurrences of the pattern in the text(or all occurrences, whichever is lesser) :return: A list of matching strings and their starting and ending index values in the format (matching_text, start_index, end_index) """ import re matcher = re.compile(pattern) matches = [] iter = 0 for m in matcher.finditer(text): entry = (m.group(), m.start(), m.end()) matches.append(entry) iter += 1 if limit != -1 and iter == limit: break return matches
def null_group_membership(username, group): """Default group membership test. Gives HOST permission to all users and MOD permission to those with dpauth.moderator Django permission. Custom implementations can delegate to this one if group is blank. Parameters: username -- the Username instance or None if this is a guest user group -- group name or None if no group was specified """ if group: return None flags = ['HOST'] if username and username.is_mod and username.user.has_perm('dpauth.moderator'): flags.append('MOD') return { 'member': False, 'flags': flags, }
def html_escape(s, quote=False, crlf=False): """html.escape but also newlines""" s = s.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;") if quote: s = s.replace('"', "&quot;").replace("'", "&#x27;") if crlf: s = s.replace("\r", "&#13;").replace("\n", "&#10;") return s
def sls(container) -> list: """ sorted list set """ return sorted(list(set(container)))
def search_clip_threshold(qs, la, lb, rc, rd): """ assume qs is sorted, rc,la>=0 return inf{M: Pr(q(X)<= la/M+lb) <= M*rc+rd } """ n = len(qs) lo, hi = 0, n while lo<hi: mid = (lo+hi)//2 cur_M = la/(qs[mid]-lb) if mid/n < cur_M*rc+rd: lo = mid+1 else: hi = mid q = 1 if lo==n else qs[lo] #print("search clip: prop=%.2f q=%.5f th=%.2f bound=%.2f"%(lo/n, q, la/(q-lb), la/(q-lb)*rc+rd)) return la/(q-lb)
def qualitative_pcs_value(pcs_value): """Convert PCS value into qualitative description""" if pcs_value < 369: output = "Very good" elif pcs_value < 1088: output = "Good" elif pcs_value < 1700: output = "Standard" elif pcs_value < 4622: output = "Bad" elif pcs_value < 7696: output = "Very Bad" else: output = "Hazardous" return output
def find_smallest_angle(angle1, angle2, absolute_value=False): """Find the smallest angle between two provided azimuth angles. @param: - angle1 - first angle in degrees between 0 and 360 degrees @param: - angle2 - first angle in degrees between 0 and 360 degrees @param: - absolute_value - if true, return absolute value of result """ diff = angle1 - angle2 diff = (diff + 180) % 360 - 180 if absolute_value: diff = abs(diff) return diff
def reportMissingGenes(geneSet, gafDict, indicator): """ Finds and reports Uniprot AC's in the provided background/interest gene sets which are not present in the gene association file (most likely obsolete entries). Also returns a new set where these missing genes are removed. Parameters ---------- geneSet : set of str A set of Uniprot ACs. Generated by importSubset() or importBackground(). gafDict : dict of str mapping to set A dictionary mapping gene Uniprot AC's (str) to a set GO IDs. Generated by importGAF(). indicator : str A string signifying whether the set is the background or interest set of genes. Returns ------- geneSet : set of str The set after removal of Uniprot AC's not present in provided gene lists. """ if len(geneSet) != len(gafDict): obsoleteGenes = [AC for AC in geneSet if AC not in gafDict] print('WARNING! The', indicator, 'gene set contained genes not present in the gene association file:') print(obsoleteGenes) print('Removing these genes from the', indicator, 'set...\n') return geneSet.difference(obsoleteGenes) else: return geneSet
def last_8chars(x): """Function that aids at list sorting. Args: x: String name of files. Returns: A string of the last 8 characters of x. """ return (x[-8:])
def dict_to_nice_str(d, max_line_length=80): """Returns dictionary [d] as as nicely formatted string.""" s, last_line_length = "", 0 for k in sorted(d.keys()): item_len = len(f"{k}: {d[k]}, ") if last_line_length + item_len > max_line_length: s += f"\n{k}: {d[k]}, " last_line_length = item_len else: s += f"{k}: {d[k]}, " last_line_length += item_len return s
def getNumPlaces(x): """ getNumPlaces() | gets the number of decimal places in a float/integer x | (float) (int) returns (int) """ if int(x) == x: return 0 return len(str(x)) - len(str(int(x))) - 1