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 """ if tick_val >= 1000000000: val = round(tick_val/1000000000, 1) new_tick_format = '{:}B'.format(val) elif tick_val >= 1000000: val = round(tick_val/1000000, 1) new_tick_format = '{:}M'.format(val) elif tick_val >= 1000: val = round(tick_val/1000, 1) new_tick_format = '{:}K'.format(val) elif tick_val < 1000: new_tick_format = round(tick_val, 1) else: new_tick_format = tick_val return str(new_tick_format)
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]: return True elif value in ["0", "false", "False", False]: return False raise ValueError('Invalid bool representation "%s" provided.' % value)
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 in dic[key]: for lol in key.split(","): val.append(lol) return val
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 = [mp_xy_entry[0] for mp_xy_entry in control_dict['mp xy']] mp_xy_files_found = all([fn in fits_filenames for fn in mp_location_filenames]) mp_location_xy = [(item[1], item[2]) for item in control_dict['mp xy']][:2] flatten_mp_location_xy = [y for x in mp_location_xy for y in x] mp_xy_values_ok = all([x > 0.0 for x in flatten_mp_location_xy]) return mp_xy_files_found, mp_xy_values_ok
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 of integers to be sorted. Returns: numbers (list): sorted list. iterations (int): number of iterations the algorithm took to sort the list. Args: numbers (list): list of integers to be sorted. Returns: numbers (list): sorted list. """ size = len(numbers) iterations = 0 for i in range(size): iterations += 1 j = i while j > 0: iterations += 1 if numbers[j] < numbers[j - 1]: numbers[j], numbers[j - 1] = numbers[j - 1], numbers[j] j -= 1 return numbers, iterations
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 with filename turned into lowercase string stripped of numbers and extensions (e.g. 'Boston_terrier_02259.jpg' => ['boston terrier']) """ name_list = filename.split("_")[:-1] for idx in range(0, len(name_list)): name_list[idx] = name_list[idx].lower() return [" ".join(name_list)]
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 NOT break words and you can choose a custom suffix. """ if text is None: return '' # Return the string itself if length is smaller or equal to the limit if len(text) <= max_length: return text # Cut the string value = text[:max_length] # Break into words and remove the last words = value.split(' ')[:-1] # Join the words and return return ' '.join(words) + suffix
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"} if weekday in weekday_names: return weekday_names[weekday] else: raise KeyError("Can't find the weekday name.") exit(1)
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: return True
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 can be faster, but this should be ok as well result = 1 while result < bits: result = result * 2 return result
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;', ' ') text = text.replace('&lt;', '<') text = text.replace('&gt;', '>') text = text.replace('&quot;', '"') text = text.replace('&amp;', '&') return text
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_info['id']) return category_ids
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[1] == this_cluster else clusters[1]
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 else: pass return inst_ptr
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 from 0 to 255. Returns ------- tuple The RGB values of the color corresponding to the provided number. If `normalize` is true, the RGB values are normalized to values between 0.0 and 1.0. If `normalize` is false, the RGB values are integers between 0 and 255. Examples -------- >>> i_to_rgb(1.0) (255, 0, 0) >>> i_to_rgb(0.75) (255, 255, 0) >>> i_to_rgb(0.5) (0, 255, 0) >>> i_to_rgb(0.25) (0, 255, 255) >>> i_to_rgb(0.0) (0, 0, 255) >>> i_to_rgb(1.0, True) (1.0, 0.0, 0.0) >>> i_to_rgb(0.75, True) (1.0, 1.0, 0.0) >>> i_to_rgb(0.5, True) (0.0, 1.0, 0.0) >>> i_to_rgb(0.25, True) (0.0, 1.0, 1.0) >>> i_to_rgb(0.0, True) (0.0, 0.0, 1.0) """ i = max(i, 0.0) i = min(i, 1.0) if i == 0.0: r, g, b = 0, 0, 255 elif 0.0 < i < 0.25: r, g, b = 0, int(255 * (4 * i)), 255 elif i == 0.25: r, g, b = 0, 255, 255 elif 0.25 < i < 0.5: r, g, b = 0, 255, int(255 - 255 * 4 * (i - 0.25)) elif i == 0.5: r, g, b = 0, 255, 0 elif 0.5 < i < 0.75: r, g, b = int(0 + 255 * 4 * (i - 0.5)), 255, 0 elif i == 0.75: r, g, b = 255, 255, 0 elif 0.75 < i < 1.0: r, g, b, = 255, int(255 - 255 * 4 * (i - 0.75)), 0 elif i == 1.0: r, g, b = 255, 0, 0 else: r, g, b = 0, 0, 0 if not normalize: return r, g, b return r / 255.0, g / 255.0, b / 255.0
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']} for exam_eval_dict in evaluated_signatures: if exam_eval_dict['exam'] == exam_dict['exam']: exam_data['evaluated_groups'] = exam_eval_dict['groups'] result.append(exam_data) return result
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 have values 'yes' or 'no, which are mapped to the integers 1 and 0, respectively. Args: row: String representing an individual row of an ARFF file in the PHP dataset. Returns: List of the form [features, label], where features is a list of features (tokens or metrics data) and label is an integer having the value 1 if the last field of the row is 'yes' and '0' otherwise. """ assert row.count('\'') in [0,2] mod_row = row.split('\''); # Rows with multiple tokens are wrapped in single quote marks. Otherwise, # they are separated by commas. if row.count('\'') == 2: mod_row = row.split('\'')[1:]; else: mod_row = row.split(','); assert (len(mod_row) == 2), "mod row: {}".format(mod_row) return [mod_row[0].replace('\'', ''), 1 if 'yes' in mod_row[1] else 0]
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("FromPort") to_port = rule.get("ToPort") ip_protocol = rule.get("IpProtocol") # if ip_protocol is -1, all ports are allowed if ip_protocol == "-1": return True # tcp == protocol 6, # if the ip_protocol is tcp, from_port and to_port must >= 0 and <= 65535 if (ip_protocol in ["tcp", "6"]) and (from_port <= port_to_check <= to_port): return True return False
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', 'green' else: if changed: return 'Fixed', 'green' else: return 'Skipped', 'yellow'
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 value exists, print -1. Args: a (list): list of integers to check Returns: int: the minimum distance between any pair of equal elements, or -1 """ if len(set(a)) == len(a): return -1 smallest_distance = len(a) values = {} for idx, val in enumerate(a): if val in values: distance = idx - values[val] if distance < smallest_distance: smallest_distance = distance values[val] = idx return smallest_distance
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 * POP))**2 return result except Exception: return "None"
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 this record allow to use multiple values :return: parsed biosample record """ if is_list: tmp = list() if biosample_name in sample['characteristics']: for item in sample['characteristics'][biosample_name]: tmp.append(item[field_to_fetch]) return tmp else: if biosample_name in sample['characteristics']: return sample['characteristics'][biosample_name][0][field_to_fetch] else: return ''
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_list if e != element]
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(data[0]) return x[::-1]
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 singleton ingredients Each dish is represented by a `set` of its ingredients. Each `<CATEGORY>_INTERSECTION` is an `intersection` of all dishes in the category. The function should return a `set` of ingredients that only appear in a single dish. """ singletons = (dish - intersection for dish in dishes) return set.union(*singletons)
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 are: 2, 1, 3, 4, 7, 11, 18, 29, 47, 76, 123, .... """ if n == 0: return 2 elif n == 1: return 1 else: return lucas(n - 1) + lucas(n - 2)
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 and bmi <= 29.9: return "Overweight" elif bmi >=30 and bmi <= 34.9: return "Moderately obese" elif bmi >= 35 and bmi <= 39.9: return "Severely obese" elif bmi > 40: return "Very severely obese"
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 = value[1:-1].strip() return variable, value
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 %.3f 1.000"%(red_tone) # print color return color.lower()
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: translationType = command[2] # argumento t ou f do request numberLanguage = int(command[1]) #neste caso linguagem message = "UNQ "+ languages[numberLanguage-1] +"\n" if translationType == 't': numberWords = len(command[3:]) if numberWords == 0: print("Bad format: no words to translate") return ["Wrong UNQ format\n",0,0] return [message, translationType, numberWords] elif translationType == 'f': filename = command[3] return [message, translationType, filename] else: return ["Wrong UNQ format\n",0,0] except IndexError: print('Request is not correctly formulated or you need to call the list command first') return ["Wrong UNQ format\n",0,0] except ValueError: #print('Wrong argument format\n') return ["Wrong UNQ format\n",0,0]
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 letter # if it is a capital letter it is getting shift by 32 which makes it a capital case letter return "".join( chr(ord(char) - 32) if 97 <= ord(char) <= 122 else char for char in word )
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 = list_str + str(b) return list_str
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) return hashtag_list
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_size] del object_byte_array[:number_size+1+data_size] return data
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", "power", "view", "memstat", "mem_no", "read_no", ) csv = [] if header: csv = [sep.join(cols)] csv.append(sep.join(([str(dat[col]) for col in cols]))) return "\n".join(csv)
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(name) # Skip this key if it is not set if value is None: continue # Skip `timelimit` if it is not set (it's default/unset value is `(None, None)`) if name == 'timelimit' and value == (None, None): continue # Skip `retries` if it's value is `0` if name == 'retries' and value == 0: continue # prefix the tag as 'celery' tag_name = 'celery.{}'.format(name) meta[tag_name] = value return meta
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 return operand
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 ``key`` identifies an object that obsoletes an object identifies by the PID in ``value``. Returns: tuple of sorted_list, unconnected_dict : ``sorted_list``: A list of PIDs ordered so that all PIDs that obsolete an object are listed after the object they obsolete. ``unconnected_dict``: A dict of PID to obsoleted PID of any objects that could not be added to a revision chain. These items will have obsoletes PIDs that directly or indirectly reference a PID that could not be sorted. Notes: ``obsoletes_dict`` is modified by the sort and on return holds any items that could not be sorted. The sort works by repeatedly iterating over an unsorted list of PIDs and moving PIDs to the sorted list as they become available. A PID is available to be moved to the sorted list if it does not obsolete a PID or if the PID it obsoletes is already in the sorted list. """ sorted_list = [] sorted_set = set() found = True unconnected_dict = unsorted_dict.copy() while found: found = False for pid, obsoletes_pid in list(unconnected_dict.items()): if obsoletes_pid is None or obsoletes_pid in sorted_set: found = True sorted_list.append(pid) sorted_set.add(pid) del unconnected_dict[pid] return sorted_list, unconnected_dict
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: if not replace_duplicates: raise ValueError( "Found duplicate entry: '{}'".format(entry.msgid)) this_entry = merged.find( entry.msgid, include_obsolete_entries=True) this_entry.msgstr = entry.msgstr return merged
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 " + str(len(measure)))
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: break return dataDict
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)]) % 11
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. """ dups = list(set([x for x in li if li.count(x) > 1])) return dups
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, annual). """ return outstanding_balance * interest_rate / 12
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 """ if 'standard_name' in field_dict: field_name = field_dict['standard_name'] elif 'long_name' in field_dict: field_name = field_dict['long_name'] else: field_name = str(field) field_name = field_name.replace('_', ' ') field_name = field_name[0].upper() + field_name[1:] return 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) * factorial(n - 1)
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 source_and_key string. """ try: source, key = source_and_key.split('|', 2) return source, key or None except ValueError: return source_and_key, None
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 f"{round(size / 1e6, decimal_places)} MB" return f"{round(size / 1e9, decimal_places)} GB"
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__.relationships.keys(): ret.append(r) r1 = _relations_(c.__mapper__.relationships[r].mapper.class_, exts) if r1: ret.extend(r1) return ret if not extend_fields: return None result = list() for x in extend_fields: y = _relations_(cls, x.split('.')) if y: result.append('.'.join(y)) return result
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 The value not to be matched. Example: -------- >>> ifirst_is_not(['a', 'b', 'c'], 'a') 1 """ try: return next((i for i, _ in enumerate(l) if _ is not v)) except StopIteration: raise ValueError('There is no matching item in the list.')
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 not None <device_name> should be empty or equal to forced_device Else <device_name> can be another device """ parsed = param.rsplit("@", 2) if len(parsed) > 1: account_name = parsed[0] domain_name = parsed[1] if (len(parsed) == 3 and parsed[2] and forced_device and (parsed[2] != forced_device)): return None device_name = (forced_device or parsed[2]) if len(parsed) == 3 \ else None return account_name, domain_name, device_name else: return None
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']['hashes']['sha256'], tree_node)) else: stack = stack + tree_node['children'] return file_map
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 calls to this function. Copyright 2003 Jeffrey Clement. See pyrijnadel.py for license and original source :param value: Value :param bits: Bits """ if bits < 0 or bits > 31: raise ValueError('bad shift count') if bits == 0: return value minint = -2147483648 if bits == 31: if value & minint: return 1 return 0 tmp = (value & 0x7FFFFFFE) // 2**bits if value & minint: tmp |= (0x40000000 // 2 ** (bits - 1)) return tmp
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! if val2 is not None: return False elif val2 is None: if val1 is not None: return False for i in range(len(val1)): if val1[i] != val2[i]: return False return True
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', 'G$^\\sharp$'] name = chroma[(p - 69) % 12] + str(p // 12 - 1) return name
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 iberian) Returns a string (dual or simplied) or a list of strings (iberan)""" output = [] for current_chr in line: if current_chr < 0: current_chr = 0 for dict_chr in encoding: if dict_chr["id"] == current_chr: output.append(dict_chr[fmt]) if fmt != "iberian": output = "".join(output) return output
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 of equation. Examples -------- C00068 + C00001 <=> C01081 + C00009 C00029 + C00001 + 2 C00003 <=> C00167 + 2 C00004 + 2 C00080 G10481(n+1) + G10620 <=> G10481(n) + G11108 C17207(n) + (n-2) C00009 <=> C20861 + (n-2) C00636 """ res = [] for side in equation.split(' <=> '): cpds = [] for field in side.split(' + '): idx = field.find('C') if idx >= 0: cpd = field[idx:idx + 6] if len(cpd) == 6 and cpd[1:].isdigit(): cpds.append(cpd) res.append(sorted(set(cpds))) return res