content
stringlengths
42
6.51k
def format_list(items, seporate="", replaces=None): """ :param items: :param seporate: :param replaces: :return: """ if not replaces: replaces = [] replaces.extend([" ", "\r", "\n", "\t"]) list_str = seporate.join(items) if replaces and isinstance(replaces, list): for strs in replaces: list_str = list_str.replace(strs, "") return list_str.strip()
def orient(startP, endP, pt): """ Find orientation of a point w.r.t. a line segment :param startP: start point of segment [x,y] :param endP: end point of segment [x,y] :param pt: point [x,y] :return: -1, 0, 1 """ orientation= (((startP[0]-pt[0])*(endP[1]-pt[1]))-((startP[1]-pt[1])*(endP[0]-pt[0]))) if orientation<0: return -1 elif orientation>0: return 1 else: return 0
def selective_stringify_nums(nums): """Selectively stringify nums: Given a list of numbers, write a list comprehension that produces a list of strings of each number that is divisible by 5. >>> selective_stringify_nums([25, 91, 22, -7, -20]) ['25', '-20'] """ lst = [str(a) for a in nums if a%5 ==0] return lst pass
def get_object_path(obj): """Return path to object.""" return obj.__module__ + "." + obj.__name__
def merge(i, j): """Merge two word counts.""" return {k:(i.get(k,set()) | j.get(k,set())) for k in i.keys() | j.keys()}
def reconstruct_path(goal, branch, waypoint_fn): """ Reconstruct a path from the goal state and branch information """ current_node = goal path = [current_node] while current_node is not None: previous_node = branch[waypoint_fn(current_node)] path.append(previous_node) current_node = previous_node path.pop() path.reverse() return path
def swap_to_title_case(word): """ Converts a word from any case to title case. E.g. 'mumbai' will become 'Mumbai' :param word: A string which is will converted to Title case. :return: A string in Title case """ return word.lower()[0].upper() + word.lower()[1:]
def jaccard_sim(u, v): """ Computes the Jaccard similarity between sets u and v. sim = intersection(u, v) / union(u, v) params: u, v: sets to compare returns: float between 0 and 1, where 1 represents perfect similarity and 0 represents no similarity """ intersection = len(u.intersection(v)) union = len(u.union(v)) zero = 1e-10 # Add small value to denominator to avoid divide by zero sim = intersection / (union + zero) return sim
def get_cleaned_attrs_from_object( object_in, ignore_callable=True, ignore_types=None, ignore_prefixes="__" ): """ Return all the attributes of an object that pass criteria :param object_in: Any python object the attributes with the "sub_object" they belong to. Default: False :param ignore_callable: Don't return attributes than can be called. Default: True :param ignore_types: Don't return attributes of this type (or tuple of types). Default: None. :param ignore_prefixes: Don't return attributes starting with prefixes (as strings) in this list. Default: "__" :return: list of attributes meeting criteria """ attributes = [attr for attr in dir(object_in)] if ignore_callable: attributes = [ attr for attr in attributes if not callable(getattr(object_in, attr)) ] if ignore_types is not None: attributes = [ attr for attr in attributes if not isinstance(getattr(object_in, attr), ignore_types) ] if ignore_prefixes is not None: for prefix in ignore_prefixes: attributes = [ attr for attr in attributes if not attr.startswith(prefix) ] return attributes
def is_blank(_str): """ Convenient function to check if a str is blank is_blank(None) = True is_blank("") = True is_blank(" ") = True is_blank("1") = False is_blank("abc") = False is_blank(1) # Raise AttributeError: 'int' object has no attribute 'strip' """ return not (_str and _str.strip())
def remove_ext_filename(filename): """ Remove OTB extended filenames (keep only the part before the "?") """ if "?" in filename: return filename[:filename.rfind("?")] return filename
def get_java(spec='general'): """ contains skills required for java developers :return: skills and advanced_skills """ # user can ask for specific info or general info # general skills = ['Scala', 'Kotlin', 'Groovy', 'JVM Internals', 'SQL', 'MySQL', 'PostgreSQL', 'JSP Servlets' , 'REST', 'SOAP', 'XML', 'JSON', 'OOP', 'Multithreading', 'Serialization'] advanced_skills = ['Blockchain', 'AWS', 'Big Data', 'Spring boot', 'Microservices'] # specific info ================================================================================== java_build_tools = ['Maven', 'Gradle'] web_tech = ['HTML', 'CSS', 'Javascript', 'JQuery'] web_frameworks = ['SpringMVC', 'Play', 'Java Web Services'] app_containers = ['JBoss', 'Jetty', 'WebSphere', 'WebLogic'] testing_tools = ['JUnit', 'TestNG', 'Selenium'] big_data = ['DBMS', 'Hadoop', 'SQL', 'JDBC'] EE_components = ['Servlets', 'Java Beans', 'Java Server Pages'] code_version_control = ['GitHub'] # =============================================================================================== name_var_dict = [ {'javabuildtools': java_build_tools}, {'webtechnologies': web_tech}, {'webframeworks': web_frameworks}, {'applicationcontainers': app_containers}, {'javatestingtools': testing_tools}, {'bigdata': big_data}, {'javaeecomponents': EE_components}, {'codeversioncontrol': code_version_control} ] if spec is None: return skills # if nothing else is passed if spec.lower() == 'general': return skills, advanced_skills else: for key in name_var_dict: temp = spec.lower().strip().replace(" ", "") if temp in list(key.keys())[0]: idx = name_var_dict.index(key) return name_var_dict[idx][list(key.keys())[0]]
def get_lcp(word1, word2): """ Gets the LCP, Longest Common Prefix, between the two given words. Parameters ---------- word1: str The first word to consider when getting LCP. word2: str The second word to considerwhen getting LCP. Returns ------- str: The longest common prefix between the given two words. Raises ------ AssertionError: If either of the two given words isn't a string. Example ------- >>> get_lcp("apple", "append") app >>> get_lcp("apple", "abnormal") a >>> get_lcp("apple", "xapple") """ assert type(word1) == str and type(word2) == str for i in range(min(len(word1), len(word2))): if word1[i] != word2[i]: return word1[:i] return word1 if len(word1) < len(word2) else word2
def delete_zero_amount_exchanges(data, drop_types=None): """Drop all zero value exchanges from a list of datasets. ``drop_types`` is an optional list of strings, giving the type of exchanges to drop; default is to drop all types. Returns the modified data.""" if drop_types: dont_delete = lambda x: x["type"] not in drop_types or x["amount"] else: dont_delete = lambda x: x["amount"] for ds in data: ds["exchanges"] = list(filter(dont_delete, ds["exchanges"])) return data
def abrv_it(x): """Add state abbreviation""" abr = x.split(",")[1].lstrip() if len(abr) == 2: return abr else: return "None"
def join_rows(rows, sep='\n'): """Given a list of rows (a list of lists) this function returns a flattened list where each the individual columns of all rows are joined together using the line separator. """ output = [] for row in rows: # grow output array, if necessary if len(output) <= len(row): for i in range(len(row) - len(output)): output.extend([[]]) for i, field in enumerate(row): field_text = field.strip() if field_text: output[i].append(field_text) return list(map(lambda lines: sep.join(lines), output))
def is_true(string) -> bool: """Determines whether a string represents True. As the name suggests, any input which is not explicitly evaluated to True will cause this method to return False. Args: string: the string to evaluate """ assert type(string) == str return string in ['True', 'true', '1']
def binary_search(input_array, value): """Your code goes here.""" # mid = len(input_array)//2 # if input_array[mid] < value: # return binary_search(input_array[mid+1:],value) # elif input_array[mid] > value: # return binary_search(input_array[:mid],value) # elif input_array[mid] == value: # # print('rfr', mid) # return input_array.index(value) # else: # return -1 low = 0 high = len(input_array) while (low <= high): mid = (low+high)//2 if input_array[mid] < value: low = mid+1 # continue elif input_array[mid] > value: # mid = (len(input_array[:mid]))//2 high = mid-1 # continue elif input_array[mid] == value: return input_array.index(value) # if mid < 0 or mid > len(input_array): # return -1 # return input_array.index(value) return -1
def is_fully_implemented(cls): """ Returns True if a ``cls`` is a fully implemented derivate of an ABC. """ return not getattr(cls, '__abstractmethods__', False)
def count_words(text): """ This function counts some words and return integer which is the length of wordsg """ if not isinstance(text, str): raise TypeError("only accepts strings") special_characters = ['-', '+', '\n'] for character in special_characters: text = text.replace(character, " ") words = text.split() return len(words)
def merge_dict(data, *override): """ Merges any number of dictionaries together, and returns a single dictionary Usage:: >>> util.merge_dict({"foo": "bar"}, {1: 2}, {"Doc": "SDK"}) {1: 2, 'foo': 'bar', 'Doc': 'SDK'} """ result = {} for current_dict in (data,) + override: result.update(current_dict) return result
def get_extrap_col_and_ht(height, num, primary_height, sensor="Ane", var="WS"): """Determine name of column and height to use for extrapolation purposes Parameters ---------- height : int or float comparison height num : int or str number/label of comparison height primary_height : int or float primary comparison height sensor : str type of sensor ("Ane", "RSD") var : str variable to be extracted ("WS", "SD", "TI") Returns ------- string column name of data to be extracted from inputdata float height to be extracted for extrapolation """ col_name = sensor + "_" + str(var) + "_Ht" + str(num) if "primary" in col_name: if sensor == "Ane": col_name = "Ref_" + str(var) elif sensor == "RSD": col_name = "RSD_" + str(var) height = float(primary_height) else: height = float(height) return col_name, height
def _composite_maxderiv(maxA,maxB): """ Determine the maxderiv value of a composite DFun A(B(x)) Parameters ---------- maxA, maxB : int or None maxderiv parameter of composite Dfun Returns ------- int or None maxderiv of composite function """ if maxA is None and maxB is None: maxderiv = None elif maxA is None: maxderiv = maxB elif maxB is None: maxderiv = maxA else: maxderiv = min(maxA,maxB) return maxderiv
def table_row(text_list): """Make a CSV row from a list.""" return ','.join(f'"{text}"' for text in text_list)
def clean(data_dict): """ Removes all unmarked reviews from the dataset. Keyword arguments: data_dict -- the dictionary dataset. Returns: Cleaned dataset. """ unassessed_entries = [key for key, value in data_dict.items() if value[1] == -1] for key in unassessed_entries: del data_dict[key] return data_dict
def round_nicely(number): """Round a number based on its size (so it looks nice).""" if number < 10: return round(number, 2) if number < 100: return round(number, 1) return round(number)
def transpose(M): """[summary] Args: M ([type]): [description] Returns: [type]: [description] """ return [[row[i] for row in M] for i in range(len(M[0]))]
def get_corners(shape): """ This is a recursive function to calculate the corner indices of an array of the specified shape. :param shape: length of the dimensions of the array :type shape: tuple of ints, one for each dimension """ if not type(shape) == tuple: raise TypeError('get_corners argument is non-tuple') if len(shape) == 1: corners = [(0,), (shape[0]-1,)] else: shape_less1 = shape[1:len(shape)] corners_less1 = get_corners(shape_less1) corners = [] for corner in corners_less1: newcorner = (0,) + corner corners.append(newcorner) newcorner = (shape[0]-1,) + corner corners.append(newcorner) return corners
def has_duplicates(t: list) -> bool: """Returns True if any element appears more than once in a sequence.""" s = list(t) s.sort() for i in range(1, len(s)): if s[i - 1] == s[i]: return True return False
def hms2hh(hms): """convert hours, minutes seconds to decimal hours""" if type(hms) is str: if hms.find(':')>0: hms = hms.split(':') else: hms = hms.split(' ') hms = [float(h) for h in hms] if len(hms)==2: hms.append(0.0) return (hms[0] + hms[1]/60. + hms[2]/3600.)
def get_loc_from_dict(dct, loc): """ Take a string loc and return a sub-dict corresponding to that loc. i.e. "foo.bar" would return dict['foo']['bar'] empty string returns top-level dict. """ if loc == "": return dict else: locs = loc.split(".") d = dct for ll in locs: try: d = d[ll] except KeyError: raise KeyError(f"loc {loc} does not exist in dict {dct}") return d
def querystr(d): """Create a query string from a dict""" if d: return '?' + '&'.join( ['%s=%s' % (name, val) for name, val in d.items()]) else: return ''
def _zone_to_region(zone): """Convert a zone (like us-west1-b) to the corresponding region (like us-west1).""" # See https://cloud.google.com/compute/docs/regions-zones/#identifying_a_region_or_zone # noqa return '-'.join(zone.split('-')[:-1])
def is_numeric(s): """ It's a useful function for checking if a data is a numeric. This function could identify any kinds of numeric: e.g. '0.1', '10', '-2.', 2.5, etc Parameters ---------- s : int, float or string. The input could be any kind of single value except the scalable type of python like 'list()', 'dict()', 'set()' Returns ------- A boolean. Ture if `s` is numeric else False Examples -------- >>> from geneview.utils import is_numeric >>> is_numeric('a') False >>> is_numeric(1) True >>> is_numeric(3.14) True Notes ----- http://stackoverflow.com/questions/354038/how-do-i-check-if-a-string-is-a-number-float-in-python """ try: float(s) return True except ValueError: return False
def merge_none(a, b): """ Compare two sequences elementwise and merge them discarding None entries. Raises ValueError exception if the two sequances do not have the same length or if they have different non-None elements. Parameters ---------- a, b : sequences The sequences to be compared. Example ------- >>> merge_none([1,None,3],[None,2,3]) [1, 2, 3] """ if a is b is None: return None if len(a) != len(b): raise ValueError('The input sequences do not have the same length.') if any(p != q for p, q in zip(a, b) if None not in (p, q)): raise ValueError('The input sequences have incompatible values.') return tuple(p if p is not None else q for p, q in zip(a, b))
def quote(s, quote=None): """Convert a string object to a quoted string literal. This is similar to repr() but will return a "raw" string (r'...' or r"...") when the string contains backslashes, instead of doubling all backslashes. The resulting string does *not* always evaluate to the same string as the original; however it will do just the right thing when passed into re.compile(). The optional second argument forces the string quote; it must be a single character which is a valid Python string quote. """ if quote is None: q = "'" altq = "'" if q in s and altq not in s: q = altq else: assert quote in ('"', "'") q = quote res = q for c in s: if c == q: c = '\\' + c elif c < ' ' or c > '~': c = "\\%03o" % ord(c) res = res + c res = res + q if '\\' in res: res = 'r' + res return res
def omega_red(s) -> str: """Changes string color output to red""" s = '\033[1;91m' + s + '\033[0m' return s
def _extras_msg(extras): """ Create an error message for extra items or properties. """ if len(extras) == 1: verb = "was" else: verb = "were" return ", ".join(repr(extra) for extra in extras), verb
def random_state_data(n, random_state=None): """Return a list of arrays that can initialize ``np.random.RandomState``. Parameters ---------- n : int Number of tuples to return. random_state : int or np.random.RandomState, optional If an int, is used to seed a new ``RandomState``. """ import numpy as np if not isinstance(random_state, np.random.RandomState): random_state = np.random.RandomState(random_state) maxuint32 = np.iinfo(np.uint32).max return [(random_state.rand(624) * maxuint32).astype('uint32') for i in range(n)]
def dataset_map_from_iterable(iterable): """ Turn a list of datasets into a map from their IDs to the datasets. """ return {dataset.dataset_id: dataset for dataset in iterable}
def insert_external(expr): """ Replaces variables prefixed with @ in the expression with the value of the variable from the global namespace Example: x=['4AB02', '4AB04', '4AB06'] expr = '@x before 4AB02' insert_external(expr) """ externals = [word.strip('@') for word in expr.split() if word.startswith('@')] for external in externals: tmp = globals()[external] expr = expr.replace(f'@{external} ', f'{tmp} ') return expr
def _get_controller_of(pod): """Get a pod's controller's reference. This uses the pod's metadata, so there is no guarantee that the controller object reference returned actually corresponds to a controller object in the Kubernetes API. Args: - pod: kubernetes pod object Returns: the reference to a controller object """ if pod["metadata"].get("ownerReferences"): for owner_ref in pod["metadata"]["ownerReferences"]: if owner_ref.get("controller"): return owner_ref return None
def cast_to_list(x): """ Make a list out of the input if the input isn't a list. """ if type(x) is list: return x else: return [x]
def getThumbnailFrameForClip(clip): """ Returns the in frame for the clip, or 0 if none was set. """ frame = 0 if not clip: return frame # This raises if its not been set try: frame = clip.posterFrame() except RuntimeError: pass return frame
def GetCells(line): """Get cells.""" # [A, B, C, ..] from "A","B ",C,.. return [column.strip('"').strip() for column in line.strip().split(',')]
def compare_JSON(json1, json2, raise_error=False): """! @brief Will compare two JSON strings, and return False if they differ. An extra argument can be used to force the function to raise an error with the line the difference was observed. """ for linenumber, (line1, line2) in enumerate(zip(json1.splitlines(), json2.splitlines())): if (line1 != line2): if raise_error: raise Exception("JSON differs at line: " + str(linenumber)) return False return True
def getOverlap(a, b): """ Return overlap between two intervals >>> getOverlap( [0,2], [0,1]) 1 """ return max(0, min(a[1], b[1]) - max(a[0], b[0]))
def bubble_sort(items): """Sorts a list of items. Uses inserstion sort to sort the list items. Args: items: A list of items. Returns: The sorted list of items. """ for i in range(1, len(items)): for j in range(1, len(items)): if items[j] < items[j - 1]: items[j], items[j - 1] = items[j - 1], items[j] return items
def isGarbageChar(byte): """ Indicates whether this char is likely to be garbage or english """ if byte == 32: return False #space if byte >= 65 and byte <= 90: return False #uppercase if byte >= 97 and byte <= 122: return False #lowercase return True
def get_mapping(combinable_list): """Determine the mapping from acceptance_id to the register id that can be used to index into an array. """ result = {} array_index = 0 while len(combinable_list) != 0: # Allways, try to combine the largest combinable set first. k = max(enumerate(combinable_list), key=lambda x: len(x[1]))[0] combination = combinable_list.pop(k) for acceptance_id in (x for x in combination if x not in result): result[acceptance_id] = array_index # Since: -- The combinations only contain post_context_id's that have not been # mentioned before, and # -- all empty combinations are deleted from the combinable_list, # Thus: It is safe to assume that new entries were made for the current # array index. Thus, a new array index is required for the next turn. array_index += 1 # Delete combinations that have become empty combinable_list = [ x for x in combinable_list if len(x) ] return result
def _lookup_format(var): """ Looks up relevant format in fits. Parameters ---------- var : object An object to look up in the table Returns ------- lookup : str The str describing the type of ``var`` """ lookup = {"<type 'int'>": "J", "<type 'float'>": "E", "<type 'numpy.int64'>": "K", "<type 'numpy.float64'>": "D", "<type 'numpy.float128'>": "D", "<type 'str'>": "30A", "<type 'bool'": "L"} form = type(var) try: return lookup[str(form)] except KeyError: # If an entry is not contained in lookup dictionary return "D"
def time_in_HMS(begin, finish): """ Calculate time difference between begin and finish. Args: begin (float): time at start finish (float): time at finish Returns: tuple: differences between begin and finish: raw difference, hours, minutes and seconds """ raw = finish - begin hours = round(raw // 3600) minutes = round((raw % 3600) // 60) seconds = round((raw % 3600) % 60) return raw, hours, minutes, seconds
def get_detailed_str_dict (configuration: dict) -> dict: """ Returns the dictionary of all `str`-like attributes. Keys are names, values are subdictionaries containing corresponding group and group_str names. Parameters: configuration (dict) : configuration from `trex.json` Returns: str_dict (dict) : dictionary of string attributes """ str_dict = {} for k1,v1 in configuration.items(): for k2,v2 in v1.items(): if len(v2[1]) == 0: tmp_str = f'{k1}_{k2}' if 'str' in v2[0]: tmp_dict = {} tmp_dict['group'] = k1 tmp_dict['group_str'] = tmp_str str_dict[tmp_str] = tmp_dict return str_dict
def _srange(begin, end): """ Return a set based on range """ return set(range(begin, end))
def selection_sort(array): """ Sort array in ascending order by selection sort The selection sort algorithm sorts an array by repeatedly finding the minimum element (considering ascending order) from unsorted part and putting it at the beginning. - Best-case time performance: O(n^2) - Worst-case time performance: O(n^2) - Average time performance: O(n^2) - Worst-case space complexity: O(1) :param array: given unsorted array :type array: list :return: sorted array in ascending order :rtype: list """ # traverse through all array elements for i in range(len(array)): min_idx = i # find the minimum element in remaining # unsorted array for j in range(i + 1, len(array)): if array[j] < array[min_idx]: min_idx = j # swap the found minimum element with # the first element array[i], array[min_idx] = array[min_idx], array[i] return array
def q2mat(q): """ Generate a left rotation matrix from a normalized quaternion Parameters q: The normalized quaternion (list) Returns u: The rotation matrix (2-dimensional list) """ u = [] for i in range(3): u.append([]) for j in range(3): u[i].append(0.0) u[0][0] = q[0] * q[0] + q[1] * q[1] - q[2] * q[2] - q[3] * q[3] u[0][1] = 2.0 * (q[1] * q[2] - q[0] * q[3]) u[0][2] = 2.0 * (q[1] * q[3] + q[0] * q[2]) u[1][0] = 2.0 * (q[2] * q[1] + q[0] * q[3]) u[1][1] = q[0] * q[0] - q[1] * q[1] + q[2] * q[2] - q[3] * q[3] u[1][2] = 2.0 * (q[2] * q[3] - q[0] * q[1]) u[2][0] = 2.0 * (q[3] * q[1] - q[0] * q[2]) u[2][1] = 2.0 * (q[3] * q[2] + q[0] * q[1]) u[2][2] = q[0] * q[0] - q[1] * q[1] - q[2] * q[2] + q[3] * q[3] return u
def extended_euclidean(a, b, test=False): """ Extended Euclidean algorithm Given a, b, solve: ax + by = gcd(a, b) Returns x, y, gcd(a, b) Other form, for a prime b: ax mod b = gcd(a, b) = 1 >>> extended_euclidean(3, 5, test=True) 3 * 2 + 5 * -1 = 1 True >>> extended_euclidean(240, 46, test=True) 240 * -9 + 46 * 47 = 2 True Derived from https://atcoder.jp/contests/acl1/submissions/16914912 """ init_a = a init_b = b s, u, v, w = 1, 0, 0, 1 while b: q, r = divmod(a, b) a, b = b, r s, u, v, w = v, w, s - q * v, u - q * w if test: print(f"{init_a} * {s} + {init_b} * {u} = {a}", init_a * s + init_b * u == a) else: return s, u, a
def GetEntryForDevice(fstab, device): """ Returns: The first entry in fstab whose device is the given value. """ if not fstab: return None for mount_point in fstab: if fstab[mount_point].device == device: return fstab[mount_point] return None
def reverse_words(s): """returns string that is just like s except that the word order is reversed.""" return ' '.join(reversed(s.split()))
def get_state(cell_id): """ Gets the state from a state identification number. :param cell_id: Natural number identifying the state :return: Two dimensional array containing the state """ state = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] binary = '{0:09b}'.format(cell_id) index = 0 for char in binary: state[index // 4][index % 4] = int(char) index += 1 return state
def multi(a, b, c=8): """ performs arithmetic operations this is the docstring of multi() """ return a * b - c
def get_lang(tweet): """ Get language label from a tweet object :param tweet: JSON object :return: (new_lang, None) for RTs/Tweets and (new_lang, ref_lang) for RT w/ comments """ try: new_lang = tweet['twitter_lang'] except KeyError as e: try: new_lang = tweet['lang'] except KeyError as e: new_lang = 'unknown' try: # old retweets ref_lang = tweet['retweeted_status']['quoted_status']['twitter_lang'] except KeyError: try: # GNIP format ref_lang = tweet['object']['twitter_quoted_status']['lang'] except KeyError: ref_lang = 'unknown' return new_lang, ref_lang
def to_list(val): """ Converts a string argument to a list by splitting it by spaces. Returns the object if not a string:: from waflib.Utils import to_list lst = to_list('a b c d') :param val: list of string or space-separated string :rtype: list :return: Argument converted to list """ if isinstance(val, str): return val.split() else: return val
def charge_value(input): """Returns the numerical value of the charge from the string.""" charges = { 0: 0, "0": 0, "+" or "+1" or "1+": 1, "2+" or "+2": 2, "3+" or "+3": 3, "4+" or "+4": 4, "5+" or "+5": 5, "-" or "-1" or "1-": -1, "2-" or "-2": -2, "3-" or "-3": -3, "4-" or "-4": -4, "5-" or "-5": -5 } return charges[input]
def interp(start, end, alpha): """ Interpolate lineraly between `start` and `end`. """ return (end - start) * alpha + start
def check_type( obj, types, allow_iterable=False, allow_none=False, allow_dict=False ) -> bool: """Check if the obj is of any of the given types This includes recursive search for nested lists / dicts and fails if any of the values is not in types Parameters ---------- obj: object to check types: single class or tuple of classes to check against allow_iterable: check list entries if a list is provided allow_none: accept None even if not in types. allow_dict: allow for {key: types} """ if isinstance(obj, (list, tuple, set)) and allow_iterable: for value in obj: if check_type(value, types, allow_iterable, allow_none, allow_dict): continue return False elif isinstance(obj, dict) and allow_dict: for value in obj.values(): if check_type(value, types, allow_iterable, allow_none, allow_dict): continue return False else: if allow_none and obj is None: return True if not isinstance(obj, types): return False return True
def _after(date): """ Returns a query item matching messages sent after a given date. Args: date (str): The date messages must be sent after. Returns: The query string. """ return f"after:{date}"
def incrementalAverageUpdate(avg, sample, sample_number): """ :param avg: the old average :param sample: the new sample to update the average with :param sample_number: the current sample number (#samples observed so far+1) Updates an average incrementally. """ return avg + (sample - avg) / (sample_number * 1.)
def name_to_number(name): """ Helper function that converts a name to a number between 0 and 4 """ num = -1 if name == "rock": num = 0 elif name == "Spock": num = 1 elif name == "paper": num = 2 elif name == "lizard": num = 3 elif name == "scissors": num = 4 return num
def extract_system_name(name): """ look for handy system name in filename. - used to label top level memory map class """ check = ["_","-","."] value = len(name) for char in check: pos = name.find(char) if pos > -1 and pos < value: value = pos return name[:value]
def cross_partial_overlap_2(dep_t, dep_h): """Checks whether the head in the text triplet matches the dependent in the hypthesis triplet.""" return dep_h[0] in dep_t[2]
def without(s, w): """Remove all in str w from string s""" l = list(s) for i in w: l.remove(i) return "".join(l)
def _buffer_box(bbox, interval): """Helper function to buffer a bounding box to the nearest multiple of interval args: bbox (list[float]): list of float values specifying coordinates, expects order to be [W,E,S,N] interval (float): float specifying multiple at which to buffer coordianates to returns: extent (tuple[float]): returns tuple of buffered coordinates rounded to interval in order of [W,E,S,N] """ if bbox[0] % interval != 0: xmin = bbox[0] - (bbox[0] % interval) else: xmin = bbox[0] if bbox[1] % interval != 0: xmax = bbox[1] + (interval - (bbox[1] % interval)) else: xmax = bbox[1] if bbox[2] % interval != 0: ymin = bbox[2] - (bbox[2] % interval) else: ymin = bbox[2] if bbox[3] % interval != 0: ymax = bbox[3] + (interval - (bbox[3] % interval)) else: ymax = bbox[3] return (xmin, xmax, ymin, ymax)
def new_links(all_links, existing_links): """ Return all links which are in the all_links but not in the existing_links. This is used to determine which links are new and not indexed jet. Set the ONLY_NEW environment variable to activate this filter mechanism. """ existing_urls = {link['url'] for link in existing_links} return [link for link in all_links if link['url'] not in existing_urls]
def int_from_32bit_array(val): """ Converts an integer from a 32 bit bytearray :param val: the value to convert to an int :return: int """ rval = 0 for fragment in bytearray(val): rval <<= 8 rval |= fragment return rval
def to_camel_case(snake_str): """ Convert a string to camel case """ components = snake_str.split('_') return components[0] + ''.join(x.title() for x in components[1:])
def turn_back(dirs: dict): """ Make a new dict with a structure: dict( list_1_elem_1: key_1, list_1_elem_2: key_1, list_1_elem_2: key_1, list_2_elem_1: key_2, list_2_elem_2: key_2 etc.. ) """ proper_dict = {} for key, values in dirs.items(): for value in values: proper_dict[value.lower()] = key return proper_dict
def assert_data_property(uri, data_property, value): """ Given a uri, a data_property name, and a value, generate rdf to assert the uri has the value of the data property. Value can be a string or a dictionary. If dictionary, sample usage is three elements as shown: value = { 'value': val, 'xml:lang': 'en-US', 'dataype' : 'http://www.w3.org/2001/XMLSchema#string'} Note: This function does not check that the data property name is valid """ from xml.sax.saxutils import escape if isinstance(value, dict): val = escape(value['value']) else: val = escape(value) rdf = ' <rdf:Description rdf:about="' + uri + '">' rdf = rdf + '\n <' + data_property if isinstance(value, dict) and 'xml:lang' in value: rdf = rdf + ' xml:lang="' + value['xml:lang'] + '"' if isinstance(value, dict) and 'datatype' in value: rdf = rdf + ' datatype="' + value['datatype'] + '"' rdf = rdf + '>' + val + '</' + data_property + '>' rdf = rdf + '\n </rdf:Description>\n' return rdf
def mostLikelyGoalObject(rewardMatrix): """ Return the object index of an object that is at least >50% probable to have a greater reward than all other objects. """ # Given a list of values, return True if every value is greater than 0.5 allLikely = lambda ls : False if False in [x>0.5 for x in ls] else True # Apply function to all objects goals = [] for i in range(4): if allLikely(rewardMatrix[i]): goals.append(i) # If more than one object satisfy the criterion, there is an indeterminate # priority between them. if len(goals) > 1: return -1 # Likewise if no objects satisfy it. if len(goals) == 0: return -1 # Else, return the one object return goals[0]
def FlagIsExplicitlySet(args, flag): """Return True if --flag is explicitly passed by the user.""" # hasattr check is to allow the same code to work for release tracks that # don't have the args at all yet. return hasattr(args, flag) and args.IsSpecified(flag)
def getlabel(key): """ Get a file label from keys with reversed order """ return '-'.join(["%05g" % k for k in key])
def get_default_assignment_policy(is_human): """ Return the default assignment policy. Args: is_human (bool): Indicates whether the policy is for a human or machine. Returns: default_policy (dict): A dictionary specifying the assignment policy. """ return {} if not is_human else { 'policy_function': { 'entry_level': { 'path': 'orchestra.assignment_policies.anyone_certified' }, 'reviewer': { 'path': 'orchestra.assignment_policies.anyone_certified' } }, }
def matchBrackets(string: str): """ Separate the contents matching the first set of brackets from the rest of the input. """ rest = string[1:] inside = "(" while rest != "" and not rest.startswith(")"): if rest.startswith("("): (part, rest) = matchBrackets(rest) inside = inside + part else: inside = inside + rest[0] rest = rest[1:] if rest.startswith(")"): return (inside + ")", rest[1:]) raise AssertionError("Unmatched bracket in string '" + string + "'")
def unrole_variations_to_list(dictionary): """ :param dictionary: e.g. { 'b': {'0.6': [{'shape': 'sphere', 'general_position': 'left'}, {'shape': 'sphere', 'general_position': 'left'}, {'shape': 'sphere', 'general_position': 'left'}, {'shape': 'cylinder', 'general_position': 'right', 'material': 'metal'}, {'shape': 'cylinder', 'general_position': 'right', 'material': 'metal'}, {'shape': 'cylinder', 'general_position': 'right', 'material': 'metal'}]}, 'a': {'0.4': [{'shape': 'sphere', 'general_position': 'left'}, {'shape': 'sphere', 'general_position': 'left'}, {'shape': 'sphere', 'general_position': 'left'}]} } :return: """ return [list(list(dictionary.items())[i][1].items())[0][1] for i in range(len(dictionary.items()))]
def _try_to_float(s): """convert string to float or leave as string""" try: return float(s) except (ValueError, TypeError): return s
def most_minutes_asleep(naps): """ Return the ID of the guard who naps the most. """ most_minutes = 0 sleepiest = None for guard, recorded_naps in naps.items(): total = 0 for nap in recorded_naps: total += nap[1] - nap[0] if total > most_minutes: most_minutes = total sleepiest = guard return sleepiest
def get_aa_using_codon_gct(gct=None, codon=None): """ This functions returns dictionary object containing data for respective amino acid for the given codon. :param gct: dictionary object containing gc table data. :param codon: Codon (string) e.g. AAA :return: """ try: if gct is None or codon is None: # Invalid set of inputs provided return None for key in gct.keys(): aa_data = gct.get(key) if codon.upper() in aa_data["codons"]: # found the codon, return AA key. return aa_data # Could not find this codon in any AA's data. return None except Exception as e: print(e) return None
def PySelectCoins_MultiInput_SingleValue( \ unspentTxOutInfo, targetOutVal, minFee=0): """ This method should usually be called with a small number added to target val so that a tx can be constructed that has room for user to add some extra fee if necessary. However, we must also try calling it with the exact value, in case the user is trying to spend exactly their remaining balance. """ target = targetOutVal + minFee outList = [] sumVal = 0 for utxo in unspentTxOutInfo: sumVal += utxo.getValue() outList.append(utxo) if sumVal>=target: break return outList
def get_fancy_time(sec): """ Convert a time measured in seconds to a fancy-printed time. :param sec: Float :return: String """ h = int(sec) // 3600 m = (int(sec) // 60) % 60 s = sec % 60 if h > 0: return '{h} hours, {m} minutes, and {s} seconds.'.format(h=h, m=m, s=round(s, 2)) elif m > 0: return '{m} minutes, and {s} seconds.'.format(m=m, s=round(s, 2)) else: return '{s} seconds.'.format(s=round(s, 2))
def get_shard_name(shard, num_shards): """Returns an appropriate shard name, as a string. A single shard name is simply 0; otherwise it will attempt to split up 0x100 into multiple shards. For example, in a two sharded keyspace, shard 0 is -80, shard 1 is 80-. This function currently only applies to sharding setups where the shard count is 256 or less, and all shards are equal width. Args: shard: The integer shard index (zero based) num_shards: Total number of shards (int) Returns: The shard name as a string. """ if num_shards == 1: return '0' shard_width = int(0x100 / num_shards) if shard == 0: return '-%02x' % shard_width elif shard == num_shards - 1: return '%02x-' % (shard * shard_width) else: return '%02x-%02x' % (shard * shard_width, (shard + 1) * shard_width)
def binary_search(data, target, low, high): """Return True if target is found in indicated portion of a Python list Taking advantage of a sorted array or list """ if low < 0 or high > len(data): return 'Please ensure low and high index are within range of the data' if low > high: return -1 # means we could not find the target else: mid = (low + high) // 2 if target == data[mid]: return True elif target < data[mid]: # recur on the portion left of the middle # interval is empty; no match # found a match return binary_search(data, target, low, mid - 1) else: # recur on the portion right of the middle return binary_search(data, target, mid + 1, high)
def partial_str(s: str, width=100) -> str: """ >>> partial_str('abcd', 5) 'abcd' >>> partial_str('abcde', 5) 'abcde' >>> partial_str('abcdef', 5) 'ab...' >>> partial_str('abcd', 2) Traceback (most recent call last): ... ValueError: width must be greater than 3 """ if width <= 3: raise ValueError('width must be greater than 3') if len(s) > width: s = s[:width - len('...')] + '...' return s
def hex_to_rgb(hex): """Return (red, green, blue) for the color given as #rrggbb.""" hex = hex.lstrip('#') lv = len(hex) return tuple(int(hex[i:i + lv // 3], 16) for i in range(0, lv, lv // 3))
def tuple_to_fasta_name(structure_name, chain_name): """Fasta names can only be strings. This code writes the tuples in.""" sname = '___'.join([str(x) for x in structure_name]) cname = '___'.join([str(x) for x in chain_name]) return sname + '____' + cname
def _exec(code: str, globals_: dict, ret): """ References: https://stackoverflow.com/questions/1463306/how-does-exec-work-with -locals """ locals_ = {} exec(code, globals_, locals_) assert ret in locals_, ( f'The lambda code block didn\'t contain `{ret} = <some_function>` ' f'statement!' ) return locals_[ret]
def find_empty_location(grid): """ Looks for the coordinates of the next zero value on the grid, starting on the upper left corner, from left to right and top to bottom. Keyword Arguments: grid {number matrix} -- The matrix to look for the coordinates on (default: {The instance's grid}) Returns: tuple -- The (x, y) coordinates of the next zero value on the grid if one is found """ for index, row in enumerate(grid): if 0 in row: return (row.index(0), index)
def can_string_be_rearranged_as_palindrome(input_str: str = "") -> bool: """ A Palindrome is a String that reads the same forward as it does backwards. Examples of Palindromes mom, dad, malayalam >>> can_string_be_rearranged_as_palindrome("Momo") True >>> can_string_be_rearranged_as_palindrome("Mother") False >>> can_string_be_rearranged_as_palindrome("Father") False >>> can_string_be_rearranged_as_palindrome_counter("A man a plan a canal Panama") True """ if len(input_str) == 0: return True lower_case_input_str = input_str.replace(" ", "").lower() # character_freq_dict: Stores the frequency of every character in the input string character_freq_dict = {} for character in lower_case_input_str: character_freq_dict[character] = character_freq_dict.get(character, 0) + 1 """ Above line of code is equivalent to: 1) Getting the frequency of current character till previous index >>> character_freq = character_freq_dict.get(character, 0) 2) Incrementing the frequency of current character by 1 >>> character_freq = character_freq + 1 3) Updating the frequency of current character >>> character_freq_dict[character] = character_freq """ """ OBSERVATIONS: Even length palindrome -> Every character appears even no.of times. Odd length palindrome -> Every character appears even no.of times except for one character. LOGIC: Step 1: We'll count number of characters that appear odd number of times i.e oddChar Step 2:If we find more than 1 character that appears odd number of times, It is not possible to rearrange as a palindrome """ oddChar = 0 for character_count in character_freq_dict.values(): if character_count % 2: oddChar += 1 if oddChar > 1: return False return True
def listmods(n): """ Trasforma il valore restituito dall'API di osu! di enabled_mods in una stringa contenente l'elenco corrispondente a parole. :param n: Valore da trasformare in stringa """ mods = "*Mod:*" # Dividi in bit l'ID delle mod selezionate usando un bitwise and # Forse si potrebbe rifare usando la forma esadecimale...? if int(n) & 0x1: mods += " NoFail" if int(n) & 0x2: mods += " Easy" if int(n) & 0x4: mods += " NoVideo (?)" if int(n) & 0x8: mods += " Hidden" if int(n) & 0x10: mods += " HardRock" if int(n) & 0x20: mods += " SuddenDeath" if int(n) & 0x40: mods += " DoubleTime" if int(n) & 0x80: mods += " Relax" if int(n) & 0x100: mods += " HalfTime" if int(n) & 0x200: mods += " Nightcore" if int(n) & 0x400: mods += " Flashlight" if int(n) & 0x800: mods += " Autoplay" if int(n) & 0x1000: mods += " SpunOut" if int(n) & 0x2000: mods += " Autopilot" if int(n) & 0x4000: mods += " Perfect" if int(n) & 0x8000: mods += " 4K" if int(n) & 0x10000: mods += " 5K" if int(n) & 0x20000: mods += " 6K" if int(n) & 0x40000: mods += " 7K" if int(n) & 0x80000: mods += " 8K" if int(n) & 0x100000: mods += " FadeIn" if int(n) & 0x200000: mods += " Random" if int(n) & 0x400000: mods += " 9K" if int(n) & 0x800000: mods += " 10K" if int(n) & 0x1000000: mods += " 1K" if int(n) & 0x2000000: mods += " 3K" if int(n) & 0x4000000: mods += " 2K" return mods
def recordenum_view_url(enum_id, coll_id="testcoll", type_id="testtype"): """ Returns public access URL / URI for indicated enumerated value. enum_id id of enumerated value coll-id id of collection type_id id of enumeration type """ return ( "/testsite/c/%(coll_id)s/d/%(type_id)s/%(enum_id)s/"% {'coll_id': coll_id , 'type_id': type_id , 'enum_id': enum_id} )
def _build_path(key: str, base_path: str): """Build a path string.""" if base_path: return f'{base_path}|{key}' return key