content
stringlengths
42
6.51k
def _apply_if_callable(maybe_callable, obj, **kwargs): """ Evaluate possibly callable input using obj and kwargs if it is callable, otherwise return as it is """ if callable(maybe_callable): return maybe_callable(obj, **kwargs) return maybe_callable
def length_of_last_word(words): """ Returns the length of the last word (a string of lower or uppercase characters) from a string composed of space and alphabetic characters. Parameters: words(str) Returns: int """ def traverse(index, progress): """ Returns the index ...
def prestats(threshold): """Wrapper for the ``tbss_4_prestats`` command. The normal recommendation for <threshold> is 0.2 """ return ["tbss_4_prestats", f'{threshold}']
def linear(u, v, d): """ Linear interpolation. Args: u (float) v (float) d (float): the relative distance between the two to return. Returns: float. The interpolated value. """ return u + d*(v-u)
def CollectUniqueByOrderOfAppearance(dataset:list): """ This method collect all unique in order of appearance and return it as list. :param dataset:list: dataset list """ try: seen = set() seen_add = seen.add return [x for x in dataset if not (x in seen or seen_add(x))] ...
def extendURL(url, extend): """Extend a URL by the given extend.""" url = url.strip().strip('/') + '/' + extend.strip().strip('/') return url
def version_get(v1, v2): """Check if version v1 is great or equal then version v2. """ return [int(i) for i in v1.split('.') if i.isdigit()] > [int(i) for i in v2.split('.') if i.isdigit()]
def uv_emoji(uv): """ Accepts UV index value. Returns colour emoji corresponding to risk of harm. See https://en.wikipedia.org/wiki/Ultraviolet_index#Index_usage """ # negative values if uv < 0: raise ValueError("UV index cannot be negative.") # low -> green elif uv <= 2...
def format_route_key(route: str, method: str) -> str: """Formats an HTTP verb and the associated route into a dictionary key. :param route: The URL route. :param method: The HTTP method associated with the route. :returns: The formatted string. """ return "{}, {}".format(rou...
def score_reference_dist(sim_frame: dict) -> dict: """Simplest example of score assignment. Gives points from zero to one simply by (10-d)/10, where d is distance from reference track in meters. Parameters ---------- sim_frame : dict A single object from simulationMessage.frames compliant with ...
def reduceDict(_object, exclude_fields): """ this function take a dict object and and array of keys 'exclude_fields' and return same object without the keys in the 'exclude_fields' array """ for field in exclude_fields : try: del _object[str(field)] except KeyError : ...
def find_used_chars(name_list): """ Move to guitool_ibeis """ used_chars = [] for name in name_list: index = name.find('&') if index == -1 or index + 1 >= len(name): continue char = name[index + 1] used_chars.append(char) return used_chars
def convert_args_to_laid_out_tensors(xs): """Convert list elements to laid-out-tensors when possible. Args: xs: a list Returns: a list """ ret = [] for x in xs: if hasattr(x, "to_laid_out_tensor"): ret.append(x.to_laid_out_tensor()) else: ret.append(x) return ret
def unique_mers(sequencelist, sizeofmer): """ WEV This will create a list of all of the unique Nmers of the object The goal is to have this be flexible enough to take a list or string """ output = [] if isinstance(sequencelist, list) or isinstance(sequencelist, set): for sequence in sequ...
def url_exists(url): """Checks whether a URL exists.""" return True validator = URLValidator(True) try: validator(url) return True except ValidationError: return False
def _legendre(a, p): """ Returns the legendre symbol of a and p assuming that p is a prime i.e. 1 if a is a quadratic residue mod p -1 if a is not a quadratic residue mod p 0 if a is divisible by p Parameters ========== a : int The number to test. p : prime ...
def IsPalindromePermutation(s): """ check if the string s is a permutation of a palindrome""" chars = {k : 0 for k in set(s)} for i in s: chars[i] += 1 odd_nums = 0 for k, v in chars.items(): if (v % 2) != 0: odd_nums += 1 if odd_nums > 1: return False return True
def truncate_metadata(data_string): """ Avoid probelms with Studio and Kolibri DB constraints. """ MAX_CHARS = 190 if len(data_string) > MAX_CHARS: data_string = data_string[:190] + " ..." print('Truncating string', data_string, 'to length 190.') return data_string
def is_prolog_functor(json_term): """ True if json_term is Prolog JSON representing a Prolog functor (i.e. a term with zero or more arguments). See `swiplserver.prologserver` for documentation on the Prolog JSON format. """ return ( isinstance(json_term, dict) and "functor" in json_term and "ar...
def padding_rfam_genome_id_with_zeros(number): """ Adds a prefix of zeros to the number provided to generate a new Rfam genome id number: A number to add zeros to return: A 9 character long string of a number with a prefix of zeros """ zero_vector = "000000000" text_num = str(num...
def get_snps(x: str) -> tuple: """Parse a SNP line and return name, chromsome, position.""" snp, loc = x.split(' ') chrom, position = loc.strip('()').split(':') return snp, chrom, int(position)
def check_phone(collection, id_, cont): """ Phone checking """ return 11 <= len(str(cont)) <= 18
def any_in_string(l, s): """ Check if any items in a list is in a string :params l: dict :params s: string :return bool: """ return any([i in l for i in l if i in s])
def count_negatives(nums): """Return the number of negative numbers in the given list. >>> count_negatives([5, -1, -2, 0, 3]) 2 """ n_negative = 0 for num in nums: if num < 0: n_negative = n_negative + 1 return n_negative
def longest_common_prefix(strs): """Submitted this and it passed all test cases January 18, 2022.""" o = "" # Find/compute the length of the shortest item in the list. shortest_seen_so_far = 201 for item in strs: if len(item) < shortest_seen_so_far: shortest_seen_so_far = len(it...
def _get_node_from_dictionary(obj, key, fallback=0): """Get node from dictionary.""" if isinstance(obj, dict): obj = obj.get(key) or obj.get(fallback) return obj
def times_add(a, b, c): """Returns a * b + c""" return a * b - -c
def ensure_dict(x): """Make sure ``x`` is a ``dict``, creating an empty one if ``x is None``. """ if x is None: return {} return dict(x)
def _get_authority_url(authority_endpoint, tenant): """Convert authority endpoint (active_directory) to MSAL authority: - AAD: https://login.microsoftonline.com/your_tenant - ADFS: https://adfs.redmond.azurestack.corp.microsoft.com/adfs For ADFS, tenant is discarded. """ # Some Azure St...
def speed_convert(size): """Hi human, you can't read bytes?""" power = 2 ** 10 zero = 0 units = {0: "", 1: "Kb/s", 2: "MB/s", 3: "Gb/s", 4: "Tb/s"} while size > power: size /= power zero += 1 return f"{round(size, 2)} {units[zero]}"
def pos2d(s): """ s - position on the board, for example 'a3' or 'hMAX_BOARD' """ column = ord(s[0]) - ord('a') row = ord(s[1]) - ord('1') return column, row
def to_sting(reads): """join FASTQ reads to a single DNA string""" return ''.join(i for i in reads)
def is_hashable(arg): """Return True if hash(arg) will succeed, False otherwise. Some types will pass a test against collections.Hashable but fail when they are actually hashed with hash(). Distinguish between these and other types by trying the call to hash() and seeing if they raise TypeError. ...
def is_terminal(x, y, world_size): """Identify whether a state is terminal or not (top-left and bottom-right corner)""" return (x == 0 and y == 0) or (x == world_size-1 and y == world_size-1)
def WordStartWithUppercase(word): """Return whether a word starts with uppercase letter""" if len(word) == 0: return False firstChar = word[0] return firstChar == firstChar.upper()
def tags_to_dict(tags): """ Converts the tag set to a dictionary """ return {key: value for key, value in tags}
def find_order(recipe): """ function to find an order in a string that contains instructions in the form of: "these are my instructions: 1. chop onions 2. fry onions 3. eat onions 4. digest onion" will be transformed to {'instructions': [{'steps': 'these are my instructions: '}, {'...
def soft_thresholding_operator(z, l): """ Soft-thresholding operator. """ if z > l: val = z - l elif z < -l: val = z + l else: val = 0 return val
def _crawl(name, mapping): """ ``name`` of ``'a.b.c'`` => ``mapping['a']['b']['c']`` """ key, _, rest = name.partition('.') value = mapping[key] if not rest: return value return _crawl(rest, value)
def get_cal(length, width, bombs): """ Get numbers of non-bomb positions :param length: length of the board :param width: width of the board :param bombs: list of bomb positions :return: matrix of numbers """ cals = [[0 for _ in range(width)] for _ in range(length)] for i in range(le...
def coin_sums(coins, value): """Calculates the number of combinations of given coins add up to given value""" length = len(coins) # pylint: disable=misplaced-comparison-constant if 0 == value: return 1 if 0 > value: return 0 if 0 >= length and 1 <= value: return 0 r...
def sort_by_value(d): """ Returns the keys of dictionary d sorted by their values """ items=d.items() backitems=[ [v[1],v[0]] for v in items] backitems.sort() backitems.reverse() return [ backitems[i][1] for i in range(0,len(backitems))]
def _wrap_js(script: str) -> str: """Wrap JS in <script></script> tag for injection into HTML.""" return "<script type='text/javascript'>{script}</script>".format(script=script)
def get_domain_id_field(domain_table): """ A helper function to create the id field :param domain_table: the cdm domain table :return: the id field """ return domain_table + '_id'
def ceiling(a, b): """ Returns ceil(a/b) """ return -(-a//b)
def parse_07h_and_08h_bytes(byte_val_10: int, byte_val_11: int) -> int: """Key""" assert 0 <= byte_val_10 < 256 assert 0 <= byte_val_11 < 256 # key has 16 bit = 2 byte # byte_val_10 are high bits of module address # byte_val_11 are low bits of module address # shifting byte_val_10 8 bits to ...
def close_enough(vector_one, vector_two): """Check that the values for vectors are close enough (< 0.1)""" for i in range(len(vector_one)): for j in range(len(vector_one[i])): if vector_one[i][j] - vector_two[i][j] > 0.1: return(False) return(True)
def _parse_outputs(outputs_data): """ Parses outputs from .tfstate file :param outputs_data: dict "output": { "value": string, "type": string } :return: dict, with the following structure: { "{name}": string, } """ res_outputs = {} for name, value...
def bb_to_area(bb): """ width : float Rectangle width height : float Rectangle height :param bb: xmin ymin xmax ymax :return: """ width = bb[2] - bb[0] height = bb[3] - bb[1] area = width * height return area
def n_inv(r1, r2): """ Calculates the Kendall-tau distance between two rankings, i.e. the number of inversions between the two sequences. r1 and r2 are iterables so that r1[i] is the ranking of the i-th element.""" assert len(r1) == len(r2) n = 0 for i in range(len(r1)): for j in range(i...
def evolve_state(state, rules): """ Given state string, return a state string after applying rules. """ ret = '' offsets = list(range(-2, 2 + 1)) for index, symbol in enumerate(state[2:-2], 2): nbhood = ''.join(state[(index + offset)] for offset in offsets) ret += rules[nbhood] ...
def str_to_bool(string): """ Converts strings to boolean :param string (str): string to convert : retrun (bool): True if string is equal to "True", False if equal to "False" """ if string == "True": return True elif string == "False": return False else: return st...
def other_classes(nb_classes, class_ind): """ Heper function that returns a list of class indices without one class :param nb_classes: number of classes in total :param class_ind: the class index to be omitted :return: list of class indices without one class """ other_classes_list = list(ra...
def two_of_three(x, y, z): """Return a*a + b*b, where a and b are the two smallest members of the positive numbers x, y, and z. >>> two_of_three(1, 2, 3) 5 >>> two_of_three(5, 3, 1) 10 >>> two_of_three(10, 2, 8) 68 >>> two_of_three(5, 5, 5) 50 >>> # check that your code cons...
def split_args(args): """Split command line args in 3 groups: - head, containing the initial options - body, containing everything after head, up to the first option - tail, containing everything after body """ head = [] body = [] tail = [] for arg in args: if arg.startswith...
def matrixmultip(matrix_a, matrix_b): """ A function that multiplies two matrices, and return a callable list with the result. :param matrix_a: First matrix to be added at the multiplication; :param matrix_b: Second matrix to be added at the multiplication; :return: A callable list containing 9 elem...
def format_string(string, metadata, output_extension="", sanitizer=lambda s: s): """ Replaces any special tags contained in the string with their metadata values. Parameters ---------- string: `str` A string containing any special tags. metadata: `dict` Metadata in standard...
def get_size_of_corpus(filepaths): """ Given a list of filepaths, it will return the total number of lines Parameters ---------- filepaths : [ str ] A list of filepaths Returns ------- num_lines : int The total number of lines in filepaths ...
def _parse_lib_part_(self, get_name_only=False): # pylint: disable=unused-argument """ Create a Part using a part definition from a SKiDL library. """ # Parts in a SKiDL library are already parsed and ready for use, # so just return the part. return self
def dict_map(f, d): """Apply function f to all terminal elements of dict d.""" if isinstance(d, dict): return {k: dict_map(f, v) for k, v in d.items()} elif isinstance(d, list): return [dict_map(f, x) for x in d] else: return f(d)
def _IssueProjectKey(project_name, local_id): """Make a dictionary key to identify a referenced issue.""" return '%s:%d' % (project_name, local_id)
def _code_block(inp: str) -> str: """_code_block. Args: inp (str): inp Returns: str: github style code block """ return "\n".join( [ "```", inp, "```", ] )
def format_gt_red(val, red_length): """ Helper function to get css style of color for cell value. """ return "color: red" if val > red_length else None
def orb_rot_meta(name): """Parse metadata from orbital rotation variable name Args: name (str): optimizable variable name Return: dict: metadata Example: >>> name = "spo-up_orb_rot_0000_0002" >>> orb_rot_meta(name) >>> {'prefix': 'spo-up', 'i': 0, 'j': 2} """ useful = name.replace('orb_...
def gather_pieces(fmtstr, placeholder): """ Takes a format string where % marks replacements by placeholder, and %% marks replacements by %. The returned object is a list of substrings and placeholders. """ pieces = [] substr = [] escape = False for c in fmtstr: if escape: ...
def get_frame_info(frame): """ return a string buffer containing selected frame info """ if not frame or not frame.IsValid(): return None, None, None #info_buffer = "{} in {}".format(hex(frame.pc()), frame.name()) info_buffer = "{} in {}".format(frame.GetPCAddress().__hex__, frame.Get...
def stem(word): """ Stem word to primitive form """ return word.lower().rstrip(",.!:;'-\"").lstrip("'\"")
def modify_average(old_average, old_member_count, new_value, round_value): """Modify average value (e.g. mass) for an averaged feature on addition of a new member. i.e. if the average value for a feature is 4 based on an average from 4 input values, then adding a new value (6) will make the new average (4 *...
def sanitize_hex(hex_string): """ Sanitize input to uppercase hex string :param hex_string: the input hex string, e.g. 0xabc, 0xABC, abc, 28h :return: sanitized hex string, e.g. ABC or 28 """ return ''.join(c for c in hex_string.upper() if c in '0123456789ABCDEF')
def le(h): """ Little-endian, takes a 16b number and returns an array arrange in little endian or [low_byte, high_byte]. """ h &= 0xffff # make sure it is 16 bits return [h & 0xff, h >> 8]
def adjust_learning_rate(lr, iter): """Sets the learning rate to the initial LR decayed by 0.5 every 1000 iterations""" lr = lr * (0.5 ** (iter // 1000)) return lr
def convindicetoplanetype(listindice): """ Converts miller plane (3 indices) into plane type for recognition where indices are sorted in decreasing order ex: [1,-2,-1] -> 211 """ listpositiveinteger = [abs(elem) for elem in listindice] listpositiveinteger.sort(reverse=True) resint = (1...
def ensure_not_removed_bootstrapped(package_control_settings): """ Forces the `Package Control.sublime-settings` to be reloaded, so we can uninstall it immediately. """ print( "[2_bootstrap.py] ensure_not_removed_bootstrapped, finishing Package Control Uninstallation, setting bootstrapped......
def flops_to_string(flops, units='GFLOPs', precision=2): """Convert FLOPs number into a string. Note that Here we take a multiply-add counts as one FLOP. Args: flops (float): FLOPs number to be converted. units (str | None): Converted FLOPs units. Options are None, 'GFLOPs', 'MFL...
def csv_ints(value): """ Parse a CSV string into an array of ints. """ return list(map(int, value.split(",")))
def ensure_list_from_str(s, sep='\n'): """Given a multiline string convert it to a list of return None if empty Parameters ---------- s: str or list """ if not s: return None if isinstance(s, list): return s return s.split(sep)
def _call_signature(callable, *args, **kwargs): """ Generate a human-friendly call signature From recipe http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/307970 """ argv = [repr(arg) for arg in args] + ["%s=%r" % x for x in kwargs.items()] return "%s(%s)" % (callable.__name__, ", ".join(...
def get_body_part_colour(shot): """ Decide the colour of a plot element based on the shooter's body part. """ body_part = shot['shot']['body_part']['name'] if body_part == 'Right Foot': return 'orange' if body_part == 'Left Foot': return 'red' if body_part == 'Head': ...
def assign_label(offsets, terms): """ Assign BIO label to each word of the sentence. """ terms_sentence = [] if len(terms) == 0: lst = [['O'] * len(offsets)] return lst, lst, terms_sentence max_level = max([item[-1] for item in terms]) lst = [] # nner lst_term = [] ...
def split_and_strip_non_empty_lines(text): """Return lines split by newline. Ignore empty lines. """ return [line.strip() for line in text.splitlines() if line.strip()]
def harmonic( ranks ): """ returns the harmonic mean of the assembly's ranks """ h = 0 for r in ranks: h += 1.0 / r h = 1.0 / h h *= len( ranks ) return h
def listwrap(val): """Wrap `val` as a list. :param val: iterable or constant :returns: `list(val)` if `val` is iterable, else [val] """ if isinstance(val, list): return val if isinstance(val, tuple): return list(val) return [val]
def mean (nums): """Calculate Mean. Parameters: nums: list of numbers Return Value: mean value """ return float(sum(nums))/len(nums)
def max_sub_array(nums): """ Returns the max subarray of the given list of numbers. Returns 0 if nums is None or an empty list. Time Complexity: o(n) Space Complexity: 0(1) """ if not nums: return 0 max_return = nums[0] last_seen = nums[0] for i in range(1, l...
def to_algebraic(cartesian): """Convert cartesian to algebraic Parameters ---------- cartesian: tuple Cartesian coordinate Returns ------- str Algebraic coordinate """ mapper = { 1: 'A', 2: 'B', 3: 'C', 4: 'D', 5: 'E', ...
def getUnionAndMap(listOfLists): """ Given a list of lists, computes union of all lists, as well as map from list of lists to union lists. """ union_list = [] union_map = [] for i in range(len(listOfLists)): union_map.append([None] * len(listOfLists[i])) for j in range(len(li...
def _parse_table_cell(col, x): """ Parse 1 table cell. If col is 0, left margin - 1 should be kept for hierarchical data. :param col: col index :param x: data in cell :return: int, float or str """ try: return int(x) except ValueError: pass try: return float(x...
def get_shape2D(in_val): """ Return a 2D shape Args: in_val (int or list with length 2) Returns: list with length 2 """ # in_val = int(in_val) if isinstance(in_val, int): return [in_val, in_val] # if isinstance(in_val, list): if len(in_val) == 2:...
def divisors (n): """ return all divisors of a given number >>> divisors(1) [1, 1] >>> divisors(12) [1, 2, 3, 4, 6, 12] """ result = [] i = 1 while(i *i< n+1): if (n%i == 0): result.append(n/i) result.append(i) i = i + 1 result...
def create_dummy_file(path, filesize): """Helper routine to create a dummy file with desired size.""" with open(path, "wb") as outfile: outfile.seek(filesize - 1) outfile.write(b"\0") return path
def unmangle(name: str) -> str: """Remove internal suffixes from a short name.""" return name.rstrip("'")
def phaseID_linestyle(phaseID, linestyles=["-", "--", ":", "-."]*2): """ Method for generating linestyles for delineating sequential phases based on their phase IDs (e.g. olivine_0, olivine_1) . Parameters ----------- phasename : :class:`str` Phase ID for which to generate a line style....
def _choose_correct_hierarchy(u_occupations, v_occupations): """ """ if len(u_occupations) == 0 or len(v_occupations) == 0: return None u_best_match = next(iter(u_occupations)) v_best_match = next(iter(v_occupations)) for u_occupation in u_occupations: for v_occupation in v_occupatio...
def add_leading_dot(s): """Add leading dot. """ if '.' != s[0]: s = '.' + s return(s)
def outfile_hidden(arg): """Decorate an argument as an output that is not passed as a command-line argument. :parameter arg: Argument to designate as an input file. """ return ('out_hidden', arg)
def countSyllables(word): """ Returns the number of syllables in a word """ count = 0 vowels = 'aeiouy' word = word.lower().strip(".:;?!,") #If first letter is a vowel if word[0] in vowels: count += 1 for index in range(1, len(word)): #Handles compound-vowel ...
def make_tokens(binary_parse): """ Convert a binary parse: ( ( The men ) ( ( are ( fighting ( outside ( a deli ) ) ) ) . ) ) to [The men are fighting outside a deli .] @returns tuple """ return tuple(binary_parse.replace("(", "").replace(")", "").split())
def sorted_by_key(x, i, reverse=False): """For a list of lists/tuples, return list sorted by the ith component of the list/tuple, E.g. Sort on first entry of tuple: > sorted_by_key([(1, 2), (5, 1)], 0) >>> [(1, 2), (5, 1)] Sort on second entry of tuple: > sorted_by_key([(1, 2), (5,...
def _scale_to_fit(width, height, max_width, max_height): """scales input dimensions to fit within max dimensions""" height_scale = height/max_height width_scale = width/max_width scale = max(height_scale, width_scale) if scale > 1: height /= scale width /= scale return width, hei...
def hms(ts): """Return hours, minutes, seconds""" tval = int(ts) hours = tval/3600 leftover = tval - hours * 3600 minutes = leftover/60 seconds = leftover - 60 * minutes return (hours, minutes, seconds)