content
stringlengths
42
6.51k
def ordinal(n): """ Converts numbers into ordinal strings """ return ( "%d%s" % (n, "tsnrhtdd"[(n // 10 % 10 != 1) * (n % 10 < 4) * n % 10::4]))
def reformat_large_tick_values(tick_val, pos): """ Turns large tick values (in the billions, millions and thousands) such as 4500 into 4.5K and also appropriately turns 4000 into 4K (no zero after the decimal). taken from: https://dfrieds.com/data-visualizations/how-format-large-tick-values.html ""...
def transform_to_bool(value): """ Transforms a certain set of values to True or False. True can be represented by '1', 'True' and 'true.' False can be represented by '1', 'False' and 'false.' Any other representation will be rejected. """ if value in ["1", "true", "True", True]: ret...
def str_strip(str_in): """ strip whitespace at right of string. Wrap string rstrip method into function """ return str(str_in.rstrip())
def clean_response(inp): """ Remove arbitrary characters from the response string """ # Remove all alert characters. inp = inp.replace('', '') return inp
def getfunc(num, dic): """ Given a brodmann area number and and directory of functions will look up which function is active. :param num: the brodmann area number for the area which will be looked up :param dic: dictionary of functions """ val = [] for key in dic: if num...
def validate_mp_xy(fits_filenames, control_dict): """ Quick check for frequently made errors in MP XY entries in control dict. :param fits_filenames: :param control_dict: :return: 2-tuple, (mp_xy_files_found, mp_xy_values_ok). [2-tuple of booleans, both True if OK] """ mp_location_filenames = [m...
def first_insertion_sort(numbers): """Non recursive first implementation of insertion sort.This one does not have any optimization and it is considered to be the worst one. The iteration counter will be present to show the difference between each implementation. Args: numbers (list): list o...
def create_label_from_filename(filename): """ Takes a filename and turns it into a list with a single lowercase string containing the pet label that is in the filename (ex. filename = 'Boston_terrier_02259.jpg' Pet label = 'boston terrier') Parameters: filename - The filename (string) Returns: List w...
def is_package(item): """Does this string describes a package""" if "/" not in item and "\\" not in item: return True else: return False
def smart_truncate(text: str, max_length: int = 100, suffix: str = '...') -> str: """ Returns a string of at most `max_length` characters, cutting only at word-boundaries. If the string was truncated, `suffix` will be appended. In comparison to Djangos default filter `truncatechars` this method does...
def compute_middle_point(p0, p1): """ Compute the middle point between 2 points by simple arithmetical mean :param p0: first point as a list or tuple :param p1: second point :return: a list that contains the middle point """ return [(p0[0] + p1[0]) / 2.0, (p0[1] + p1[1]) / 2.0]
def get_weekday_name(weekday): """ Return the name of the week day. @param weekday: Week day chunk of the NetworkList Registry key. """ weekday_names = {0: "Sunday", 1: "Monday", 2: "Tuesday", 3: "Wednesday", 4: "Thursday", 5: "Friday", 6: "Saturday...
def is_int(value) -> bool: """ Tests a value to check if it is an integer or not. "value" can be of any type, as long as it can be converted to int. Note: `is_int(None)` will raise TypeError. """ try: int(value) except ValueError: return False else: ret...
def _ensure_iterable(x): """ If the object is iterable, return the object. Else, return the object in a length 1 list. """ return x if hasattr(x, "__iter__") else [x]
def sum_col(grid, col, row, size): """Sum values in column for rows - row:row + size.""" return sum( cur_row[col] for cur_row in grid[row:row + size] )
def ToPowerOfTwo(bits: int) -> int: """ Given a number, find the next power of two that is >= to the given value. Can be used to figure out a variable size given non-standard bit sizes in matter: eg. a int24 can be stored in an int32, so ToPortOfTwo(24) == 32. """ # probably bit manipulation c...
def _maybe_return_list(lst): """Return `lst` unless all of its elements are empty.""" if all(e is None for e in lst): return None else: return lst
def htmldec(text): """Decode HTML entities in the given text.""" chunks = text.split('&#') for i in range(1, len(chunks)): number, rest = chunks[i].split(';', 1) chunks[i] = chr(int(number)) + rest text = ''.join(chunks) text = text.replace('\xa0', ' ') text = text.replace('&nbsp...
def class_names2id(class_names, data): """Match class names to categoty ids using annotation in COCO format.""" category_ids = [] for class_name in class_names: for category_info in data['categories']: if category_info['name'] == class_name: category_ids.append(category_i...
def _get_opt_attr(obj, attr_path): """Returns the value at attr_path on the given object if it is set.""" attr_path = attr_path.split(".") for a in attr_path: if not obj or not hasattr(obj, a): return None obj = getattr(obj, a) return obj
def get_other_cluster(this_cluster, clusters): """Return the cluster in clusters, which is not this_cluster. Args: this_cluster (str): name of this_cluster clusters (list): list of two cluster names. Returns: the name of the other cluster. """ return clusters[0] if clusters...
def jump(inst_ptr, program, direction): """Jump the instruction pointer in the program until matching bracket""" count = direction while count != 0: inst_ptr += direction char = program[inst_ptr] if char == '[': count += 1 elif char == ']': count -= 1 ...
def to_gb(size: int): """ Convert size to formatted float representing Gigabytes. size should be an int of bytes.""" return round(size / 1024**3, 3)
def i_to_rgb(i, normalize=False): """Convert a number between 0.0 and 1.0 to an equivalent RGB tuple. Parameters ---------- i : float A number between `0.0` and `1.0`. normalize : bool, optional Normalize the resulting RGB values. Default is to return integer values ranging ...
def get_evaluations_and_evaluated(evaluations, evaluated_signatures): """Return a dictionary with the exams, students-signatures and evaluated students-signatures""" result = [] for exam_dict in evaluations: exam_data = {'exam': exam_dict['exam'], 'groups': exam_dict['groups'...
def _create_instance(row): """ Parse individual row of ARFF file in PHP dataset. If the row is from a tokens file, the first field must be a string of tokens optionally enclosed in single quotes. If the row is from a metrics file, it must be a comma- separated list of numbers. The last field must ha...
def last_number_in_circle_2(n, m): """ :param n: max number :param m:count m then pop :return: last number """ if n < 1 or m < 1: return -1 last = 0 for i in range(2, n + 1): last = (last + m) % i return last
def _check_sg_rules_for_port(rule, port_to_check): """ Verify if the security group rule accepts connections on the given port. :param rule: The rule to check :param port_to_check: The port to check :return: True if the rule accepts connection, False otherwise """ from_port = rule.get("From...
def _get_status_and_color(check, changed): """ Return a pair (status message, color) based if we are checking a file for correct formatting and if the file is supposed to be changed or not. """ if check: if changed: return 'Failed', 'red' else: return 'OK', 'g...
def digest_line(line): """ Lines are of the form Step A must be finished before step I can begin. Returns (A, I). """ return (line[5], line[36])
def minimum_distances(a): """Hackerrank Problem: https://www.hackerrank.com/challenges/minimum-distances/problem We define the distance between two array values as the number of indices between the two values. Given a, find the minimum distance between any pair of equal elements in the array. If no such va...
def celsius_to_fahrenheit(temp): """Converts temperature units C to F PARAMETERS ---------- temp : float Scalar temp in Celsius RETURNS ------- float Scalar temp in Fahrenheit """ return 9/5*temp + 32
def RACCU_calc(TOP, P, POP): """ Calculate RACCU (Random accuracy unbiased). :param TOP: test outcome positive :type TOP : int :param P: condition positive :type P : int :param POP: population :type POP : int :return: RACCU as float """ try: result = ((TOP + P) / (2 ...
def queues_has_items(queues): """helper function for checking if queue still has items""" for q in queues.values(): if len(q): return True else: return False
def get_text_unit_field(sample, biosample_name, field_to_fetch, is_list=False): """ This function will parse text and unit fields in biosamples :param sample: sample to parse :param biosample_name: name to use in biosample record :param field_to_fetch: text or unit to use :param is_list: does th...
def remove_all(str_list, element, ignore_cases=False): """removes all occurrences of element from string list and ignores optionally letter cases""" if ignore_cases: return [e for e in str_list \ if str(e).lower() != str(element).lower()] else: return [e for e in str...
def float_to_int_filter(v): """ Converts float (which might be passed as a string) to int E.g. 2.0 to 2 """ if v: try: return int(float(v)) except: return v return ""
def upto_sum(n): """Sum 1...n with built-in sum and range""" return sum(range(n))
def isolate_true(data): """Turn all Trues except the first into Falses in a run of Trues.""" data_backwards = data[::-1] x = [] for i in range(len(data) - 1): if data_backwards[i] and data_backwards[i+1]: x.append(0) else: x.append(data_backwards[i]) x.append(...
def count(items): """count(items) -> dict of counts of each item Count the number of times each item appears in a list of data. """ c = {} for i in items: c[i] = c.get(i, 0) + 1 return c
def color_blend(a, b): """ Performs a Screen blend on RGB color tuples, a and b """ return (255 - (((255 - a[0]) * (255 - b[0])) >> 8), 255 - (((255 - a[1]) * (255 - b[1])) >> 8), 255 - (((255 - a[2]) * (255 - b[2])) >> 8))
def singleton_ingredients(dishes, intersection): """ :param intersection: constant - one of (VEGAN_INTERSECTION,VEGETARIAN_INTERSECTION,PALEO_INTERSECTION, KETO_INTERSECTION,OMNIVORE_INTERSECTION) :param dishes: list of ingredient sets :return: set of single...
def lucas(n): """ this function has one parameter (n). this function should return the nth value in the fibonacci series. the function is implemented using recursion. The Lucas Numbers are a related series of integers that start with the values 2 and 1 rather than 0 and 1. The first few Lucas numbers ar...
def bmi_category(bmi): """ Function to calculate bmi category Parameters: bmi (float): BMI value Returns: bmi category (string) """ if bmi <= 18.4 : return "Underweight" elif bmi >=18.5 and bmi <= 24.9: return "Normal weight" elif bmi >=25 a...
def parse_dunder_line(string): """Take a line like: "__version__ = '0.0.8'" and turn it into a tuple: ('__version__', '0.0.8') Not very fault tolerant. """ # Split the line and remove outside quotes variable, value = (s.strip() for s in string.split('=')[:2]) value = va...
def gen_color(num_elems,max_elems): """ Generates a red color in 'dot' format, which tone is based in the number of elements of a cluster (more elements, more intense). @param num_elems: @param max_elems: @return: """ red_tone = num_elems / float(max_elems) color = "0.000 %....
def parseFileName(url): """Parses the file name from a given url""" pieces = url.split('/') return pieces[len(pieces)-1].replace("%20", " ")
def get_bool_from_text(text): """Check if we can convert this string to bool.""" if text.lower() in ['1', 'true', 'on']: return True elif text.lower() in ['0', 'false', 'off']: return False else: raise Exception("Unknown boolean text")
def processRequestCommand(command, languages): """ Argumets: command and the language Processes the Request command, verifies the type of the translation and the if the command is valid. """ command = command.split() #(request, language, t or f, words) try: translationTyp...
def upper(word: str) -> str: """ Will convert the entire string to uppercase letters >>> upper("wow") 'WOW' >>> upper("Hello") 'HELLO' >>> upper("WHAT") 'WHAT' >>> upper("wh[]32") 'WH[]32' """ # converting to ascii value int value and checking to see if char is a lower...
def list_to_str(block, delim=", "): """ Convert list to string with delimiter :param block: :param delim: :return: list_str """ list_str = "" for b in block: # print("processing:", block) if len(list_str) > 0: list_str = list_str + delim list_str = li...
def process_hash_tags(raw_hash_tags): """method that takes the hashtags from a dictionary and stores them in a list""" hashtag_list = list() for hash_tag in raw_hash_tags: text = hash_tag["text"] # Append the text of any included hashtags to our list hashtag_list.append(text) ...
def _babel_locale(locale): """Return the Babel locale code, given a normal one.""" # Babel uses underscore as separator. return locale.replace('-', '_')
def answer(n): """Sum of the all natural numbers less than n that are multiples of 3 or 5""" result = 0 for i in range(1, n): if i % 3 == 0 or i % 5 == 0: result = result + i return result
def load_data(object_byte_array): """ info: Loads bytes :param object_byte_array: bytearray :return: bytes """ number_size = object_byte_array[0] data_size = int.from_bytes(object_byte_array[1:number_size+1], byteorder="big") data = object_byte_array[number_size+1: number_size+1+data_siz...
def live_data2csv(dat, sep, header=True): """returns csv from live data dict""" # define columns and assemble header cols = ( "date", "weekday", "time", "value", "rawvalue", "unit", "range", "mode", "hold", "apo", "powe...
def recs_to_dict(keyfldname, recs): """Given an iterable of recs and a keyfldname, build and return a dictionary of records""" d = dict() for rec in recs: d[rec[keyfldname]] = rec return d
def meta_from_context(context): """ helper to extract meta values from a celery context """ meta_keys = ( 'correlation_id', 'delivery_info', 'eta', 'expires', 'hostname', 'id', 'reply_to', 'retries', 'timelimit', ) meta = dict() for name in meta_keys: value = context.get(nam...
def get_registry_image_tag(app_name: str, image_tag: str, registry: dict) -> str: """Returns the image name for a given organization, app and tag""" return f"{registry['organization']}/{app_name}:{image_tag}"
def show_fact_sheet_f(responses, derived): """ If one of the claimants earns over $150,000, Fact Sheet F is indicated. """ return derived['show_fact_sheet_f_you'] or derived['show_fact_sheet_f_spouse']
def add_even_sub_odd(operator, operand): """Add even numbers, subtract odd ones. See http://1w6.org/w6 """ try: for i, x in enumerate(operand): if x % 2: operand[i] = -x return operand except TypeError: if operand % 2: return -operand r...
def stripword(word): """ Split whitespace from a word """ for x in range(len(word)): word[x] = word[x].strip() return word
def template(string, values): """Apply a template""" for k, v in values.items(): try: string = string.replace(f"{{{k}}}", v) except Exception as e: print(f"Can't apply template for '{k}' with '{v}' -- {e}") return string
def topological_sort(unsorted_dict): """Sort objects by dependency. Sort a dict of obsoleting PID to obsoleted PID to a list of PIDs in order of obsolescence. Args: unsorted_dict : dict Dict that holds obsolescence information. Each ``key/value`` pair establishes that the PID in ...
def merge(this_po, that_po, replace_duplicates=False): """ Merge two pofiles. If `replace_duplicates` is set and there duplicate entries replace this with that. """ merged = this_po for entry in that_po: try: merged.append(entry) except ValueError: i...
def add_month(year, month, delta): """ Helper function which adds `delta` months to current `(year, month)` tuple and returns a new valid tuple `(year, month)` """ year, month = divmod(year * 12 + month + delta, 12) if month == 0: month = 12 year = year - 1 return year, month
def per_mode_small_36(x): """Takes Numeric Code and returns String API code Input Values: 1:"Totals", 2:"PerGame", 3:"Per36" Used in: """ measure = {1: "Totals", 2: "PerGame", 3: "Per36"} try: return measure[x] except: raise ValueError("Please enter a number between 1 and ...
def getFromDict(dataDict, mapList): """ Retrieves value from nested dict (dir_structure) using a list of keys https://stackoverflow.com/questions/14692690/access-nested-dictionary-items-via-a-list-of-keys """ for k in mapList: dataDict = dataDict.get(k, None) if dataDict is None: ...
def get_isbn10_checksum(isbn): """ Args: isbn (str/list): ISBN number as string or list of digits Warning: Function expects that `isbn` is only 9 digits long. Returns: int: Last (checksum) digit for given `isbn`. """ return sum([(i + 1) * x for i, x in enumerate(isbn)])...
def check_dups(li): """Checks duplicates in a list of ID values. ID values must be read in as a list. Author(s) -- Luc Anselin <anselin@uchicago.edu> Parameters ---------- li : list A collection of ID values. Returns ------- dups : list The duplicate IDs. "...
def getmaxv(n): """ Returns the maximum value of an unsigned n-bit integer. """ return 2**n - 1
def Insert(unused_op): """Shape function for Insert Op.""" return [[None], [None], [None]]
def _title_case(value): """ Return the title of the string but the first letter is affected. """ return value[0].upper() + value[1:]
def binary_card_generator(card_details): """ Stub card generator monkeypatched into the flight module for testing boarding card printing :param card_details: Boarding card details """ return "\n".join(card_details.values()).encode("utf-8")
def determine_interest(outstanding_balance: float, interest_rate: float) -> float: """Determine the interest of a mortgage. In a month in case the principal at start of the month is given by outstanding_balance and the interest rate is given by interest_rate (as decimal, annu...
def get_field_name(field_dict, field): """ Return a nice field name for a particular field Parameters ---------- field_dict : dict dictionary containing field metadata field : str name of the field Returns ------- field_name : str the field name """ ...
def factorial(n): """Compute basic factorial function Parameters ---------- n : integer Specifies the number to be factorial Returns ------- Float value of the product for all n """ if n == 0: return 1.0 else: return float(n) * f...
def cartesian( v1, v2 ): """ Helper function returns cartesian product of the two 'sets' v1, v2""" return tuple([(x,y) for x in v1 for y in v2])
def get_source_and_pgp_key(source_and_key): """Look for a pgp key ID or ascii-armor key in the given input. :param source_and_key: Sting, "source_spec|keyid" where '|keyid' is optional. :returns (source_spec, key_id OR None) as a tuple. Returns None for key_id if there was no '|' in the so...
def format_byte(size: int, decimal_places=3): """ Formats a given size and outputs a string equivalent to B, KB, MB, or GB """ if size < 1e03: return f"{round(size, decimal_places)} B" if size < 1e06: return f"{round(size / 1e3, decimal_places)} KB" if size < 1e09: return...
def find_join_loads(cls, extend_fields): """find_join_loads: find the relationships from extend_fields which we can call joinloads for EagerLoad...""" def _relations_(c, exts): if not exts: return None ret = [] r = exts.pop(0) if r in c.__mapper__.relationshi...
def ifirst_is_not(l, v): """ Return index of first item in list which is not the specified value. If the list is empty or if all items are the specified value, raise a ValueError exception. Parameters ---------- l : sequence The list of elements to be inspected. v : object ...
def _get_address_mode(field, db_server, family): """Retrieves the address mode if populated on the DB entry""" for entry in getattr(db_server, 'address_modes', []): if entry.family == family: return entry.mode return None
def parse_param(param, forced_device=None): """ Extract account representation string format is <account_name>@<domain_name>[@<device_name>] If @<device_name> is absent, <domain_name> is a global domain name Else <domain_name> is a local domain name of the forced_device if 'forced_device' is ...
def _do_get_file_map(file_tree): """Reduces a tree of folders and files into a list of (<sha256>, <file_metadata>) pairs """ file_map = [] stack = [file_tree] while len(stack): tree_node = stack.pop(0) if tree_node['kind'] == 'file': file_map.append((tree_node['extra']['h...
def quicksort(lst): """Recursive function to order a list quickly.""" if len(lst) < 2: return lst else: midpoint = len(lst)/2 L = quicksort(lst[midpoint::]) R = quicksort(lst[::midpoint]) return lst
def kdelta(i,j): """ returns the Kroneker Delta of two variables """ if i==j: q = 1 else: q = 0 return q
def bsr(value, bits): """ bsr(value, bits) -> value shifted right by bits This function is here because an expression in the original java source contained the token '>>>' and/or '>>>=' (bit shift right and/or bit shift right assign). In place of these, the python source code below contains cal...
def bits_to_bytes(num_bits): """compute bitstring length in bytes from number of blocks""" return (num_bits + 7) >> 3
def segment_lists_are_equal(val1, val2): """ Returns True if the two lists hold the same set of segments, otherwise returns False. """ if len(val1) != len(val2): return False val1.sort() val2.sort() if val1 is None: # get rid of this later -- we don't any empty dict values! ...
def add_to_divide(number, divisor): """ this function returns the int needed to be added to number to make it divisable by divisor""" tmp = number%divisor if tmp == 0: return 0 return divisor - tmp
def distm(p1, p2): """ Returns manhattan distance divided by the default NYC speed. NOT admissible. Parameters: (p1, p2) p1 - (lat, lon) p2 - (lat, lon) """ return abs(p1[0] - p2[0]) + abs(p1[1] - p2[1]) / 65
def vec2name(ndes, natom): """ get index of the first feature for each element """ v = [] for i in range(natom): v += [ndes * i] return v
def make_rect(width, height): """ Makes a rectangle on x-y plane to be drawn with GL_TRIANGLES_FAN """ return [[0, 0, 0], [0, height, 0], [width, height, 0], [width, 0, 0]]
def note_name(p): """Returns note name of pitch Notebook: C3/C3S1_SpecLogFreq-Chromagram.ipynb Args: p (int): Pitch value Returns: name (str): Note name """ chroma = ['A', 'A$^\\sharp$', 'B', 'C', 'C$^\\sharp$', 'D', 'D$^\\sharp$', 'E', 'F', 'F$^\\sharp$', 'G', '...
def trade_duration_map_nb(record): """`map_func_nb` that returns trade duration.""" return record['exit_idx'] - record['entry_idx']
def decode_iberian(line, encoding, fmt="simplified"): """ Use an iberian JSON encoding to decode a text into one of the supported output formats (dual, simplified or SVG): line:list: list of symbols encoding:json: encoding infomation fmt:str: output format (simplified, dual or iberi...
def round_up(n, size): """ Round an integer to next power of size. Size must be power of 2. """ assert size & (size - 1) == 0, "size is not power of 2" return ((n - 1) | (size - 1)) + 1
def get_compounds(equation): """Extract compound entries from an equation. Parameters ---------- equation : str Equation string. Returns ------- list of str Compounds extracted from the left side of equation. list of str Compounds extracted from the right side o...