content
stringlengths
42
6.51k
def filter_vdj_alarms(all_alarms, sample_properties): """ Only get subset of metric alarms """ chain_filter = sample_properties.get('chain_type') if chain_filter is None: return all_alarms result = [] for alarm in all_alarms: # No filters specified; don't filter if 'filters' not in alarm: result.append(alarm) continue for f in alarm['filters']: if f.get('chain_type') == chain_filter: result.append(alarm) return result
def get_bigram_scores(text_words, min_bgfreq=2.): """ compute scores for identifying bigrams in a collection of texts compute unigram and bigram frequencies (of words) and give a score for every bigram. depending on this score (e.g. if higher than a threshold), bigram phrases can be identified in the raw texts before splitting them into words --> once the lists of words in the text_words are replaced by appropriate bigrams, the whole thing could be repeated to find trigrams, etc. Input: - text_words: a list (or generator) of lists of (preprocessed) words - min_bgfreq: how often a bigram has to have to occur in the corpus to be recognized (if both words occur just once and that in combination, it still doesn't mean it's a true phrase because we have too little observations of the words Returns: - bigram_scores: a dict with bigrams ("word1 word2") and their score """ unigram_freq = {} bigram_freq = {} for wordlist in text_words: for i, word in enumerate(wordlist): # count unigrams and bigrams try: unigram_freq[word] += 1. except KeyError: unigram_freq[word] = 1. if i: try: bigram_freq["%s %s" % (wordlist[i - 1], word)] += 1. except KeyError: bigram_freq["%s %s" % (wordlist[i - 1], word)] = 1. # compute bigram scores bigram_scores = {} for bigram in bigram_freq: # discount to ensure a word combination occurred a sufficient amount of times if max(0., bigram_freq[bigram] - min_bgfreq): bigram_scores[bigram] = bigram_freq[bigram] / \ max(unigram_freq[bigram.split()[0]], unigram_freq[bigram.split()[1]]) return bigram_scores
def centerOfMass(*args): """input: [m, x, y, z, r] variables: m=mass, x=position-along-x, y=position-along-y, z=position-along-z, r=position-along-radius""" mi=0; xi=1; yi=2; zi=3; ri=4 m_total = sum([item[mi] for item in args]) x = sum([item[mi]*item[xi] for item in args])/m_total y = sum([item[mi]*item[yi] for item in args])/m_total z = sum([item[mi]*item[zi] for item in args])/m_total r = sum([item[mi]*item[ri] for item in args])/m_total return x,y,z,r
def time(present_t, start_t, lap): """ calculates the starting time of the present lap :param present_t: present time :param start_t: starting time of the lap :param lap: duration of the lap :return: starting time of the present lap """ if present_t - start_t >= lap: start_t = present_t return start_t
def infer_time_unit(time_seconds_arr): """ Determine the most appropriate time unit for an array of time durations specified in seconds. e.g. 5400 seconds => 'minutes', 36000 seconds => 'hours' """ if len(time_seconds_arr) == 0: return 'hours' max_time_seconds = max(time_seconds_arr) if max_time_seconds <= 60*2: return 'seconds' elif max_time_seconds <= 60*60*2: return 'minutes' elif max_time_seconds <= 24*60*60*2: return 'hours' else: return 'days'
def is_binary_dxf_file(filename: str) -> bool: """Returns ``True`` if `filename` is a binary DXF file.""" with open(filename, "rb") as fp: sentinel = fp.read(22) return sentinel == b"AutoCAD Binary DXF\r\n\x1a\x00"
def outputCode(x): """ x = <-4.1714, 4.1714> y = <0, 1> Formula: y = (x + 4.1714) / 8.3428 """ x = float(x) return (x + 4.1714) / 8.3428
def replace_dict_keys(dicts, replace_list_dict): """ Replace values in `dicts` according to `replace_list_dict`. Parameters ---------- dicts : dict Dictionary. replace_list_dict : dict Dictionary. Returns ------- replaced_dicts : dict Dictionary. Examples -------- >>> replace_dict_keys({"a":1,"b":2,"c":3}, {"a":"x","b":"y"}) {'x': 1, 'y': 2, 'c': 3} >>> replace_dict_keys({"a":1,"b":2,"c":3}, {"a":"x","e":"y"}) # keys of `replace_list_dict` {'x': 1, 'b': 2, 'c': 3} """ replaced_dicts = dict([(replace_list_dict[key], value) if key in list(replace_list_dict.keys()) else (key, value) for key, value in dicts.items()]) return replaced_dicts
def es5(n): """ Write a script that, given an input number n, computes the numbers of the Fibonacci sequence that are less than n. """ if n <= 0: return 0 if n <= 1: return 1 a, b = 0, 1 cont = 2 while a + b < n: b += a a = b - a cont += 1 return cont
def _is_slice_in_list(s, l): """ Check if list s in in list l :param s: first array :param l: second array :return: bool """ len_s = len(s) return any(s == l[i:len_s + i] for i in range(len(l) - len_s + 1))
def _stix_vid_to_version(stix_vid): """ Convert a python package name representing a STIX version in the form "vXX" to the dotted style used in the public APIs of this library, "X.X". :param stix_vid: A package name in the form "vXX" :return: A STIX version in dotted style """ assert len(stix_vid) >= 3 stix_version = stix_vid[1] + "." + stix_vid[2:] return stix_version
def exclude_zero_decimals(value): """ Returns removes trailing zeros from decimal numbers if all numbers after the decimal are zeros. """ if value==None: return_value=value else: str_value = str(value) value_length = len(str_value) decimal_index = str_value.index('.'); str_decimals = str_value[decimal_index+1:value_length]; if str_decimals.count(str_decimals[0]) == len(str_decimals) and str_decimals[0] == '0': str_value = str_value[0:decimal_index] return_value=str_value return return_value
def name_to_path_name(name): """ :param name: :return: """ return name.replace("\\", "\\\\")\ .replace(".", r"\.")\ .replace("$", r"\$")\ .replace("|", r"\|")\ .replace("[", r"\[")\ .replace("]", r"\]")
def contains_num(token): """ Return True for - Dates: 21.01.2011 - Probably egzotic entities: B2B, sum41 - Skype names: duygu621 Args: token: single token Returns: Booelan Raises: None Examples: >>> contains_num("duygu") False >>> contains_num("2.2017") True """ nums = "0123456789" return any(num in token for num in nums)
def rcomp(s): """Does same thing as reverse_complement only cooler""" return s.translate(str.maketrans("ATCG","TAGC"))[::-1]
def get_verification_code(hash_value): """Compute Mobile-ID verification code from a hash Excerpt from https://github.com/SK-EID/MID#241-verification-code-calculation-algorithm 1. 6 bits from the beginning of hash and 7 bits from the end of hash are taken. 2. The resulting 13 bits are transformed into decimal number and printed out. The Verification code is a decimal 4-digits number in range 0000...8192, always 4 digits are displayed (e.g. 0041). :param bytes hash_value: """ if not isinstance(hash_value, bytes): raise TypeError(f"Invalid hash value: expected bytes, got {type(hash_value)}") if not hash_value: raise ValueError("Hash value can not be empty") leading_byte = hash_value[0] trailing_byte = hash_value[-1] leading_6_bits = leading_byte >> 2 trailing_7_bits = trailing_byte & 0x7F raw_value = (leading_6_bits << 7) + trailing_7_bits return f"{raw_value:04d}"
def first_line(s): """Return first full line from string s (not including the '\n') """ i = s.find('\n') if i > 0: return s[:i] else: raise RuntimeError("can't find '\\n' in first_line")
def urlQuoteSpecific(s, toQuote=''): """ Only quote characters in toQuote """ result = [] for c in s: if c in toQuote: result.append("%%%02X" % ord(c)) else: result.append(c) return "".join(result)
def format_key(key): """ Format the key provided for consistency. """ if key: return key if key[-1] == "/" else key + "/" return "/"
def format_skills(items): """Format list of skills to a string for CLI output.""" list_str = '' for item in items: list_str += ( '{line}\n' 'Name: {name}\n' 'Description: {description}\n' 'Protocols: {protocols}\n' 'Version: {version}\n' '{line}\n'.format( name=item['name'], description=item['description'], version=item['version'], protocols=''.join( name + ' | ' for name in item['protocol_names'] ), line='-' * 30 )) return list_str
def unbox_usecase(x): """ Expect a set of numbers """ res = 0 for v in x: res += v return res
def allZeroDict(source): """ Checks whether or not a dictionary contains only 0 items :param source: a dictionary to test :returns: bool -- whether or not all entries in the dictionary are equal to zero """ for i in source.values(): if i != 0: return False return True
def stringifydict(res): """[summary] Args: res ([type]): [description] Returns: [type]: [description] """ a = {} for k, v in res.items(): if type(v) is dict: a[k] = stringifydict(v) else: a[str(k)] = v return a
def rec_cmp_releases(one, two): """Recursive function that compares two version strings represented as lists to determine which one comes "after" / takes precedence, or if they are equivalent. List items must be integers (will throw TypeError otherwise). If the left argument ("one") is a later version, returns 1. If the right argument ("two") is a later version, returns 2. If they are equivalent, returns 0. :param one: list of ints to compare to two :param two: list of ints to compare to one :returns: code in (0, 1, 2) :rtype: int """ # we've exhausted all three levels of comparison, so logically we're at equivalence. if len(one)==0: return 0 top1 = one[0] top2 = two[0] if top1 > top2: return 1 elif top1 < top2: return 2 else: return rec_cmp_releases(one[1:], two[1:])
def calculateYVertice(termA, termB, termC, xVertice): """ Calculates the value of the vertice Y. """ vertice = ((termA*(pow(xVertice, 2)) + (termB*xVertice) + termC)) return vertice
def locate_s_in_RHS(surf_index, surf_array): """Find starting index for current surface on RHS This is assembling the RHS of the block matrix. Needs to go through all the previous surfaces to find out where on the RHS vector it belongs. If any previous surfaces were dirichlet, neumann or asc, then they take up half the number of spots in the RHS, so we act accordingly. Arguments --------- surf_index: int, index of surface in question surf_array: list, list of all surfaces in problem Returns ------- s_start: int, index to insert values on RHS """ s_start = 0 for surfs in range(surf_index): if surf_array[surfs].surf_type in ['dirichlet_surface', 'neumann_surface', 'asc_surface']: s_start += len(surf_array[surfs].xi) else: s_start += 2 * len(surf_array[surfs].xi) return s_start
def parse_integer_range(bounds_string): """ Returns an integer lower bound and upper bound of the range defined within <bounds_string>. Formats accepted include 'n', 'n+', and 'm-n'. :param bounds_string: String representing a range of integers :return: Pair of integer lower bound and upper bound on the range """ if bounds_string.endswith('+'): lower_bound = int(bounds_string[:-1]) upper_bound = float('inf') elif bounds_string.count('-') == 1: lower_bound, upper_bound = map(int, bounds_string.split('-')) else: lower_bound = int(bounds_string) upper_bound = lower_bound return (lower_bound, upper_bound)
def sanitize_path(path): """Cleaning up path for saving files.""" return "".join([c for c in path if c.isalpha() or c.isdigit() or c in ' .-_,']).rstrip()
def interpolate(point1, point2, numberOfPoints, roundToInt = True): """<numberOfPoints> should be greater or equal to 1. <numberOfPoints> is number of points from point1 until point2.""" if numberOfPoints == 1: return([point1]) interval = (point2 - point1) / numberOfPoints if roundToInt: return([int(round(point1 + i * interval)) for i in range(numberOfPoints)]) return([point1 + i * interval for i in range(numberOfPoints)])
def default_case(experiment_code, participantid, project_id): """Creates a minimal case.""" return { "type": "case", "experiments": {"submitter_id": experiment_code}, "submitter_id": participantid, "primary_site": "unknown", "disease_type": "unknown", "project_id": project_id }
def smoothstep(a, b, x): """ Returns the Hermite interpolation (cubic spline) for x between a and b. The return value between 0.0-1.0 eases (slows down) as x nears a or b. """ if x < a: return 0.0 if x >= b: return 1.0 x = float(x - a) / (b - a) return x * x * (3 - 2 * x)
def reverse_string_iterative(s): """ Returns the reverse of the input string Time complexity: O(n) Space complexity: O(n) More efficient, only 3 O(n) operations """ chars = list(s) # O(n) i, j = 0, len(s) - 1 while i < j: # O(n) chars[i], chars[j] = chars[j], chars[i] i += 1 j -= 1 return "".join(chars)
def line_interpolate_y(line, x): """Interpolates y values on a line when given x To avoid duplicate hits for nodes level with the joints between lines, the end of a line is not considered an intersection.""" if line[0][0] == x: return line[0][1] #if line[1][0] == x: # return line[1][1] elif (line[0][0] < x < line[1][0]) and ((line[1][0] - line[0][0]) != 0): return line[0][1] + (x - line[0][0]) * (line[1][1] - line[0][1]) / (line[1][0] - line[0][0]) else: return None
def print_result(error, real_word): """" print_result""" if error == 5: print("You lost!") print("Real word is:", real_word) else: print("You won!") return 0
def get_config_contract(config): """ A function to delete context and dockerfile_path from config """ if not config: return config if "context" in config: del config["context"] if "dockerfile_path" in config: del config["dockerfile_path"] return config
def merge(a,b): """ Function to merge two arrays """ c = [] while len(a) != 0 and len(b) != 0: if a[0] < b[0]: c.append(a[0]) a.remove(a[0]) else: c.append(b[0]) b.remove(b[0]) if len(a) == 0: c += b else: c += a return c
def seq_sqrt(xs): """Computes and returns a list of the square-roots of each value in xs.""" sqrts = [] for n in xs: if n >= 0: sqrts.append(n ** 0.5) else: sqrts.append(0) return sqrts
def tokenise(line): """Tokenise a string and return a list. Split a line of text into tokens separated by whitespace, but ignoring whitespace that appears within quotes. This attempts to do a similar to job the CCP4 'parser' (which is itself actually a tokeniser) in the core CCP4 libraries. The hard part is dealing with quoted strings which form a single token, and which can themselves also contain quotes.""" sline = str(line) tokens = [] token = False quote = False tquote = "" start = 0 for i in range(len(sline)): c = sline[i] if token and not quote: if c == " " or c == "\t" or c == "\n": # end of current token tokens.append(sline[start:i]) token = False quote = False if token and ( c == '"' or c == "'" ): # Detected a quote - flip the quote flag if quote: if c == tquote: quote = False else: quote = True tquote = c if not token: if c != " " and c != "\t" and c != "\n": # Start of a new token token = True start = i if c == '"' or c == "'": # Also it's quoted quote = True tquote = c # End of the loop if token: # End of the last token tokens.append(sline[start:len(sline)]) return tokens
def solution(s: str) -> int: """ >>> solution('(()(())())') 1 >>> solution('())') 0 """ count = 0 m = {'(': 1, ')': -1} for token in s: count += m[token] if count < 0: return 0 return 0 if count else 1
def untrack_cache_storage_for_origin(origin: str) -> dict: """Unregisters origin from receiving notifications for cache storage. Parameters ---------- origin: str Security origin. """ return { "method": "Storage.untrackCacheStorageForOrigin", "params": {"origin": origin}, }
def create_distribution_chart(p_summary): """ Helper function that generates Tool distribution chart Args: p_summary (dictionary): parsed summary.yaml """ graph_data = [set() for i in range(len(p_summary.keys()))] all_fusions = [fusions for _, fusions in p_summary.items()] all_fusions = sum(all_fusions, []) for fusion in all_fusions: index = all_fusions.count(fusion) graph_data[index - 1].add(fusion) return [[str(index + 1) + ' tool/s', len(value)] for index, value in enumerate(graph_data)]
def count_swaps(str_one, str_two): """ return the minimum number of swaps necessary to change str_one into str_two """ left, right = '', '' swap_count = 0 # iterate strings and find differences. store non-matching characters in left and right # evaluate, and count matching pairs that can be swapped return swap_count
def get_ion_actor_id(process): """Given an ION process, return the ion-actor-id from the context, if set and present""" ion_actor_id = None if process: ctx = process.get_context() ion_actor_id = ctx.get('ion-actor-id', None) if ctx else None return ion_actor_id
def UpperCase(text : str): """Returns Uppercase text.""" return text.upper()
def scrub_external_ids(eids): """ Removes the index from "univaf_v.[_.]" keys. """ for i in range(len(eids)): if 'univaf' not in eids[i]: continue if 'v' not in eids[i].split(':')[0].split('_')[-1]: # very risky! assumes keys to be "univaf.v._.:.*" eids[i] = eids[i][:9] + eids[i][11:] return eids
def line_id_2_txt(line_id): """ Convert line id (integer) to string nnnn :return: line_id_txt -> <string> ID de la linia introduit en format text """ line_id_str = str(line_id) if len(line_id_str) == 1: line_id_txt = "000" + line_id_str elif len(line_id_str) == 2: line_id_txt = "00" + line_id_str elif len(line_id_str) == 3: line_id_txt = "0" + line_id_str else: line_id_txt = line_id_str return line_id_txt
def suppress_non_unicode(dirty_string): """Get rid of non-unicode characters. WARNING: This loops through each character in strings. Use sparingly. http://stackoverflow.com/questions/20078816/replace-non-ascii-characters-with-a-single-space """ return '' .join([i if ord(i) < 128 else ' ' for i in dirty_string])
def make_hit(card, cards, deck): """ Adds a card to player's hand """ if card in deck: cards.append(card) deck.remove(card) return cards
def bsearch(n, pred): """ Given a boolean function pred that takes index arguments in [0, n). Assume the boolean function pred returns all False and then all True for values. Return the index of the first True, or n if that does not exist. """ # invariant: last False lies in [l, r) and pred(l) is False if pred(0): return 0 l = 0 r = n while r-l > 1: m = l + (r-l)//2 result = pred(m) if result: r = m else: l = m return l+1
def gctor2newc(name, args): """Create a new container object based on generator-constructor name.""" if name == "construct_yaml_set": return set() if name == "construct_yaml_map": return {} if name == "construct_yaml_object": return args[0].__new__(args[0]) return []
def convert_rankine_to_celcius(temp): """Convert the temperature from Rankine to Celcius scale. :param float temp: The temperature in degrees Rankine. :returns: The temperature in degrees Celcius. :rtype: float """ return ((temp - 491.67) * 5) / 9
def enum(cls): """Make a class behave like an enumerated type by generating a reverse mapping for all the names defined on the class which are uppercased. """ rmap = {} for name in dir(cls): if name == name.upper(): k = cls.__name__ + "_" + name v = getattr(cls, name) if (v not in rmap or k < rmap[v]): rmap[v] = k cls.codes = rmap return cls
def get_status_from_node(data_item): """ Extract the status conditions from the data Returns: a dict combining the hostname and the status conditions. """ addresses = data_item['status']['addresses'] address = None for addr in addresses: if addr['type'] == 'Hostname': address = addr['address'] assert address is not None # There is always a hostname. return {'hostname': address, 'conditions': data_item['status']['conditions']}
def pop_known_arguments(args): """Extracts known arguments from the args if present.""" rest = [] run_test_cases_extra_args = [] for arg in args: if arg.startswith(('--gtest_filter=', '--gtest_output=')): run_test_cases_extra_args.append(arg) elif arg == '--run-manual': run_test_cases_extra_args.append(arg) elif arg == '--gtest_print_time': # Ignore. pass elif 'interactive_ui_tests' in arg: # Run this test in a single thread. It is useful to run it under # run_test_cases so automatic flaky test workaround is still used. run_test_cases_extra_args.append('-j1') rest.append(arg) elif 'browser_tests' in arg: # Test cases in this executable fire up *a lot* of child processes, # causing huge memory bottleneck. So use less than N-cpus jobs. run_test_cases_extra_args.append('--use-less-jobs') rest.append(arg) else: rest.append(arg) return run_test_cases_extra_args, rest
def duplicate_encode_oneline_list(word): """List comp version.""" return "".join(["(" if word.count(c) == 1 else ")" for c in word])
def serialize_monto(valor=0, moneda="MXN"): """ $ref: '#/components/schemas/monto' """ if valor: return { "valor": 0 if valor is None else int(valor), "moneda": moneda } return {"valor": 0, "moneda": moneda}
def _fk(feature_name, channel, target): """Construct a dict key for a feature instance""" return "{}::{}::{}".format(feature_name, channel, target)
def binary_to_decimal(binary): """Converts a binary number into a decimal""" reversed_binary = binary[::-1] # i = correct power when reversed decimal = 0 for i, value in enumerate(reversed_binary): if value == "0": continue # ignore 0 because no value decimal += 2**i # multiply 2 by i b/c index = power, add this value to decimal variable return decimal
def calScNoEq1(GaDe, GaVi, GaDiCoi): """ calculate Schmidt number args: GaDe: gas density [kg/m^3] GaVi: gas viscosity [Pa.s] | [kg/m.s] GaDiCoi: gas component diffusivity coefficient [m^2/s] """ # try/except try: return (GaVi/GaDe)/GaDiCoi except Exception as e: raise
def formatSurveyStr(survey): """Format survey keyword data @param[in] surveyData: the value of guider.survey or sop.survey (a pair of strings, either of which may be None) """ surveyStrList = [] if survey[0] is None: surveyStrList.append("?") else: surveyStrList.append(survey[0]) if survey[1] is None: surveyStrList.append("?") elif survey[1].lower() != "none": surveyStrList.append(survey[1]) return "-".join(surveyStrList)
def html_strip(text): """ Strips html markup from text """ mark = 0 markstart = 0 markend = 0 index = 0 occur = 0 for i in text: if i == "<": try: if text[index+1] != " ": mark = 1 markstart = index except(IndexError): pass elif i == ">": if mark == 1: mark = 0 markend = index text = "%s%s" % (text[:markstart], text[markend+1:]) occur = 1 break index += 1 if occur == 1: text = html_strip(text) return text
def _parse_package_name(name: str) -> str: """ Force lower case and replace underscore with dash to compare environment packages (see https://www.python.org/dev/peps/pep-0426/#name) Args: name: Unformatted package name Returns: Formatted package name """ return name.lower().replace("_", "-")
def count_sequences(data): """Count the number of JSON NE sequences. :param data: Dictionary of NE sequences :type data: Dictionary :return: Number of NE sequences :rtype: Integer """ count = 0 try: for value in data.items(): if isinstance(value, list): count += len(value) except: print('Invalid NE sequences format') return count
def convert_to_string(num): """ Converts a base 27 number back into a string @param num The number we wish to convert @return converted_string The string of that number @complexity O(M) where M the length of the string """ converted_string = "" while num > 0: # Loop for converting back from number to string, backward: converted_string += (chr(97 + (num - 1) % 26)) num -= 1 num //= 26 converted_string = converted_string[::-1] # Flip the order for return purposes return converted_string
def check_win(board,player_marker): """ Checks if computer/player wins """ return ((board[0] == player_marker and board[1] == player_marker and board[2] == player_marker) or (board[3] == player_marker and board[4] == player_marker and board[5] == player_marker) or (board[6] == player_marker and board[7] == player_marker and board[8] == player_marker) or (board[0] == player_marker and board[3] == player_marker and board[6] == player_marker) or (board[1] == player_marker and board[4] == player_marker and board[7] == player_marker) or (board[2] == player_marker and board[5] == player_marker and board[8] == player_marker) or (board[0] == player_marker and board[4] == player_marker and board[8] == player_marker) or (board[2] == player_marker and board[4] == player_marker and board[6] == player_marker))
def clean_escseq(element, encodings): """Remove escape sequences that Python does not remove from Korean encoding ISO 2022 IR 149 due to the G1 code element. """ if 'euc_kr' in encodings: return element.replace( "\x1b\x24\x29\x43", "").replace("\x1b\x28\x42", "") else: return element
def refinement_func_area(tri_points, area): """ refine (equivalent to the max_volume parameter) """ max_area = 0.005 return bool(area > max_area)
def backwards(string): """Return string, but backwards.""" return string[::-1] # Could also be: # return ''.join(reversed(string))
def get_qual_range(qual_str): """ >>> get_qual_range("DLXYXXRXWYYTPMLUUQWTXTRSXSWMDMTRNDNSMJFJFFRMV") (68, 89) """ vals = [ord(c) for c in qual_str] return min(vals), max(vals)
def makeListList(roots): """Checks if the element of the given parameter is a list, if not, creates a list with the parameter as an item in it. Parameters ---------- roots : object The parameter to be checked. Returns ------- list A list containing the parameter. """ if isinstance(roots[0], (list, tuple)): return roots else: return [roots]
def valid_passphrase(passphrase: str) -> bool: """Find if there are no repeated words in this passphrase.""" all_words = passphrase.split() return len(all_words) == len(set(all_words))
def getLineFromPoints(point1, point2): """ Get line parameter (y = mx +c) from two points. Parameters ---------- point1, point2 : list of int Coordinates of the two points Returns ------- m, c : float Line parameters for y = mx +c """ # m = (y2 - y1)/(x1 - x2) m = (point2[1] - point1[1]) / (point2[0] - point1[0]) # c = y2 - m*x2 c = point2[1] - m * point2[0] return m, c
def to_img_tag(b64): """Create an Img html tag from a base64 string. Parameters ---------- b64 : :class:`str` A base 64 string. Returns ------- :class:`str` The <img> tag. """ return f'<img src="data:image/jpeg;base64, {b64}"/>'
def howmany_within_range(row, minimum, maximum): """Returns how many numbers lie within `maximum` and `minimum` in a given `row`""" count = 0 for n in row: if minimum <= n <= maximum: count = count + 1 return count
def domain_level(host): """ >>> domain_level('') 0 >>> domain_level(' ') 0 >>> domain_level('com') 1 >>> domain_level('facebook.com') 2 >>> domain_level('indiana.facebook.com') 3 """ if host.strip() == '': return 0 else: raw_parts = host.strip().split('.') parts = [p for p in raw_parts if p != ''] return len(parts)
def guess_module_name(fct): """ Guesses the module name based on a function. @param fct function @return module name """ mod = fct.__module__ spl = mod.split('.') name = spl[0] if name == 'src': return spl[1] return spl[0]
def encrypt(plaintext, key): """ encrypt encryption function. Encrypts the text using the Caesar Cypher method. :param plaintext: text block input :type plaintext: str :param key: key for encryption :type key: int :return: text block output :rtype: str """ cyphertext = '' for character in plaintext: if character.isalpha(): number = ord(character) number += key if character.isupper(): if number > ord('Z'): number -= 26 elif number < ord('A'): number += 26 elif character.islower(): if number > ord('z'): number -= 26 elif number < ord('a'): number += 26 character = chr(number) cyphertext += character return cyphertext
def getValid(pair1, pair2): """ Validate that the pair does not have the same key used twice """ res = [] for p1 in pair1: for p2 in pair2: if not p1 & p2 and p1|p2 not in res: res.append(p1|p2) return res
def orderTranscriptsByChromosome(transcripts): """ orders a set of transcripts by chromosome """ chromosomes = {} for trans_id in transcripts.keys(): seqname = transcripts[trans_id][0]['seqname'] if seqname not in chromosomes: chromosomes[seqname] = [trans_id] else: index = len(chromosomes[seqname]) - 1 ss = transcripts[chromosomes[seqname][index]][0]['start'] while(int(ss) > int(transcripts[trans_id][0]['start'])): index = index - 1 if index == -1: break ss = transcripts[chromosomes[seqname][index]][0]['start'] chromosomes[seqname].insert(index + 1, trans_id) return chromosomes
def factorial(x): """This function returns the factorial of a single input/argument.""" # check if input value is negative or positive if x < 0: return print("Factorials do not exist for negative numbers.") else: y = 1 for i in range(1, x + 1): y = y * i return y
def fully_qualified_classname(class_or_instance): """Get the fully qualified Python path of a class (or instance). Parameters ---------- class_or_instance : any The class (or instance of a class) to work on Returns ------- str The fully qualified, dotted Python path of that class or instance. """ if isinstance(class_or_instance, type): # operating on a class (NOT an instance!) return ".".join([class_or_instance.__module__, class_or_instance.__qualname__]) # operating on an instance return ".".join( [ class_or_instance.__class__.__module__, class_or_instance.__class__.__qualname__, ] )
def _expand(dat, counts, start, end): """ expand the same counts from start to end """ for pos in range(start, end): for s in counts: dat[s][pos] += counts[s] return dat
def escape(container, field, app_map=None): """ See: http://www.hl7standards.com/blog/2006/11/02/hl7-escape-sequences/ To process this correctly, the full set of separators (MSH.1/MSH.2) needs to be known. Pass through the message. Replace recognised characters with their escaped version. Return an ascii encoded string. Functionality: * Replace separator characters (2.10.4) * replace application defined characters (2.10.7) * Replace non-ascii values with hex versions using HL7 conventions. Incomplete: * replace highlight characters (2.10.3) * How to handle the rich text substitutions. * Merge contiguous hex values """ if not field: return field esc = str(container.esc) DEFAULT_MAP = { container.separators[1]: "F", # 2.10.4 container.separators[2]: "R", container.separators[3]: "S", container.separators[4]: "T", container.esc: "E", "\r": ".br", # 2.10.6 } rv = [] for offset, c in enumerate(field): if app_map and c in app_map: rv.append(esc + app_map[c] + esc) elif c in DEFAULT_MAP: rv.append(esc + DEFAULT_MAP[c] + esc) elif ord(c) >= 0x20 and ord(c) <= 0x7E: rv.append(c) else: rv.append("%sX%2x%s" % (esc, ord(c), esc)) return "".join(rv)
def gray(s): """Color text gray in a terminal.""" return "\033[1;30m" + s + "\033[0m"
def appointment_removal(parent, list_to_remove): """ Removes the appointment in list_to_remove from parent. """ for element in list_to_remove: for index in range(0, len(parent)): parent[index] = \ [item for item in parent[index] if item != element] return parent
def tei_to_omeka_header(csv_header_info): """ Transforms an XML-TEI header path to a Omeka (semantic-web compliant) header.""" # XML-TEI headers elements to Linked Data correspondences xml_tag_to_voc = { u"#fileDesc#titleStmt_title": u"dc:title", u"#fileDesc#titleStmt_author_key": u"dc:creator", u"#fileDesc#sourceDesc#bibl_publisher": u"dc:publisher", u"#fileDesc#sourceDesc#bibl_pubPlace": u"pubPlace", u"#fileDesc#sourceDesc#bibl_date": u"dc:date", u"#profileDesc#langUsage_language_ident": u"dc:language", u"#fileDesc#sourceDesc#bibl_ref_target":u"dc:relation", u"#fileDesc#publicationStmt_idno": u"dc:identifier", # Obligatoire u"#fileDesc#publicationStmt#availability_licence_target": u"dc:rights", } new_csv_header_info = {xml_tag_to_voc.get(k, k): v for (k, v) in csv_header_info.items()} if u"dc:creator" not in new_csv_header_info: not_normalized_creator_form = new_csv_header_info.get(u"#fileDesc#titleStmt_author", False) if not_normalized_creator_form: new_csv_header_info[u"dc:creator"] = not_normalized_creator_form return {k: v for (k, v) in new_csv_header_info.items() if not k.startswith('#')}
def n2npairs(n): """return number of pairs for n conditions. see also scipy.special.binom.""" return (n - 1) * n / 2
def get_lcm(num1,num2): """ returns lowest common multiple amoung two numbers """ if(num1>num2): num = num1 den = num2 else: num = num2 den = num1 rem = num % den while(rem != 0): num = den den = rem rem = num % den gcd = den lcm = int(int(num1 * num2)/int(gcd)) return lcm
def parse_id(text): """Parse a string into a list of integers. :param str text: the input string. :return list: a list of IDs which are integers. :raise ValueError Examples: Input IDs separated by comma: parse_id("1, 2, 3") == [1, 2, 3] parse_id("1, 2, ,3") == [1, 2, 3] parse_id("1, 1, ,1") == [1] Range-based input: parse_id("0:5") == [0, 1, 2, 3, 4] parse_id("0:5:2") == [0, 2, 4] Combination of the above two styles: parse_id("1:3, 5") == [1, 2, 5] ":" means all the pulses in a train. The indices list will be generated after data is received. parse_id(":") == [-1] """ def parse_item(v): if not v: return [] if v.strip() == ':': return [-1] if ':' in v: try: x = v.split(':') if len(x) < 2 or len(x) > 3: raise ValueError("The input is incomprehensible!") start = int(x[0].strip()) if start < 0: raise ValueError("Pulse index cannot be negative!") end = int(x[1].strip()) if len(x) == 3: inc = int(x[2].strip()) if inc <= 0: raise ValueError( "Increment must be a positive integer!") else: inc = 1 return list(range(start, end, inc)) except Exception as e: raise ValueError("Invalid input: " + repr(e)) else: try: v = int(v) if v < 0: raise ValueError("Pulse index cannot be negative!") except Exception as e: raise ValueError("Invalid input: " + repr(e)) return v ret = set() # first split string by comma, then parse them separately for item in text.split(","): item = parse_item(item.strip()) if isinstance(item, int): ret.add(item) else: ret.update(item) return sorted(ret)
def convert_to_days(period_type, time_to_elapse): """ :param period_type: :param time_to_elapse: :return: """ return time_to_elapse * 7 if 'week' in period_type else time_to_elapse * 30
def parallel_multiplier(items): """Determine if we will be parallelizing items during processing. """ multiplier = 1 for data in (x[0] for x in items): if data["config"]["algorithm"].get("align_split_size"): multiplier += 50 return multiplier
def K(u, kap, eps): """Compute diffusion function .. math:: K(u) = \kappa \, (1 + \varepsilon u)^3 + 1 Parameters ---------- u : array_like Temperature variable. kap : float Diffusion parameter. eps : float Inverse of activation energy. Returns ------- array_like Evaluation of K function. """ return kap * (1 + eps * u) ** 3 + 1
def Q(p0, p1, v0, v1, t0, t1, t): """Basic Hermite curve.""" s = (t-t0)/(t1-t0) h0 = (2*s+1)*(s-1)*(s-1) h1 = (-2*s+3)*s*s h2 = (1-s)*(1-s)*s*(t1-t0) h3 = (s-1)*s*s*(t1-t0) return h0*p0 + h1*p1 + h2*v0 + h3*v1
def pprint_blockers(blockers): """Pretty print blockers into a sequence of strings. Results will be sorted by top-level project name. This means that if a project is blocking another project then the dependent project will be what is used in the sorting, not the project at the bottom of the dependency graph. """ pprinted = [] for blocker in sorted(blockers, key=lambda x: tuple(reversed(x))): buf = [blocker[0]] if len(blocker) > 1: buf.append(' (which is blocking ') buf.append(', which is blocking '.join(blocker[1:])) buf.append(')') pprinted.append(''.join(buf)) return pprinted
def accept_file(file, filters): """ Returns True if file shall be shown, otherwise False. Parameters: file - an instance of FileSystemObject filters - an array of lambdas, each expects a file and returns True if file shall be shown, otherwise False. """ for filter in filters: if filter and not filter(file): return False return True
def _to_initials(state): """ Given a state, returns its initials """ states = { 'Alaska': 'AK', 'Alabama': 'AL', 'Arkansas': 'AR', 'American Samoa': 'AS', 'Arizona': 'AZ', 'California': 'CA', 'Colorado': 'CO', 'Connecticut': 'CT', 'District of Columbia': 'DC', 'Delaware': 'DE', 'Florida': 'FL', 'Georgia': 'GA', 'Guam': 'GU', 'Hawaii': 'HI', 'Iowa': 'IA', 'Idaho': 'ID', 'Illinois': 'IL', 'Indiana': 'IN', 'Kansas': 'KS', 'Kentucky': 'KY', 'Louisiana': 'LA', 'Massachusetts': 'MA', 'Maryland': 'MD', 'Maine': 'ME', 'Michigan': 'MI', 'Minnesota': 'MN', 'Missouri': 'MO', 'Northern Mariana Islands': 'MP', 'Mississippi': 'MS', 'Montana': 'MT', 'National': 'NA', 'North Carolina': 'NC', 'North Dakota': 'ND', 'Nebraska': 'NE', 'New Hampshire': 'NH', 'New Jersey': 'NJ', 'New Mexico': 'NM', 'Nevada': 'NV', 'New York': 'NY', 'Ohio': 'OH', 'Oklahoma': 'OK', 'Oregon': 'OR', 'Pennsylvania': 'PA', 'Puerto Rico': 'PR', 'Rhode Island': 'RI', 'South Carolina': 'SC', 'South Dakota': 'SD', 'Tennessee': 'TN', 'Texas': 'TX', 'Utah': 'UT', 'Virginia': 'VA', 'Virgin Islands': 'VI', 'Vermont': 'VT', 'Washington': 'WA', 'Wisconsin': 'WI', 'West Virginia': 'WV', 'Wyoming': 'WY' } return states[state]
def map_args(args): """used to filter arguments passed in on the command line that should also be passed as keyword args to make_map""" arg_set = set(['starting_year', 'ending_year', 'ranking_algorithm', 'similarity_algorithm', 'filtering_algorithm', 'number_of_terms', 'include_svg_dimensions', 'file_format', 'only_terms', 'sample_size', 'evaluation_output_path', 'n_layers']) graphattr_set = set(['layerselect']) pass_args = {} for arg in arg_set: if arg in args: pass_args[arg] = args[arg] graph_attrs = { key: args[key] for key in graphattr_set if key in args and args[key]} pass_args['graph_attrs'] = graph_attrs return pass_args
def gen_rate_step(n, schedule): """ :param n: the current iteration number :param schedule: a dictionary where the keys are the min value for the step and the values are the corresponding rate; for example, {0: 0.005, 200: 0.0002, 400: 0.0001} is an annealing schedule where iterations 0 to 200 get a rate of 0.005, iterations 201 to 400 get a rate of 0.0002, and iterations >400 get a rate of 0.0001; importantly, schedule dictionaries will be ordered by key, and the first key must be 0 :return: the corresponding rate for the iteration number n """ sorted_keys = sorted(schedule.keys()) if len(sorted_keys) < 1 or sorted_keys[0] != 0: raise Exception("the schedule must contain 0 as a key") for k in reversed(sorted_keys): if n > k: return schedule[k] if n == 0: return schedule[0]
def is_valid_minute(minute): """ Check if minute value is valid :param minute: int|string :return: boolean """ return (minute == '*') or (59 >= minute >= 0)
def contained_in_others(ls, others): """ Identifies whether all of the elements in ls are contained in the lists of others (a list of lists of items (O(n^2)) """ return all(any([elem in other_ls for other_ls in others]) for elem in ls)