content
stringlengths
42
6.51k
def identify_target_ligand(ligand_residues): """Attempts to guess the target ligand""" # If there is only one target ligand then that must be the target # even if there are multiple instances. That could be the case if # the compound is peptidic for example. if len(ligand_residues) == 1: ret...
def get_divisors_sum(number): """ Gives the sum of divisors of a number = S According to the Zur algorithm, S should be equal to total number of trans_matrices """ if number == 0: return 0 divisors_list = [] for i in range(number+1): j = i + 1 if number % j == 0:...
def RCI_calc(mutual_information, reference_entropy): """ Calculate Relative classifier information (RCI). :param mutual_information: mutual information :type mutual_information: float :param reference_entropy: reference entropy :type reference_entropy: float :return: RCI as float """ ...
def reorder_columns(colnames): """ :param colnames: :return: """ reordered = [] idx = 5 for col in colnames: if col == 'chrom': reordered.append((0, col)) elif col == 'start': reordered.append((1, col)) elif col == 'end': reordered....
def concatenate_rounds(rounds_1, rounds_2): """ :param rounds_1: list - first rounds played. :param rounds_2: list - second set of rounds played. :return: list - all rounds played. """ res = list() res.extend(rounds_1) res.extend(rounds_2) return res
def _any_phrase_capitalised(lower_case_phrases, upper_case_phrases): """tests if any of the phrases in lower_case_phrases, when capitalised, are present in upper_case_phrases""" for lc_p in lower_case_phrases: for uc_p in upper_case_phrases: if lc_p.capitalize() == uc_p: return True retu...
def divide(numbers): """Function for dividing numbers. Parameters ---------- numbers : list List of numbers that the user inputs. Returns ------- result : int Integer that is the result of the numbers divided. """ result = numbers[0] for n in nu...
def fat(a=7, show=False): """ :param a: is the value the user wants to see the factorial of :param show: checks if it should show the formula behind the calculation :return: the factorial value of the number """ f = 1 for c in range(a, 0, -1): f *= c if show: if c...
def _parse_timespan(timespan): """Parse a time-span into number of seconds.""" if timespan in ('', 'NOT_IMPLEMENTED', None): return None return sum(60 ** x[0] * int(x[1]) for x in enumerate( reversed(timespan.split(':'))))
def dec2bin(number): """Convert a decimal number to binary""" return bin(number)[2:]
def calc_RC_via_bulk_time(capacitance, L, sigma): """ Characteristic time for induced double layer to form considering a capacitance. units: s Notes: Squires, 2010 - "characteristic time for induced double layer to form" Inputs: capacitance: F/m^2 C^2*s^2/kg/m^2/m^2 (...
def parse_eei_load(ldstr): """Helper function to parse load column from EEI format files.""" load = [ldstr[0 + i : 5 + i] for i in range(0, len(ldstr), 5)] try: load = [int(l) for l in load] except TypeError: print("Load variable cannot be mapped to integer value.") return load
def timedelta_to_seconds(td): """ Converts a timedelta to total seconds, including support for microseconds. Return value is (potentially truncated) integer. (This is built-in in Python >= 2.7, but we are still supporting Python 2.6 here.) :param td: The timedelta object :type td: :cla...
def parsing_args(argstr) : """ Returns a dictionary of argument-value pairs """ dic = {} if argstr : bits = argstr.split() for bit in bits : letter = bit[0] coord = float(bit[1:]) dic[letter] = coord return dic
def get_region(b): """Tries to get the bucket region from Location.LocationConstraint Special cases: LocationConstraint EU defaults to eu-west-1 LocationConstraint null defaults to us-east-1 Args: b (object): A bucket object Returns: string: an aws region string ""...
def emit_options(options): """Emit the analysis options from a dictionary to a string.""" return ",".join("%s=%s" % (k, v) for k, v in sorted(options.items()))
def convert_float(*args, **kwargs): """ Handle converter type "float" :param args: :param kwargs: :return: return schema dict """ schema = { 'type': 'number', 'format': 'float', } return schema
def change_flat_notation(s: str): """Change flat notation from `-` to `b`""" return s.replace("-", "b")
def temp_humidity(p_temp, h_temp): """ Use this function as :attr:`~SenseEnviron.temp_source` if you want to read temperature from the humidity sensor only. """ # pylint: disable=unused-argument return h_temp
def get_midpoint_uv_list(uv_list): """ Gets the mid point of the sorted 2d points in uv_list. """ u_mid = 0.5*(uv_list[0][0] + uv_list[-1][0]) v_mid = 0.5*(uv_list[0][1] + uv_list[-1][1]) return u_mid, v_mid
def validate_email(email): """ Assignment 2 updated """ allowed_chars = "abcdefghijklmnopqrstuvwxyz._-@0123456789" for i in email: if i not in allowed_chars: return False if email.count("@") == 1 and email.islower(): first, end = email.split("@") if end.count(...
def split_exclude_string(people): """ Function to split a given text of persons' name who wants to exclude with comma separated for each name e.g. ``Konrad, Titipat`` """ people = people.replace('Mentor: ', '').replace('Lab-mates: ', '').replace('\r\n', ',').replace(';', ',') people_list = peop...
def AISC_J24(PlateThck): """ From AISC WSD Table J2.4 Minimum Size of Fillet Welds """ # # To 1/4 inclusive if PlateThck < 6.35: # Minimum zise 1/8 _MinWeldSize = 3.20 # Over 3/4 elif PlateThck > 19.0: # Minimum zise 5/16 _MinWeldSize = 8.0 el...
def isValidLatitude(lat): """ Validates the latitude value. lat -- the latitude coordinate """ eps = 0.000001 if (-90 - eps < lat) and (lat < 90 + eps): return True return False
def get_epsilon(epsilon, n, i): """ n: total num of epoch i: current epoch num """ return epsilon / ( 1 + i/float(n))
def clip(x, vmin, vmax): """Clip a value x within bounds (vmin, vmax)""" if x < vmin: return vmin elif x > vmax: return vmax else: return x
def checkFormat_coordinate0(coordinate0): """Function that probe the coordinates are in a number list""" if type(coordinate0) == list: if len(coordinate0) == 3: for elem in coordinate0: try: float(elem) except Exception as e: ...
def sum_numbers(first_int, second_int): """Returns the sum of the two integers""" result = first_int + second_int return result
def similarity_tannimoto(left, right): """ :param left: Dictionary <key, value> :param right: Dictionary <key, value> :return: """ in_common = 0 total = 0 for left_fragment_key in left: for right_fragment_key in right: left_fragment = left[left_fragment_key] ...
def contains_any(haystack, needles): """Tests if any needle is a substring of haystack. Args: haystack: a string needles: list of strings Returns: True if any element of needles is a substring of haystack, False otherwise. """ for n in needles: if n in haystack: ret...
def fib(n): """ This function calculate fib number. Example: >>> fib(10) 55 >>> fib(-1) Traceback (most recent call last): ... ValueError """ if n < 0: raise ValueError('') return 1 if n<=2 else fib(n-1) + fib(n-2)
def subsumed(origx, words, wild='*', report=True): """See whether origx is subsumed by a wildcarded entry in words.""" if origx[-1] == wild: x = origx[:-2] + wild else: x = origx + wild while len(x) > 1: if x in words: if report: print(x, 'subsumes', o...
def NLR_analysis(NLR): """ Analysis NLR(Negative likelihood ratio) with interpretation table. :param NLR: negative likelihood ratio :type NLR: float :return: interpretation result as str """ try: if NLR == "None": return "None" if NLR < 0.1: return "G...
def timeToString(seconds_input): """Description. More... """ mmss = divmod(seconds_input, 60) if mmss[0] < 10: minutes = "0" + str(mmss[0]) else: minutes = str(mmss[0]) if mmss[1] < 10: seconds = "0" + str(mmss[1]) else: seconds = str(mmss[1]) if mm...
def make_python_name(name): """ Convert Transmission RPC name to python compatible name. """ return name.replace('-', '_')
def indent(amount: int, s: str) -> str: """Indents `s` with `amount` spaces.""" prefix = amount * " " return "\n".join(prefix + line for line in s.splitlines())
def tags(tag_coll): """Serializes the given tags to a JSON string. :param set[str] tag_coll: a set of tags :return: a dictionary suitable for JSON serialization :rtype: dict """ return {'tags': sorted(tag_coll)}
def get_unsigned_character(data, index): """Return one byte from data as an unsigned char. Args: data (list): raw data from sensor index (int): index entry from which to read data Returns: int: extracted unsigned 16-bit value """ result = data[index] & 0xFF return resul...
def intercept_file_option(argv): """ Find and replace value of command line option for input file in given argv list. Returns tuple: * file_arg: the filename (value of -f option) * new_argv: argv with the filename replaced with "-" (if found) """ file_arg = None # value of -f option...
def _tag_to_snake(name: str) -> str: """Conversts string to snake representation. 1. Converts the string to the lower case. 2. Converts all spaces to underscore. Parameters ---------- name: string The name to convert. Returns ------- str: The name converted to the snake rep...
def bytes_to_str(s, encoding='utf-8'): """Returns a str if a bytes object is given. >>> 'example' == bytes_to_str(b"example") True """ if isinstance(s, bytes): value = s.decode(encoding) else: value = s return value
def oconner(w, r): """ Optimistic for low reps. Between Lombardi and Brzycki for high reps. """ return w * (1 + r/40)
def order_toc_list(toc_list): """Given an unsorted list with errors and skips, return a nested one. [{'level': 1}, {'level': 2}] => [{'level': 1, 'children': [{'level': 2, 'children': []}]}] A wrong list is also converted: [{'level': 2}, {'level': 1}] => [{'level': 2, 'children': []}, {...
def solution(A, B): """ :param A: :return: """ len_str1 = len(A) len_str2 = len(B) if len_str1 != len_str2: return False # max number in ascii temp_storage = [0] * 256 for c in A: temp_storage[ord(c)] += 1 for c in B: temp_storage[ord(c)] -= 1 for...
def text_is_list(text) -> bool: """check if text is wrapped in square brackets""" text = text.strip() return text[0] == '[' and text[-1] == ']'
def RPL_REHASHING(sender, receipient, message): """ Reply Code 382 """ return "<" + sender + ">: " + message
def ftimeout(func, args=(), kwargs={}, timeout_duration=1, default=None): """http://stackoverflow.com/a/13821695""" import signal class TimeoutError(Exception): pass def handler(signum, frame): raise TimeoutError() # set the timeout handler signal.signal(signal.SIGALRM, handle...
def check_uniqueness_in_rows(board: list): """ Check buildings of unique height in each row. Return True if buildings in a row have unique length, False otherwise. >>> check_uniqueness_in_rows(['***21**', '412453*', '423145*', '*543215', '*35214*', '*41532*', '*2*1***']) True >>> check_uniquen...
def get_slice_length(nominal: float, total: int) -> int: """Calculate actual number of sentences to return Arguments: nominal {float} -- fraction of total/absolute number to return of {int} -- total number of sentences in body Raises: ValueError -- invalid length argument Retu...
def update_params(old_params, new_params, check=False): """Update old_params with new_params. If check==False, this merely adds and overwrites the content of old_params. If check==True, this only allows updating of parameters that are already present in old_params. Parameters ---------- o...
def merge_dicts(*dict_args): """Merge all Python dictionaries into one.""" dict_args = [] if dict_args is None else dict_args result = {} for d in dict_args: result.update(d) return result
def getColor(k) : """Homemade legend, returns a nice color for 0 < k < 10 :param k : indice """ colors = ["#862B59","#A10000","#0A6308","#123677","#ff8100","#F28686","#6adf4f","#58ccdd","#3a3536","#00ab7"] return colors[k]
def encode_all( header: bytes, stream: bytes, funcs: bytes, strings: bytes, lib_mode: bool ) -> bytes: """ Combine the various parts of the bytecode into a single byte string. Parameters ---------- header: bytes The bytecode's header data. stream: bytes The actual bytecode i...
def min_max(x, mn, mx): """ recales x such that it fits in the range: [-1, 1] """ return 2 * ((x - mn) / (mx - mn)) - 1
def parse_version(version: str): """ Returns parsed version from .ezdeps.json """ eq_type = '==' if version[0] == '^': eq_type = r'\>=' version = version[1:] return eq_type + version
def detokenize_smiles(tokenized_smiles: str) -> str: """ Detokenize a tokenized SMILES string (that contains spaces between the characters). Args: tokenized_smiles: tokenized SMILES, for instance 'C C ( C O ) = N >> C C ( C = O ) N' Returns: SMILES after detokenization, for instance 'C...
def validate_input_gui(user_input): """ This function validates the input of the user during 2nd menu :param user_input: :return: bool """ if user_input in ('0', '1', '2', '3', '4'): return True return False
def my_add(argument1, argument2): """ adds two input arguments. Parameters ---------- argument1 : int, float, str input argument 1 argument2 : int, float, str input arguement 2 Returns ------- results : int, float or str the two added input argum...
def D_theo(D0, T, Tc, mu): """ Calculates the theoretical value for spinwave stiffness D as a function of temperature Parameters ---------- D0 : float spin-wave stiffness at 0 K meV/angstroem^2 T : float temperature of the system in K (needs to be <= Tc) Tc : ...
def remove_duplicates(lst): """ Return input list without duplicates. """ seen = [] out_lst = [] for elem in lst: if elem not in seen: out_lst.append(elem) seen.append(elem) return out_lst
def is_postorder(nums): """ :param nums: :return: """ def recur(i,j) : if i >= j : return True p = i while nums[p] < nums[j] : p += 1 m = p while nums[p] > nums[j] : p += 1 return p ==j and recur(i,m-1) and recur(m,...
def PosTM2Topo(posTM, seqLength, NtermState):#{{{ """ Get the membrane protein topology by given TM helix segment lists and location of N-terminus posTM : a list of tuples, e.g. [(10,30),(35,44), ...] defining TM segments, index start and end index is not included seqLength : le...
def average(num1: float, num2: float) -> float: """Return the average of num1 and num2. >>> average(10,20) 15.0 >>> average(2.5, 3.0) 2.75 """ return (num1 + num2) / 2
def handle_empty_item(item): """Handles faulty return values from SSH calls""" try: return float(item) except: return float(999999)
def noid(seq): """ Removes values that are not relevant for the test comparisons """ for d in seq: d.pop('id', None) d.pop('action_id', None) return seq
def get_all(futures, timeout=None): """ Collect all values encapsulated in the list of futures. If ``timeout`` is not :class:`None`, the method will wait for a reply for ``timeout`` seconds, and then raise :exc:`pykka.Timeout`. :param futures: futures for the results to collect :type futures: ...
def pi_list_to_str(pi_list): """ Parameters ---------- pi_list list of pi number expressions Returns A string representation ------- """ out_set = "" if len(pi_list) > 0: for i in range(len(pi_list)): if pi_list[i] is not None: out_...
def valid_url(url): """ Validate a URL and make sure that it has the correct URL syntax. Args: url (str): URL string to be evaluated. Returns: True if the URL is valid. False if it is invalid. """ if "http://" not in url and "https://" not in url: return False retu...
def tenures_burnt(qs, arg=None): """ Usage:: {{ qs|filter_tenures_burnt:"string" }} """ qs = qs.filter(tenure__name=arg) if qs else None return round(qs[0].area, 2) if qs else 0
def lorentzianAmp(x, x0, gamma): """lorentzian peak""" return 1 / (1 + ((x - x0) / gamma)**2)
def lerp(global_step, start_step, end_step, start_val, end_val): """Utility function to linearly interpolate two values.""" interp = (global_step - start_step) / (end_step - start_step) interp = max(0.0, min(1.0, interp)) return start_val * (1.0 - interp) + end_val * interp
def _args_to_recodings(*args, _force_index=False, **kwargs): """Convert arguments to replaceable""" values = {} for i, arg in enumerate(args): if isinstance(arg, dict): values.update(arg) else: values[i] = arg values.update(kwargs) if _force_index: fo...
def search_entities(raw_text_string, search): """Searches for known entities in a string. Helper function for construct_entity_conet(). Iterates over a list of entities and looks to see if they are present in a given text string. If they are, then it will append the entity to a list for each te...
def preceding(iterable, item): """The item which comes in the series immediately before the specified item. Args: iterable: The iterable series in which to search for item. item: The item to search for in iterable. Returns: The previous item. Raises: ValueError: If ite...
def sort_ipv4(ips): """ Sort a list of ipv4 addresses in ascending order """ for i in range(len(ips)): ips[i] = "%3s.%3s.%3s.%3s" % tuple(ips[i].split(".")) ips.sort() for i in range(len(ips)): ips[i] = ips[i].replace(" ", "") return ips
def check_tags_contain(actual, expected): """Check if a set of AWS resource tags is contained in another Every tag key in `expected` must be present in `actual`, and have the same value. Extra keys in `actual` but not in `expected` are ignored. Args: actual (list): Set of tags to be verified, ...
def _cachefile(dataset, year, day): """Returns the cache file name for a given day of data.""" return f'cache/{dataset}.{year:04}.{day:02}.html'
def get_fuel_required(module_mass: float) -> float: """Get the fuel required for a module. Args: module_mass: module mass Returns: fueld required to take off """ return int(module_mass / 3.0) - 2.0
def parseTime(t): """ Parses a time value, recognising suffices like 'm' for minutes, 's' for seconds, 'h' for hours, 'd' for days, 'w' for weeks, 'M' for months. >>> endings = {'s':1, 'm':60, 'h':60*60, 'd':60*60*24, 'w':60*60*24*7, 'M':60*60*24*30} >>> not False in [endings[i]*3 == parseT...
def combine_groups(groups): """Combine :obj:`list` of groups to a single :obj:`str`. Parameters ---------- groups : list of str List of group names. Returns ------- str Combined :obj:`str`. """ new_str = ', '.join(groups) return new_str
def is_iterable(obj): """Portable way to check that an object is iterable""" try: iter(obj) return True except TypeError: return False
def escape(html): """ Returns the given HTML with ampersands, quotes and angle brackets encoded. """ return html.replace('&', '&amp;')\ .replace('<', '&lt;')\ .replace('>', '&gt;')\ .replace('"', '&quot;')\ .replace("'", '&#39;')
def phi(n: int) -> int: """Euler function Parameters: n (int): Number Returns: int: Result """ res, i = n, 2 while i * i <= n: if n % i == 0: while n % i == 0: n //= i res -= res // i i += 1 if n > 1: res -= res /...
def _cal_mapped_len(mapped_intervals, chr_name, win_start, win_end): """ Description: Helper function for calculating length of mapped region in a given window. Arguments: mapped_intervals dict: Dictionary of tuples containing mapped regions across the genome. chr_name str: Name of ...
def normalize(numbers): """ normalize :param numbers: :return: """ total = sum(numbers) result = [] for value in numbers: percent = 100 * value / total result.append(percent) return result
def plural(n, s, pl=None): """ Returns a string like '23 fields' or '1 field' where the number is n, the stem is s and the plural is either stem + 's' or stem + pl (if provided). """ if pl is None: pl = 's' if n == 1: return '%s %s' % (n, s) else: return '%s %s%s'...
def guideline_amounts_difference_c(responses, derived): """ Return the difference between the guideline amounts to be paid by claimant 1 and claimant 2 for Factsheet C """ try: amount_1 = float(responses.get('your_child_support_paid_c', 0)) except ValueError: amount_1 = 0 t...
def tokenize(smiles, tokens): """ Takes a SMILES string and returns a list of tokens. Atoms with 2 characters are treated as one token. The logic references this code piece: https://github.com/topazape/LSTM_Chem/blob/master/lstm_chem/utils/smiles_tokenizer2.py """ n = len(smiles) tokeni...
def truncate(f, n): """ Truncates/pads a float f to n decimal places without rounding """ s = '{}'.format(f) if 'e' in s or 'E' in s: return '{0:.{1}f}'.format(f, n) i, p, d = s.partition('.') return '.'.join([i, (d + '0' * n)[:n]])
def nspath_eval(xpath, nsmap): """Return an etree friendly xpath""" out = [] for chunks in xpath.split('/'): namespace, element = chunks.split(':') out.append('{%s}%s' % (nsmap[namespace], element)) return '/'.join(out)
def findAnEven(L): """assumes L is a list of integers returns the first even number in L Raises ValueError if L does ont contain an even number""" for k in L: if k % 2 == 0 and k>0: return k break raise ValueError('no even numbers provided')
def times_within(time1, time2, gap): """Checks whether the gap between two times is less than gap""" if time1 is None or time2 is None: return None return abs(time1 - time2) < gap
def minimum_absolute_difference(arr): """https://www.hackerrank.com/challenges/minimum-absolute-difference-in-an-array""" sorted_array = sorted(arr) return min(abs(x - y) for x, y in zip(sorted_array, sorted_array[1:]))
def get_errors(cm, i): """Get the sum of all errornous classified samples of class i.""" n = len(cm) return sum([cm[i][j] for j in range(n)])
def solve(grades): """ Return grades rounded up to nearest 5 if above 38, otherwise, do not round the score. """ rounded_grades = [] for grade in grades: if grade >= 38: rounded = ((grade + 5) / 5) * 5 if rounded - grade < 3: grade = rounded ...
def split_call(lines, open_paren_line=0): """Returns a 2-tuple where the first element is the list of lines from the first open paren in lines to the matching closed paren. The second element is all remaining lines in a list.""" num_open = 0 num_closed = 0 for i, line in enumerate(lines): ...
def utc_time(source): """Convert source bytes to UTC time as (H, M, S) triple HHMMSS.000 >>> utc_time(b'123456.000') (12, 34, 56.0) """ if source: return int(source[:2]), int(source[2:4]), float(source[4:]) return None, None, None
def lempel_ziv_complexityLOCAL(binary_sequence): """ Manual implementation of the Lempel-Ziv complexity. It is defined as the number of different substrings encountered as the stream is viewed from begining to the end. As an example: >>> s = '1001111011000010' >>> lempel_ziv_complexity(s) # 1 / 0 /...
def c2f(celsius): """ Covert Celsius to Fahrenheit :param celsius: [float] Degrees Celsius :return: [float] Degrees Fahrenheit """ return (9 / 5 * celsius) + 32
def query_for_id(sql, keys, trg_db): """Execute the provided sql string on the target database. Issue a meaningful error message contianing keys_as_string if there is a problem. Arguments: - `sql`:a sql statement that is intended t oretrieve the id of a parent record. The sql string should re...