content
stringlengths
42
6.51k
def substring_edit_distance(s: str, t: str) -> int: """The minimum number of edits required to make t a substring of s. An edit is the addition, deletion, or replacement of a character. """ if not s: return len(t) if not t: return 0 M = [[0 for _ in range(len(t) + 1)] for _ in range(len(s) + 1)] # M[i][j] is the minimum number of t-edits required to make t[:j] a suffix of s[:i]. for i in range(len(s) + 1): M[i][0] = 0 for j in range(len(t) + 1): M[0][j] = j for i in range(1, len(s) + 1): for j in range(1, len(t) + 1): cost = 0 if s[i - 1] == t[j - 1] else 1 M[i][j] = min( [ 1 + M[i - 1][j], 1 + M[i][j - 1], cost + M[i - 1][j - 1], ]) return min(M[i][len(t)] for i in range(len(s) + 1))
def strict_map(func, iterable): """ Python 2/3-agnostic strict map. """ return [func(i) for i in iterable]
def print_perf(start, end): """Print diff as ms between start and end times (floats in secs).""" diff = (end - start) * 1000 print('{:.2f} milliseconds elapsed'.format(diff)) return diff
def remove_ribozyme_if_possible(rna_type, _): """ This will remove the ribozyme rna_type from the set of rna_types if there is a more specific ribozyme annotation avaiable. """ ribozymes = set( ["hammerhead", "hammerhead_ribozyme", "autocatalytically_spliced_intron"] ) if "ribozyme" in rna_type and rna_type.intersection(ribozymes): rna_type.discard("ribozyme") return rna_type return rna_type
def create_exceptions_mapping(*sources): """Create a single mapping of exception names to their classes given any number of dictionaries mapping variable names to variables e.g. `locals()`, `globals()` or a module. Non-exception variables are filtered out. This function can be used to combine several modules of exceptions into one mapping. :param sources: any number of `dict`s of global or local variables mapping object names to objects :return dict: """ candidates = {key: value for source in sources for key, value in source.items()} exceptions_mapping = {} for name, object in candidates.items(): try: if issubclass(object, BaseException): exceptions_mapping[name] = object except TypeError: continue return exceptions_mapping
def get_not_gaps(start, end, gaplist): """Get inverse coords of gaps Parameters ---------- start : int end : int Coords for original sequence, 0-based pythonic gaplist : list list of (int, int) tuples specifying gaps. Must not be overlapping otherwise GIGO Returns ------- list list of (int, int) tuples specifying not-gaps """ coords = [start] sortedgaps = sorted(gaplist, key=lambda x: int(x[0])) for tup in sortedgaps: coords.extend([tup[0], tup[1]]) coords.append(end) # Reslice out = [] for i in range(int(len(coords)/2)): out.append((coords[2*i], coords[2*i+1])) return(out)
def toList(given): """ This will take what is given and wrap it in a list if it is not already a list, otherwise it will simply return what it has been given. :return: list() """ if not isinstance(given, (tuple, list)): given = [given] return given
def flatten(l): """ Flattens a nested list into a single list Arguments: l: list to flatten Returns: Flattened list """ out = [] for item in l: if type(item) == list: out = out + flatten(item) else: out.append(item) return out
def mk_const_expr(val): """ returns a constant expression of value VAL VAL should be of type boolean """ return {"type" : "const", "value": val }
def to_pascal_case(snake_case_word): """Convert the given snake case word into a PascalCase one.""" parts = iter(snake_case_word.split("_")) return "".join(word.title() for word in parts)
def Frr_unit_sphere(r): """Antiderivative of RR_sphere. The RR from r1 to r2 for a unit spherical area is rr_unit_sphere(r2) - rr_unit_sphere(r1) """ return 3 * r**3/3 - 9 / 4 * r**4/4 + 3 / 16 * r**6/6
def hex2rgb(hexcolor): """Convert a hex color to a (r, g, b) tuple equivilent.""" hexcolor = hexcolor.strip('\n\r #') if len(hexcolor) != 6: raise ValueError('Input #%s not in #rrggbb format' % hexcolor) r, g, b = hexcolor[:2], hexcolor[2:4], hexcolor[4:] return [int(n, 16) for n in (r, g, b)]
def is_prime(n): """Return True if n is prime. Copied from https://stackoverflow.com/questions/1801391/what-is-the-best-algorithm-for-checking- if-a-number-is-prime """ if n == 1: return False if n == 2: return True if n == 3: return True if n % 2 == 0: return False if n % 3 == 0: return False test_int = 5 increment = 2 # test_int iterates through odd numbers, also skipping multiples of 3 # () means number is skipped # test_int = 5, 7, (9), 11, 13, (15), 17, 19, (21), 23 while test_int * test_int <= n: if n % test_int == 0: return False test_int += increment increment = 6 - increment return True
def wordpiece(token, vocab, unk_token, sentencepiece_style_vocab=False, max_input_chars_per_word=100): """call with single word""" chars = list(token) if len(chars) > max_input_chars_per_word: return [unk_token], [(0, len(chars))] is_bad = False start = 0 sub_tokens = [] sub_pos = [] while start < len(chars): end = len(chars) cur_substr = None while start < end: substr = "".join(chars[start:end]) if start == 0 and sentencepiece_style_vocab: substr = u'\u2581' + substr if start > 0 and not sentencepiece_style_vocab: substr = "##" + substr if substr in vocab: cur_substr = substr break end -= 1 if cur_substr is None: is_bad = True break sub_tokens.append(cur_substr) sub_pos.append((start, end)) start = end if is_bad: return [unk_token], [(0, len(chars))] else: return sub_tokens, sub_pos
def int2bin(i,nbits=8,output=str): """ Convert integer to binary string or list Parameters ---------- **`i`**: Integer value to convert to binary representation. **`nbits`**: Number of bits to return. Valid values are 8 [DEFAULT], 16, 32, and 64. **`output`**: Return data as `str` [DEFAULT] or `list` (list of ints). Returns ------- `str` or `list` (list of ints) of binary representation of the integer value. """ i = int(i) if not isinstance(i,int) else i assert nbits in [8,16,32,64] bitstr = "{0:b}".format(i).zfill(nbits) if output is str: return bitstr elif output is list: return [int(b) for b in bitstr]
def _sorted(dictionary): """Returns a sorted list of the dict keys, with error if keys not sortable.""" try: return sorted(dictionary) except TypeError: raise TypeError("tree only supports dicts with sortable keys.")
def _preprocess_dims(dim): """Preprocesses dimensions to prep for stacking. Parameters ---------- dim : str, list The dimension(s) to apply the function along. """ if isinstance(dim, str): dim = [dim] axis = tuple(range(-1, -len(dim) - 1, -1)) return dim, axis
def true_param(p): """Check if ``p`` is a parameter name, not a limit/error/fix attributes.""" return ( not p.startswith("limit_") and not p.startswith("error_") and not p.startswith("fix_") )
def distance_2D(p1, p2): """ Get distance between two points Args: p1: first point index 0 and 1 should be x and y axis value p2: second point index 0 and 1 should be x and y axis value Returns: distance between two points """ return (p1[0] - p2[0]) * (p1[0] - p2[0]) + (p1[1] - p2[1]) * (p1[1] - p2[1])
def _str_between(text, start, stop): """Returns the string found between substrings `start` and `stop`.""" return text[text.find(start) + 1 : text.rfind(stop)]
def make_dict(duration, voltages, beats, mean_hr, beat_times): """Makes a dictionary following the format described on github :param duration: Time length of data sequence :param voltages: Voltage extremes in tuple form :param beats: Number of beats :param mean_hr: Calculated heart rate in BPM :param beat_times: List of times where heart beat events occured :return: Dictionary of data """ metrics = {"Duration": duration, "Voltage Extremes": voltages, "Number of Beats": beats, "Mean Heart Rate": mean_hr, "Beat Times": beat_times} return metrics
def remove_old_resources(resource_list): """ Remove resources in a list which have the same id as another resource but an older timestamp """ uniques = [] ids = set() for r in resource_list: if r["id"] not in ids: uniques.append(r) ids.add(r["id"]) return uniques
def _encode(data, name='data'): """Call data.encode("latin-1") but show a better error message.""" try: return data.encode("latin-1") except UnicodeEncodeError as err: raise UnicodeEncodeError( err.encoding, err.object, err.start, err.end, "%s (%.20r) is not valid Latin-1. Use %s.encode('utf-8') " "if you want to send it encoded in UTF-8." % (name.title(), data[err.start:err.end], name)) from None
def _Offsets(*args): """Valid indentation offsets for a continued line.""" return dict((a, None) for a in args)
def expand_span(span, expand_length=2): """ Args: span (list): [st, ed] expand_length (int): length to add on the two sides Returns: expanded_span (list): [max(0, st-expand_length), ed + expand_length] Only use the span for indexing, no need to worry the case where (ed + expand_length) >= max_length. """ return [max(0, span[0] - expand_length), span[1] + expand_length]
def de_dup_and_sort(input): """ Given an input list of strings, return a list in which the duplicates are removed and the items are sorted. """ input.sort() input=set(input) input = list(input) input.sort() ###################################### added line ###################### return input
def matches(rec, labels): """returns True if rec has these labels. rec: dictionary like: "2019-10-17_08-37-38-right_repeater.mp4": { "file": "2019-10-17_08-37-38-right_repeater.mp4", "car": { "label": "car", "count": 34, "frames": [ 0, 0] "person": {...} labels: list of strings """ # print(rec) for label in labels: if label in rec.keys(): return True return False
def avg_midrange(values): """Return the arithmetic mean of the highest and lowest value of values.""" vmin = min(values) vmax = max(values) return (vmin + vmax) / 2
def unindent(source): """ Removes the indentation of the source code that is common to all lines. Does not work for all cases. Use for testing only. """ def normalize(line): normalized = [] for i, c in enumerate(line): if c == " ": normalized.append(" ") elif c == '\t': normalized.append(8 * " ") else: normalized.append(line[i:]) break return "".join(normalized) def min_indent(lines): idendations = [] for line in lines: if not line.strip(): continue if line.strip().startswith("#"): continue idendations.append(count(line)) if not idendations: return 0 else: return min(idendations) def count(normalized): count = 0 for c in normalized: if c == ' ': count += 1 else: break return count def trim(normalized, indent): indent = min(count(normalized), indent) return normalized[indent:] lines = [normalize(line) for line in source.splitlines()] indent = min_indent(lines) return "\n".join(trim(line, indent) for line in lines)
def distance(x_1, x_2): """Calculate distance between sets. Args: x_1, x_2: sets. Returns: distance. """ return len(x_1) + len(x_2) - len(x_1.intersection(x_2)) * 2
def best_time(time1, time2): """Return the best of two given times.""" time = min(time1, time2) if time == 0: return max(time1, time2) # if no time yet --> set the highest return time
def is_prime(number): """ Finds the provided number Prime or Not Example No: 3.1 in Book Complexity: O(n) :param number: Number to be checked as Prime or Not :return: True / False """ if number <= 1: return False else: for i in range(2, number-1): if number % i == 0: return False return True
def isHole(ring): """# problem due to inverted Tkinker canvas, so i do opposite of below: Checks to see if points are in counterclockwise order which denotes a inner ring of a polygon that has a donut-like shape or a hole such as a lake etc. Argument: ring - a list of tuples denoting x,y coordinates [(x1,y1),...] Return: TRUE or FALSE Notes: http://www.cartotalk.com/index.php?showtopic=2467 Charlie Frye 9/26/07 says: "Ring order could mean one of two things. First, when a shape has more than one part, e.g., a donut hole or an island, it's shape will be comprised of multiple parts, or rings. Each ring defines the geometry (list of coordinates). The expected implementation is that the rings are listed in size order, with the largest ring (covering the most area) being first in the list. Another issue is whether the coordinates in each ring are listed in clockwise or counterclockwise order; clockwise means it is an exterior ring or an island, and counterclockwise is an interior ring or an island [ A HOLE ]." """ x = [p[0] for p in ring] y = [p[1] for p in ring] n = len(x) # Below checks if inner ring, counterclockwise a = sum([x[i] * y[i + 1] - x[i + 1] * y[i] for i in range(n - 1)]) if a > 0: counterClockWise = True hole = False # opposite of normal for Tkinter canvas coordinates else: counterClockWise = False # opposite of normal for Tkinter canvas coordinates hole = True return hole
def blend3(d = 0.0, u = 1.0, s = 0.05): """ blending function polynomial d = delta x = xabs - xdr u = uncertainty radius of xabs estimate error s = tuning scale factor returns blend """ d = float(d) u = float(u) s = min(1.0,float(abs(s))) # make sure positive <= 1.0 b = 1.0 - s ** ((d * d)/(u * u)) return b
def get_digit_b(number, digit): """ Given a number, returns the digit in the specified position, for an out of range digit returns 0 """ return number % 10**digit // 10**(digit-1)
def _str(int_inn): """Change the int to string but make sure it has two digits. The int represents a month og day.""" if len(str(int_inn)) < 2: int_as_string = '0' + str(int_inn) else: int_as_string = str(int_inn) return int_as_string
def header(text, color='black'): """Create an HTML header""" raw_html = f'<h1 style="margin-top:12px;color: {color};font-size:54px"><center>' + str( text) + '</center></h1>' return raw_html
def quantiles2percentiles(quantiles): """ converts quantiles into percentiles """ return [100*x for x in quantiles]
def post_match(view, name, style, first, second, center, bfr, threshold): """Ensure that backticks that do not contribute inside the inline or block regions are not highlighted.""" if first is not None and second is not None: diff = first.size() - second.size() if diff > 0: first = first.move(first.begin, first.end - diff) elif diff < 0: second = second.move(second.begin - diff, second.end) return first, second, style
def _convert_label(key): """Ctreate char label from key string.""" try: return ''.join(chr(int(_key, 16)) for _key in key.split(',')) except ValueError: return ''
def dop2str(dop: float) -> str: """ Convert Dilution of Precision float to descriptive string. :param float dop: dilution of precision as float :return: dilution of precision as string :rtype: str """ if dop == 1: dops = "Ideal" elif dop <= 2: dops = "Excellent" elif dop <= 5: dops = "Good" elif dop <= 10: dops = "Moderate" elif dop <= 20: dops = "Fair" else: dops = "Poor" return dops
def durationToText(seconds): """ Converts seconds to a short user friendly string Example: 143 -> 2m 23s """ days = int(seconds / 86400000) if days: return '{0} day{1}'.format(days, days > 1 and 's' or '') left = seconds % 86400000 hours = int(left / 3600000) if hours: hours = '{0} hr{1} '.format(hours, hours > 1 and 's' or '') else: hours = '' left = left % 3600000 mins = int(left / 60000) if mins: return hours + '{0} min{1}'.format(mins, mins > 1 and 's' or '') elif hours: return hours.rstrip() secs = int(left % 60000) if secs: secs /= 1000 return '{0} sec{1}'.format(secs, secs > 1 and 's' or '') return '0 seconds'
def keywithmaxval(dic): """ a) create a list of the dict's keys and values; b) return the key with the max value""" v=list(dic.values()) k=list(dic.keys()) if len(v) > 0: return k[v.index(max(v))] else: return None
def num_digits(n: int) -> int: """ Find the number of digits in a number. >>> num_digits(12345) 5 >>> num_digits(123) 3 """ digits = 0 while n > 0: n = n // 10 digits += 1 return digits
def capitalize_first_character(some_string): """ Description: Capitalizes the first character of a string :param some_string: :return: """ return " ".join("".join([w[0].upper(), w[1:].lower()]) for w in some_string.split())
def root(number, index): """Calculates the number to the specified root""" return float(number) ** (1 / float(index))
def get_nth_subkey_letters(nth: int, key_length: int, message: str) -> str: """Return every nth letter in the message for each set of key_length letters in the message. Args: nth (int): Index to return for every key_length set of letters. key_length (int): Length of the key. message (str): The message Returns: str: The string of the nth letters """ # Remove non-valid characters from the message # message = VALID_CHARACTERS_PATTERN.sub("", message) i = nth - 1 letters = [] while i < len(message): letters.append(message[i]) i += key_length return "".join(letters)
def find_epoch(s): """ Given a package version string, return the epoch """ r = s.partition(':') if r[1] == '': return '' else: return r[0]
def hexagonal(n: int) -> int: """Returns the nth hexagonal number, starting with 1.""" return n * (2 * n - 1)
def decode_list(list_): """ Decodes a list of encoded strings, being sure not to decode None types Args: list_: A list of encoded strings. Returns: A list of decoded strings """ return [ item.decode() if item is not None else None for item in list_ ]
def cleanup_model(model, form): """Remove values for fields that are not visible.""" new_model = {} fields = form["fields"] for key, value in model.items(): if key not in fields: continue if key.startswith("html-"): continue field = fields[key] if not field.get("visible") and value: value = None new_model[key] = value return new_model
def get_username( strategy, details, user= None, *args, **kwargs ): """ Use the 'steamid' as the account username. """ if not user: username = details[ 'player' ][ 'steamid' ] else: username = strategy.storage.user.get_username( user ) return { 'username': username }
def pad(f_bytes, mod_len): """ Pads the file bytes to the nearest multiple of mod_len """ return f_bytes + (b'0' * (mod_len - len(f_bytes) % mod_len))
def mm_as_cm(mm_value): """Turn a given mm value into a cm value.""" if mm_value == 'None': return None return float(mm_value) / 10
def filter_files(file_list, token=".csv"): """ Filter folders and files of a file_list that are not in csv format :param file_list: List of file names :param token: String to find and accept as file, ex: ".csv" :return: Filtered list """ final_file_list = list(filter(lambda f: token in f, file_list[:])) return final_file_list
def sanitize_properties(properties): """ Ensures we don't pass any invalid values (e.g. nulls) to hubspot_timestamp Args: properties (dict): the dict of properties to be sanitized Returns: dict: the sanitized dict """ return { key: value if value is not None else "" for key, value in properties.items() }
def copy_keys_to_each_other(dict_1, dict_2, val=None): """ Make sure that all keys in one dict is in the other dict as well. Only the keys are copied over - the values are set as None eg: dict_1 = { "a": 1, "b": 2 } dict_2 = { "a": 13, "c": 4 } dict_1 after transformation = { "a" : 1, "b": 2, "c": None } dict_2 after transformation = { "a" : 13, "b": None, "c": 4 } """ for key in dict_1: if key not in dict_2: dict_2[key] = None for key in dict_2: if key not in dict_1: dict_1[key] = None return dict_1, dict_2
def split(path): """ splits path into parent, child """ if path == '/': return ('/', None) parent, child = path.rsplit('/', 1) if parent == '': parent = '/' return (parent, child)
def get_kmer_counts(kmer_idx): """ """ kmer_counts = {} for kmer, offsets in kmer_idx.items(): kmer_counts[kmer] = len(offsets) return kmer_counts
def get_line_padding(line_num: int) -> str: """ Gets line_num blank lines. :param line_num: The number of blank lines to get """ line: str = "" for i in range(line_num): line += "\n" return line
def rotate(l, n): """Rotate list for n steps.""" return l[n:] + l[:n]
def _sets_are_unique(sets): """ Returns True if each set has no intersecting elements with every other set in the list :param sets: a list of sets """ nsets = len(sets) for a in range(nsets): for b in range(a + 1, nsets): if len(sets[a].intersection(sets[b])) > 0: return False return True
def get_last_base_call_in_seq(sequence): """ Given a sequence, returns the position of the last base in the sequence that is not a deletion ('-'). """ last_base_pos = None for pos_from_end, base in enumerate(sequence[::-1]): if base != '-': last_base_pos = len(sequence) - pos_from_end break return last_base_pos
def _escape_user_name(name): """Replace `_` in name with `&lowbar;`.""" return name.replace("_", "&lowbar;")
def usage_type(d, i, r): """Get usage type from item :param d: Report definition :type d: Dict :param i: Item definition :type i: Dict :param r: Meter reading :type r: usage.reading.Reading :return: usage_type :rtype: String """ return i.get('usage_type', '')
def tile_coords_and_zoom_to_quadKey(TileX, TileY, zoom): """ The function to create a quadkey for use with certain tileservers that use them, e.g. Bing Parameters ---------- TileX : int x coordinate of tile TileY : int y coordinate of tile zoom : int tile map service zoom level Returns ------- quadKey : str """ quadKey = '' for i in range(zoom, 0, -1): digit = 0 mask = 1 << (i - 1) if (TileX & mask) != 0: digit += 1 if (TileY & mask) != 0: digit += 2 quadKey += str(digit) return quadKey
def wrapTex(tex): """ Wrap string in the Tex delimeter `$` """ return r"$ %s $" % tex
def relay_branch_tuple(relay_branches): """ Create list of (relay, branch) tuples """ relay_branch_tuple = list() for r, branches in relay_branches.items(): for b in branches: relay_branch_tuple.append((r,b)) return relay_branch_tuple
def most_favourite_genre(list_of_genres: list) -> str: """ Return one element, that is the most frequent in 2 lists of list_of_genres, return the first element in first list if there is no intersection or if 2 lists in list_of_genres are empty. If one of lists is empty, return the first element of the another. >>> most_favourite_genre([['Romance', 'Drama'], []]) 'Romance' >>> most_favourite_genre([['Romance', 'Fiction'], ['Fiction', 'Family']]) 'Fiction' >>> most_favourite_genre([[], ['Fiction', 'Family']]) 'Fiction' >>> most_favourite_genre([[], []]) [] """ if len(list_of_genres) == 1: return list_of_genres[0][0] lst1 = list_of_genres[0] lst2 = list_of_genres[1] if lst1 == [] and lst2 != []: return lst2[0] if lst1 != [] and lst2 == []: return lst1[0] if lst1 == [] and lst2 == []: return '' intersection = list(set(lst1) & set(lst2)) if intersection: return intersection[0] return lst1[0]
def sum_of_intervals(intervals): """ Write a function called sumIntervals/sum_intervals() that accepts an array of intervals, and returns the sum of all the interval lengths. Overlapping intervals should only be counted once. Intervals are represented by a pair of integers in the form of an array. The first value of the interval will always be less than the second value. Interval example: [1, 5] is an interval from 1 to 5. The length of this interval is 4. The sum of the lengths of these intervals is 7. Since [1, 4] and [3, 5] overlap, we can treat the interval as [1, 5], which has a length of 4. :param intervals: An array of intervals. :return: The sum of all the interval lengths. """ return len(set(i for x in intervals for i in range(x[0], x[1])))
def extract_hydrogens_from_instructions(instruction): """ If the core or the fragment atom contains a "-" means that the user is selecting an specific H to be bonded with the heavy atom. For this reason, this detects if this option has been selected by the user and extract the PDB-atom-name of each element. :param instruction: list that follow this structure: [fragment_pdb_file, pdb_atom_name_of_the_core (and H if required), pdb_atom_name_of_the_fragment (and H if required)] :return: if the "-" is found in the pdb_atom_name_of_the_core or pdb_atom_name_of_the_fragment it returns a list with PDB-atom-names split following this order: heavy_atom_core, hydrogen_core, heavy_atom_fragment, hydrogen_fragment. Otherwise it returns False. """ if "-" in instruction[1] or "-" in instruction[2]: try: heavy_core = instruction[1].split("-")[0] hydrogen_core = instruction[1].split("-")[1] heavy_fragment = instruction[2].split("-")[0] hydrogen_fragment = instruction[2].split("-")[1] return heavy_core, hydrogen_core, heavy_fragment, hydrogen_fragment except IndexError: raise IndexError(f"Wrong growing direction in {instruction}. Both, fragment and core atoms must include one or two atoms." "Ex: frag.pdb C1 C2 |or| frag.pdb C1-H1 C2-H2") else: return False
def _build_tool_path(d): """Build the list of tool_path for the CROSSTOOL file.""" lines = [] for k in d: lines.append(" tool_path {name: \"%s\" path: \"%s\" }" % (k, d[k])) return "\n".join(lines)
def generate_positive_example(anchor, next_anchor): """Generates a close enough pair of states.""" first = anchor second = next_anchor return first, second
def _excel_col(col): """Covert 1-relative column number to excel-style column label.""" quot, rem = divmod(col - 1, 26) return _excel_col(quot) + chr(rem + ord('A')) if col != 0 else ''
def factorial(n: int) -> int: """ Return n! for postive values of n. >>> factorial(1) 1 >>> factorial(2) 2 >>> factorial(3) 6 >>> factorial(4) 24 """ fact = 1 for i in range(2, n+1): fact=fact*n return fact
def remove_multiple_spaces(string): """ Strips and removes multiple spaces in a string. :param str string: the string to remove the spaces from :return: a new string without multiple spaces and stripped """ from re import sub return sub(" +", " ", string.strip())
def average_above_zero(tab): """ brief : computs the average args : tab : a list of numeric value Return : the computed average Raises : Value error if no positive value Value error if input tab is ot a list """ if not (isinstance(tab, list)):#on verifie si c'est bien une liste (eliminer les cas d'erreur) raise ValueError('Expected a list as Input') average = -99 valSum =0.0 #on le met en float nPositiveValues=0 for val in tab: if val>0: valSum=valSum+float(val) nPositiveValues=nPositiveValues+1 if nPositiveValues<= 0: raise ValueError('No positive values found') average= valSum/nPositiveValues return average
def power(x, n): """Compute the value x**n for integer n.""" if n == 0: return 1 else: partial = power(x, n // 2) # rely on truncated division result = partial * partial if n % 2 == 1: # if n odd, include extra factor of x result *= x return result
def who_wins(character_score_1, character_score_2): """ Determines who wins """ if character_score_1 > character_score_2: return "player 1" else: return "player 2"
def formatExc (exc): """ format the exception for printing """ try: return f"<{exc.__class__.__name__}>: {exc}" except: return '<Non-recognized Exception>'
def check_new_measurement(timestamp, last_measurement): """ checks if latency measurements have been made for the last state @param timestamp: @param last_measurement: @return: """ for dpid_rec in last_measurement: for dpid_sent in last_measurement[dpid_rec]: if last_measurement[dpid_rec][dpid_sent] < timestamp: return False return True
def links_differ(link1, link2): """Return whether two links are different""" differ = True if link1 == link2: differ = False # Handle when url had training slash if link1[0:-1] == link2: differ = False if link2[0:-1] == link1: differ = False return differ
def link(url, title, icon=None, badge=None, **context): """ A single link (usually used in a bundle with 'links' method. :param url: An action this link leads to. 'account', 'event' etc If the url starts with a slash, an looks like this: /aaa/bbb, then this link will lead to action <bbb> of the service <aaa>. Absolute external http(s) links also allowed. :param title: Link's title :param icon: (optional) An icon next to the link (font-awesome) :param badge: (optional) A small badge next to the link, like: See this(github) :param context: A list of arguments making context. link("account", "John's account", icon="account", account=5) link("index", "Home page") link("profile", "See profile", badge="profile", account=14) link("/environment/test", "See profile at 'environment'", badge="profile", account=14) """ return { "url": url, "title": title, "context": context, "badge": badge, "class": "link", "icon": icon }
def merge_metadata(cls): """ Merge all the __metadata__ dicts in a class's hierarchy keys that do not begin with '_' will be inherited. keys that begin with '_' will only apply to the object that defines them. """ cls_meta = cls.__dict__.get('__metadata__', {}) meta = {} for base in cls.__bases__: meta.update(getattr(base, '__metadata__', {})) # Don't merge any keys that start with '_' for key in list(meta.keys()): if key.startswith('_'): del meta[key] meta.update(cls_meta) return meta
def determine_winner(player_move, comp_move): """Takes in a player move and computer move each as 'r', 'p', or 's', and returns the winner as 'player', 'computer', or 'tie'""" if player_move == comp_move: return "tie" elif (player_move == "r" and comp_move == "s") or \ (player_move == "s" and comp_move == "p") or \ (player_move == "p" and comp_move == "r"): return "player" else: return "computer"
def transform_txt_to_json(f): """ Transorm JS Object to JSON with the necessary information """ try: f = open('source.txt', 'rt') lines = f.readlines() f.close() with open('source.json', 'w') as json_file: line_with_data = lines[2][:-2] json_file.write(line_with_data.replace(' data', '{"data"')) json_file.write('}') json_file.close() print("Transform data: OK!") return json_file except Exception as e: print(f'Error in transform: {e}')
def single_line(string: str) -> str: """Turns a multi-line string into a single. Some platforms use CR and LF, others use only LF, so we first replace CR and LF together and then LF to avoid adding multiple spaces. :param string: The string to convert. :return: The converted string. """ return string.replace("\r\n", " ").replace("\n", " ")
def validateYear(year): """ Validate the year value """ if year < 0: return False if len(str(year)) < 4: return False return True
def delete_x_with_catv(names_with_catv): """ Delete variables which end with CATV. Parameters ---------- names_with_catv : List of str. Returns ------- x_names : List of str. """ x_names = [] for x_name in names_with_catv: if x_name[-4:] != 'CATV': x_names.append(x_name) return x_names
def power(term, exponent): """Raise term to exponent. This function raises ``term`` to ``exponent``. Parameters ---------- term : Number Term to be raised. exponent : int Exponent. Returns ------- result : Number Result of the operation. Raises ------ ValueError If exponent is not an integer. See Also -------- add : Addition subtract : Subtraction multiply : Multiplication divide : Division Examples -------- >>> power(1, 1) 1 >>> power(2, 2) 4 >>> power(4, 2) 16 >>> power(10, 2) 100 >>> power(100, 1) 100 >>> power(10, 3) 1000 """ if not isinstance(exponent, int): raise ValueError("Exponent should be an integer. " "You provided {}.".format( type(exponent) )) result = term**exponent return result
def condition_flush_on_every_write(cache): """Boolean function used as flush_cache_condition to anytime the cache is non-empty""" return len(cache) > 0
def expected_overlapping(total, good, draws): """Calculates the expected overlapping draws from total of good.""" drawn = int(round(draws * (good / total))) return min(max(drawn, 0), int(round(good)))
def get_user_profile_url(user): """Return project user's github profile url.""" return 'https://github.com/{}'.format(user)
def has_permission(expected, actual): """ Check if singular set of expected/actual permissions are appropriate. """ x = set(expected).intersection(actual) return len(x) == len(expected)
def recommended_spacecharge_mesh(n_particles): """ ! -------------------------------------------------------- ! Suggested Nrad, Nlong_in settings from: ! A. Bartnik and C. Gulliford (Cornell University) ! ! Nrad = 35, Nlong_in = 75 !28K ! Nrad = 29, Nlong_in = 63 !20K ! Nrad = 20, Nlong_in = 43 !10K ! Nrad = 13, Nlong_in = 28 !4K ! Nrad = 10, Nlong_in = 20 !2K ! Nrad = 8, Nlong_in = 16 !1K ! ! Nrad ~ round(3.3*(n_particles/1000)^(2/3) + 5) ! Nlong_in ~ round(9.2*(n_particles/1000)^(0.603) + 6.5) ! ! """ if n_particles < 1000: # Set a minimum nrad = 8 nlong_in = 16 else: # Prefactors were recalculated from above note. nrad = round(3.3e-2 * n_particles ** (2 / 3) + 5) nlong_in = round(0.143 * n_particles ** (0.603) + 6.5) return {'nrad': nrad, 'nlong_in': nlong_in}
def check_clonotype( probe_v_gene: str, probe_j_gene: str, probe_cdr3_len: int, probe_cdr3_aa_seq: str, target_v_gene: str, target_j_gene: str, target_cdr3_len: int, target_cdr3_aa_seq: str, ) -> float: """ Compares two VH sequences to check if clonotypes match. Returns sequence identity of HCDR3 if clonotype is the same i.e. VH and JH genes are the same. If clonotypes do not match, sequence identity == 0. """ sequence_identity = 0 if ( probe_v_gene == target_v_gene and probe_j_gene == target_j_gene and probe_cdr3_len == target_cdr3_len ): # inverse hamming distance match_count = len( [ True for res1, res2 in zip(probe_cdr3_aa_seq, target_cdr3_aa_seq) if res1 == res2 ] ) sequence_identity = match_count / probe_cdr3_len return sequence_identity
def find_by_key(key, array): """Return a list of array elements whose first element matches the key. Args: key (string): Slash-separated string of keys to search for. array (list): Nested list of lists where first member of each list is a key. Returns: list: Elements from the list with the matching key. """ try: k, sub_key = key.split("/", maxsplit=1) except ValueError: k = key sub_key = None found_elements = [] for e in array: try: k = e[0].value().lower() except (IndexError, AttributeError, TypeError): pass else: if k == key: if not sub_key: found_elements.append(e) else: found_elements.extend(find_by_key(sub_key, e)) return found_elements
def goodMatchGeneralized(matchlist,thresh=10): """This function looks through all the edit distances presented in the list 'matchlist', and returns the smallest one, or -1 if they are all -1 or all above thresh""" bestmatch = -1 minimatch = thresh+10 for match_index in range(len(matchlist)): a =matchlist[match_index] if(a < thresh and a >=0): #at least one of the given matches fits in our threshold! if(a<minimatch): bestmatch = match_index minimatch = a return bestmatch
def remove_multiedges(E): """Returns ``(s, d, w)`` with unique ``(s, d)`` values and `w` minimized. :param E: a set of edges :type E: [(int, int, float)] :return: a subset of edges `E` :rtype: [(int, int, float), ...] """ result = [] exclusion = set() for i, (si, di, wi) in enumerate(E): if i in exclusion: continue minimum = 0 for j in range(i + 1, len(E)): if j in exclusion: continue sj, dj, wj = E[j] if si == sj and di == dj: if wi > wj: exclusion.add(i) elif wi < wj: exclusion.add(j) if i in exclusion: continue result.append(E[i]) return result
def merge_extras(extras1, extras2): """Merge two iterables of extra into a single sorted tuple. Case-sensitive""" if not extras1: return extras2 if not extras2: return extras1 return tuple(sorted(set(extras1) | set(extras2)))