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): ...
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[...
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 ...
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) cu...
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 """ intersect...
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_calla...
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...
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' , '...
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 lo...
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 = lambd...
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(o...
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 ['Tru...
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] == ...
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(c...
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: ...
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_heigh...
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 No...
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_en...
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_...
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]/...
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 ...
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 ...
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 c...
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...
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``...
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 w...
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 refe...
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.sp...
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...
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 ...
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", ...
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 = f...
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` ...
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) - Wors...
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...
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(2...
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) ...
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']...
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, ...
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-...
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...
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) ...
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 ==...
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 ...
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'] fo...
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(): fo...
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:la...
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 ...
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 {}...
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) ...
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':...
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_minu...
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 ...
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, ...
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, ...
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...
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: ret...
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 """ ...
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>`...
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}) Re...
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("...
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 potr...
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/%(...
def _build_path(key: str, base_path: str): """Build a path string.""" if base_path: return f'{base_path}|{key}' return key