content
stringlengths
42
6.51k
def egcd(a, b): """extended GCD returns: (s, t, gcd) as a*s + b*t == gcd >>> s, t, gcd = egcd(a, b) >>> assert a % gcd == 0 and b % gcd == 0 >>> assert a * s + b * t == gcd """ s0, s1, t0, t1 = 1, 0, 0, 1 while b > 0: q, r = divmod(a, b) a, b = b, r s0, s1, t0, t1...
def dump_datetime(value): """Deserialize datetime object into string form for JSON processing.""" if value is None: return None return value.strftime("%Y-%m-%dT%H:%M:%S.000Z")
def parse_input(input_string): """Return `input_string` as an integer between 1 and 6. Check if `input_string` is an integer number between 1 and 6. If so, return an integer with the same value. Otherwise, tell the user to enter a valid number and quit the program. """ if input_string.strip() i...
def bisect(a, x, lo=0, hi=None, cmp=lambda e1, e2: e1 < e2): """ a simplified and generalized version of python's bisect package: https://docs.python.org/3.6/library/bisect.html return the index where to insert item x in a list a a must be sorted (in ascending order) the return value i is such that...
def onefunction(a, b: int = 4): """ Return the addition of ``a+b``. :param a: first element :param b: second element :return: ``a + b`` :raises TypeError: if a and b have different types. """ if type(a) != type(b): raise TypeError("Different type {0} != {1}".format(a, b)) re...
def add_attrib(attrib, ptext): """ Insert an attribute into some html text Input: attrib -- text of the attribute to be added. ptext -- snippet of html code in which to insert the attribute. Returns the text with the attribute added. """ bloc = ptext.find('>') if bloc <= 0:...
def get_size(num_bytes, suffix="B"): """ Scale bytes to its proper format e.g: 1253656 => '1.20MB' 1253656678 => '1.17GB' """ factor = 1024 for unit in ["", "K", "M", "G", "T", "P"]: if num_bytes < factor: return f"{num_bytes:.2f}{unit}{suffix}" num_by...
def set_up_folder_name_1M ( model_file , date_run ): """ Produce log_file, plot_folder based on model_file (file name ending with _sd.pt) If model_file is epoch_1_sd.pt, date_run is 0913: plot_folder 'plot_2d_epoch_1', log file 'log_0913_2d_epoch_1' """ # if model_file == '': model_pure = f'ep{ep_in...
def union_crops(crop1, crop2): """Union two (x1, y1, x2, y2) rects.""" x11, y11, x21, y21 = crop1 x12, y12, x22, y22 = crop2 return min(x11, x12), min(y11, y12), max(x21, x22), max(y21, y22)
def python_text(text="is cool"): """prints Python is cool""" text = text.replace("_", " ") return "Python %s" % text
def calculate_int(row): """ Calculates the integer value of a binary String """ #Special case, if we are just given an integer if (type(row) == type(1)): return row res = 0 row = list(reversed(row)) for r in range(len(row)): if row[r] == 1: res = res + 2**r retur...
def menu_footer(context): """Footer navigation menu""" admin_email = context['ADMIN_EMAIL'] site_name = context['SITE_NAME'] return { 'SITE_NAME': site_name, 'ADMIN_EMAIL': admin_email, }
def verify_keyid_is_v4(signing_key_fingerprint): """Verify that the keyid is a v4 fingerprint with at least 160bit""" return len(signing_key_fingerprint) >= 160/8
def parse_list_of_dicts(result, feature, fields): """Parse list of dictionaries""" items = [] if feature in result and result[feature]: for _dict in result[feature]: item = [] for field in fields: item.append(str(_dict[field]) if field in _dict else '') ...
def _rowcol_to_id(row, column, dim): """Convert row,column to ID""" return row*(dim**2) + column
def badAddEm(somelist): """ try to return sum of numbers in somelist but something goes wrong... """ total = 0 for num in somelist: total = total + num return total
def _pad_version(v_list: list, l: int) -> list: """ pad the list at the end with 0 value, but if last component is dev or post, the padding is before the last""" if l > 0: last = None if v_list[-1].startswith("dev") or v_list[-1].startswith("post"): last = v_list[-1] v_l...
def int_to_string(message): """ Converts integer message into string. - **Arguments** :message: integer message """ char_list = "" for x in range(0, len(message)): char_list += chr(message[x]) return char_list
def can_write_read(read_and_alignment, current_position): """Returns true if the first read in the cache can safely be written. This will be the case if the read was not the first in a set of reads with the same alignment, or if the current position has gone beyond the last base covered in that alignmen...
def regular_number(num): """.""" txt = str(num) regular_num = '' for index, char in enumerate(txt[::-1]): regular_num += char if (index + 1) % 3 == 0 and index + 1 != len(txt): regular_num += ',' regular_num = regular_num[::-1] return regular_num
def truncate_or_pad(sequence, block_size, pad_token_id): """Adapt the source and target sequences' lengths to the block size. If the sequence is shorter we append padding token to the right of the sequence. """ if len(sequence) > block_size: return sequence[:block_size] else: sequenc...
def calc_average(lst): """ Driver Code lst = [15, 9, 55, 41, 35, 20, 62, 49] average = calc_average(lst) """ return sum(lst) / len(lst)
def checksum(s, m): """Create a checksum for a string of characters, modulo m""" # note, I *think* it's possible to have unicode chars in # a twitter handle. That makes it a bit interesting. # We don't handle unicode yet, just ASCII total = 0 for ch in s: # no non-printable ASCII chars, including space...
def strshape(shape, broadcast=None): """ Helper function to convert shapes or list of shapes into strings. """ if shape is None: return str(shape) if not isinstance(shape, tuple): raise TypeError('Invalid shape.') if len(shape) == 0 and broadcast in ('leftward', 'rightward'): ret...
def isFn(fn): """ Is argument a function @public @param {*} fn @return {bool} """ return hasattr(fn, '__call__')
def _get_prefixes(response): """ return lists of strings that are prefixes from a client.list_objects() response """ prefixes = [] if 'CommonPrefixes' in response: prefix_list = response['CommonPrefixes'] prefixes = [prefix['Prefix'] for prefix in prefix_list] return prefixes
def verify_only_from(pam_rhost, only_from): """Verify 'only_from' response conditions. :param pam_rhost: received pam_rhost parameter :param only_from: allowed host(s) from config file :return: True/False """ return only_from and pam_rhost and \ pam_rhost in [host.strip() for host in o...
def get_parameter(kwargs, key, default=None): """ Get a specified named value for this (calling) function The parameter is searched for in kwargs :param kwargs: Parameter dictionary :param key: Key e.g. 'loop_gain' :param default: Default value :return: result """ if kwargs is None: ...
def get_failed_set(y_true, y_pred): """ Get incorrect/failed records from the ground truth & predict values. :param y_true: ground truth values :type y_true: iterable :param y_pred: predicted values :type y_pred: iterable :return: the culled y_true & y_pred lists :rtype: list, list ...
def flatten(lst): """ Flattens list recursively @public @param {list} lst @return {list} """ if lst == []: return lst if isinstance(lst[0], list): return flatten(lst[0]) + flatten(lst[1:]) return lst[:1] + flatten(lst[1:])
def map_fields(record, fields): """ creates a dict of field name => value for the supplied record """ result = {} pos = 0 for curr in fields: field_name = curr[0] value = record[pos] result[field_name] = value pos += 1 return result
def _n_to_state_data_map(state_lines_data): """Returns a map from N (state index) -> State (list of state line data) where N uses the convention of the *.lpt files (beginning at 1 instead of 0) :param state_lines_data: list of state line data """ nb_map = dict() for cbl in state_lines...
def resolve_url(url, prefixes): """Resolve the urls of form 'prefix:name'""" if ":" in url: prefix, _, tail = url.partition(":") if prefix in prefixes: return prefixes[prefix] + tail return url
def strain_extent(strain): """Returns the GPS `[start, end)` interval covered by a strain meta dict """ starts, ends = zip(*[ (meta["GPSstart"], meta["GPSstart"] + meta["duration"]) for meta in strain ]) return min(starts), max(ends)
def Recalibrate(LastNum): """ Picks the proper limit number based on LastNum in order to obtain a multiple of 6. """ # The LastNum must be a multiple of 6!! # This selects the proper case in the dictionnary based on LastNum % 6 # Example: if Num % 6 == 2, add 4 return { 0: LastNu...
def num_frames(length, fsize, fshift): """Compute number of time frames of spectrogram """ pad = (fsize - fshift) if length % fshift == 0: M = (length + pad * 2 - fsize) // fshift + 1 else: M = (length + pad * 2 - fsize) // fshift + 2 return M
def is_serializable(obj: object) -> bool: """ Checks if object is serializable. Args: obj: object to test Returns (bool): serializable indicator """ return hasattr(obj, '__serialize__')
def tanimoto(v1, v2): """Calculates the ratio of the intersection of both sets to the union set""" c1, c2, shr = 0, 0, 0 for i in range(len(v1)): if v1[i] != 0: c1 += 1 if v2[i] != 0: c2 += 1 if v1[i] != 0 and v2[i] != 0: shr += 1 return 1.0 ...
def make_album(artist_name, album_title, tracks_number=""): """Return dictionary containing album info.""" if tracks_number: return { 'artist_name': artist_name, 'album_title': album_title, 'tracks_number': tracks_number, } return { 'a...
def remove_suffix(filenames, suffix): """This function removes the suffix from every name in the set filenames and returns a set with the new file names inputs: filenames - a set with all the filenames suffix - the suffix to be added to the filenames output new_fi...
def group_loss(image_groups, losses): """ :param image_groups: list of array, each array is contain the same class' image id :param losses: list of dict, dict: 'image_id': int 'mask_loss':tensor :return: """ loss_groups = [] for array in image_groups: loss_group = [] for ima...
def convert_query_params(qd): """ Expand a dictionary of query parameters by turning "list" values into multiple pairings of key with value. Args: qd (dict): A mapping of parameter names to values. Returns: list: A list of query parameters, each one a tuple containing name and value, a...
def greatest_profit(array: list): """given array return the maximum profit from one buy and sell the following algorithm does so in O(N) time """ minimum_price = array[0] maximum_price = array[0] greatest_profit = 0 for price in array: if price < minimum_price: minimum_price = price maximum_price = pr...
def unfold_indices(obj, indices): """Unfolds an index chain and returns the corresponding item""" original_obj = obj for depth, idx in enumerate(indices): try: obj = obj[idx] except IndexError: raise IndexError( "IndexError while accessing an item from...
def calc_check_digit(number): """Calculate the check digit for the number.""" alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ' cutoff = lambda x: x - 9 if x > 9 else x s = sum( cutoff(alphabet.index(n) * 2) if i % 2 == 0 else alphabet.index(n) for i, n in enumerate(number[::-1])) re...
def pad_texts(texts, padding_word="<PAD/>", max_length = None): """ Pads all sentences to the same length. The length is defined by the longest sentence. Returns padded sentences. """ sequence_length = max(len(x) for x in texts) if max_length is None else max_length padded_texts = [] for i i...
def just_three(nums): """ Returns largest in nums when given exactly three elements. Won't work on all problem instances. """ if len(nums) != 3: raise ValueError('I only work on lists of size 3.') if nums[1] < nums[0]: if nums[2] < nums[1]: return nums[0] if n...
def values(table, row, columns): """ Formats and converts row into database types based on table schema. Args: table: table schema row: row tuple columns: column names Returns: Database schema formatted row tuple """ values = [] for x, column in enumerate(c...
def is_checked(chkbox_state): """ Connect to a checkbox stateChanged Args: chkbox_state (int): """ switch = {0: False, 2: True} return switch.get(chkbox_state)
def _get_byte_at_index(value, index): """ """ # NOTE: We could also use int.to_bytes to just convert # value into a byte array. return value >> index * 8 & 0xFF
def dbref(inp, reqhash=True): """ Converts/checks if input is a valid dbref. Args: inp (int, str): A database ref on the form N or #N. reqhash (bool, optional): Require the #N form to accept input as a valid dbref. Returns: dbref (int or None): The integer part of t...
def CalcValueToMB(value): """Returns MB""" return value/1024.0/1024.0
def convert_string_to_html(string): """Change characters to HTML friendly versions.""" return string.replace('&', '&amp;')
def build_slack_message(feedback_type, feedback_text): """ Configures the message we will post to slack. :param feedback_type: :param feedback_text: :return: """ print( '[module: feedback_intent]', '[method: build_slack_message]', 'feedback type and text received:', ...
def lines_for_reconstruction(unicode_text): """Split unicode_text using the splitlines() str method, but append an empty string at the end if the last line of the original text ends with a line break, in order to be able to keep this trailing line end when applying LINE_BREAK.join(splitted_lines). ...
def list_from_json_dict(json_dict): """ This function converts a dictionary to a list by transforming each key/value pair of the dictionary into a tuple. This tuple is in the format: (dictionary_key, dictionary_value). If one of the dictionary keys has multiple tags, then we split them and c...
def try_parse_num_and_booleans(num_str): """ Tries to parse the provided string as a number or boolean :param num_str: :return: """ if isinstance(num_str, str): # bool if num_str.lower() == 'true': return True elif num_str.lower() == 'false': retur...
def gen_tf(tokens): """ Given a segmented string, return a dict of tf. """ # tokens = text.split() total = len(tokens) tf_dict = {} for w in tokens: tf_dict[w] = tf_dict.get(w, 0.0) + 1.0 for k in tf_dict: tf_dict[k] /= total return tf_dict
def union(a, b): """ return the union of two lists """ return list(set(a) | set(b))
def sqlite3_quote_name(name): """Quote `name` as a SQL identifier, e.g. a table or column name. Do NOT use this for strings, e.g. inserting data into a table. Use query parameters instead. """ # XXX Could omit quotes in some cases, but safer this way. return '"' + name.replace('"', '""') + '"'
def factorial(n): """Does this function work? Hint: no.""" n_fact = n while n > 1: n -= 1 n_fact *= n return n_fact
def get_etc_shadow_salt(string: str): """Returns the salt found within the line retreived from the /etc/shadow file Examples: >>> line_from_etc_shadow = 'root:$1$umqC71l2$370xDLmeGD9m4aF/ciIlC.:14425:0:99999:7:::'\n >>> get_etc_shadow_salt(line_from_etc_shadow)\n 'umqC71l2' Referen...
def markdown_comment(ext): """Markdown escape for given notebook extension""" return '' if ext in ['.Rmd', '.md'] else "#'" if ext == '.R' else "#"
def create_disconnect_request_message(source_peer_id, target_peer_id): """ creates a disconnect request message :param source_peer_id: peer id of source peer :param target_peer_id: peer id of target peer :return: disconnect request message as string (formatted like defined in protocol) """ r...
def get_tolerance_min_max(value, expected_tolerance): """ Get minimum and maximum tolerance range Args: value(int): value to find minumum and maximum range expected_tolerance ('int'): Expected tolerance precentage Returns: minimum and maximum value of tol...
def _unique_in_order(seq): """ Utility to preserver order while making a set of unique elements. Copied from Markus Jarderot's answer at https://stackoverflow.com/questions/480214/how-do-you-remove-duplicates-from-a-list-in-whilst-preserving-order Args: seq : sequence Returns: ...
def RPL_MOTD(sender, receipient, message): """ Reply Code 372 """ return "<" + sender + ">: " + message
def _get_interval_domain_min(dom): """ Get the lower bound of an interval domain Args: dom: Domain Returns: Domain min value """ return dom[0] if isinstance(dom, tuple) else dom
def make_data_files(f): """(f) -> None""" with open(f, 'w') as files: return files.close()
def permutations(string): """ :param: input string Return - list of all permutations of the input string """ if len(string) == 0: return [''] last_char = string[-1] str_perm = permutations(string[:-1]) new_list = [] for i in range(len(str_perm)): substr = str_perm[i...
def bounds(sizes): """Convert sequence of numbers into pairs of low-high pairs >>> bounds((1, 10, 50)) [(0, 1), (1, 11), (11, 61)] """ low = 0 rv = [] for size in sizes: rv.append((low, low + size)) low += size return rv
def like_escape(s): """ Escape characters in ``s`` that have special meaning to SQL's ``LIKE`` """ return s.replace('\\', r'\\').replace('%', r'\%').replace('_', r'\_')
def concat_cols(row, columns_to_concat): """ concat function """ if len(columns_to_concat) > 1 : return ", ".join( row[col] for col in columns_to_concat ) else : return row[columns_to_concat[0]]
def group_data_dict(data: dict, by_key: object, ignore_case: bool = False) -> dict: """Parameter 'data': - A dict with entity ids as keys and entity info as values. """ if data: result = {} for key, entry in data.items(): entry_value = entry[by_key] if ignore_case:...
def make_context(db_bench_obj: dict, extr_name: str, fname: str, evars: dict) -> dict: """ Make a context dict for db_bench output files. """ return { "rocks_ver": db_bench_obj["rocks_ver"], "date": db_bench_obj["date"], "memtable_rep": db_bench_obj["memtable_rep"], ...
def validate_max_results(value): """Raise exception if number of endpoints or IPs is too large.""" if value and value > 100: return "have length less than or equal to 100" return ""
def christmas_gifts(gifts, maximum_price): """ IMPORTANT: You should NOT use loops or list comprehensions for this question. Instead, use lambda functions, map, and/or filter. Given a list of tuples (Gift, Price), return the list of presents you bought. You should buy any present the price of...
def PowerStack_Calc(Power, N): """ Calculate power_stack. :param Power: single cell power [W] :type Power : float :param N: number of single cells :type N : int :return: power stack [W] as float """ try: result = N * Power return result except TypeError: ...
def parse_expression(value, native_data_types=False): """ Optionally parse an expression Args: native_data_types (:obj:`bool`, optional): whether to return new_values in their native data types Returns: :obj:`object`: expression or parsed expression """ if native_data_types: ...
def should_update_bounds(activation_bound_update_freq, activation_bound_start_step, step): """Returns whether activation bounds should be updated. Args: activation_bound_update_freq: How frequently to update bounds after the initial bounds update. A value of '-1' indicates to not...
def output_table_for(table_id): """ Get the name of the table where results of the union will be stored :param table_id: name of a CDM table :return: name of the table where results of the union will be stored """ return 'unioned_ehr_' + table_id
def equal_but_for_ellipses(got, want): """Compare two strings, but match "..." to zero or more characters""" ellipsis = "..." # Cut trailing whitespace from the comparisons given = got.rstrip() musts = want.rstrip().split(ellipsis) # Require each fragment between "..." ellipses, in order ...
def change(syllable): """ Function that returns the original form of a syllable """ if "1" in syllable: syllable = syllable.replace("1", "ch") elif "2" in syllable: syllable = syllable.replace("2", "hu") elif "3" in syllable: syllable = syllable.replace("3", "sh") eli...
def my_factorial1(n): """ >>> my_factorial1(1) 1 >>> my_factorial1(0) 1 >>> my_factorial1(-1) 1 >>> my_factorial1(5) 120 """ if n < 2: return 1 else: return n * my_factorial1(n - 1)
def insertGame(gtitle: str, release_date: str="0000-00-00") -> str: """Return a query to insert a game into the database.""" return (f"INSERT IGNORE INTO game (title, release_date) " f"VALUES ('{gtitle}', '{release_date}');" )
def is_keypress(k): """ Is this input event a keypress? """ if isinstance(k, str): return True
def represent_path(field: str): """A path field starts or and its name with path and an underscore""" return field.lower().startswith('path_') or field.lower().endswith('_path')
def get_name(last_name, first_name): """ Get name from last name and first name, if the name is in alpha, then use whitespace as the connect between them. :param last_name: Last name :param first_name: First name :return: last name + connect + first name, """ connect = '' if str(...
def fibR(n): """ :param n: :return: """ if n == 1 or n == 2: return 1 return fibR(n - 1) + fibR(n - 2)
def remove_zeros(list): """Remove zeros from the list passed. Requires the list of integers. """ list2 = [] for index in range(len(list)): if list[index]: list2.append(list[index]) return list2
def simplify_model_name(name: str) -> str: """ Converts upper case to lower case and appends '-' :param name: Model name :return: Simplified model name """ final_name = name[0].lower() for char in name[1:]: if char.isupper(): final_name += f'-{char.lower()}' else...
def parse_label( label ): """ Parses a label into a dict """ res = {} clazz, instance_num, room_type, room_num, area_num = label.split( "_" ) res[ 'instance_class' ] = clazz res[ 'instance_num' ] = int( instance_num ) res[ 'room_type' ] = room_type res[ 'room_num' ] = int( room_num ) res...
def encode(number, base): """Encode given number in base 10 to digits in given base. number: int -- integer representation of number (in base 10) base: int -- base to convert to return: str -- string representation of number (in given base)""" # Handle up to base 36 [0-9a-z] assert 2 <= base <= ...
def get_change(money: int): """ Greggy implementation used by cashiers for getting change. :param money: the amount we need change for :return: the minimum number of coins """ min_coins = 0 while money >= 10: min_coins += 1 money -= 10 while money >= 5: min_coi...
def average(values): """Computes the arithmetic mean of a list of numbers >>> print(average([10, 20, 30])) 20 """ return sum(values) / len(values)
def cm2inch(*tupl): """Convert from cm to inches. Matplotlib uses inches as default unit. Conversion supports tuples as the figsize option for figure. """ inch = 2.54 if isinstance(tupl[0], tuple): return tuple(i/inch for i in tupl[0]) else: return tuple(i/inch for i in tup...
def map(function, list): """ Given a function and a list, return the list of the results of applying function(item) on all items """ return [function(item) for item in list]
def _server_prefix(environ): """ Get the server_prefix out of tiddlyweb.config. """ config = environ.get('tiddlyweb.config', {}) return config.get('server_prefix', '')
def isInAssociation(element, iterable): """ A wrapper for 'is in' which returns true if `iterable` is None If `iterable` is None, then we accept all elements """ if iterable is None: return True if type(iterable) is str: return element['Moving group'] == iterable return elem...
def sanitize_mobile_number(number): """Add country code and strip leading zeroes from the phone number.""" if str(number).startswith("0"): return "+254" + str(number).lstrip("0") elif str(number).startswith("254"): return "+254" + str(number).lstrip("254") else: return number