content
stringlengths
42
6.51k
def deepmixdicts(*dicts): """ Deeply mix dictionaries. >>> deepmixdicts( ... {'a': 1, 'b': 2, 'sub': {'x': 1, 'y': 2, 'sub': {'v': 1}}}, ... {'a': 2, 'c': 3, 'sub': {'x': 2, 'z': 3, 'sub': {'v': 2}}}, ... ) == { ... 'a': 2, 'b': 2, 'c': 3, ... 'sub': { ... 'x...
def int2round(src): """ returns rounded integer recursively :param src: :return: """ if isinstance(src, float): return int(round(src)) elif isinstance(src, tuple): res = [] for i in range(len(src)): res.append(int(round(src[i]))) return tuple(res)...
def do_classtype_lookup_as2type(asn_query, d_as2type_data): """ Execute lookup into CAIDA as2type and return Org type. """ return d_as2type_data[asn_query][1]
def handle_includes(defns): """Recursive handling of includes for any input list of defns. The assumption here is that when an include is handled by the pyyaml reader, it adds them as a list, which is stands apart from the rest of the expected YAML definitions. """ newdefns = [] for d in def...
def prep_rg_names(item, config, fc_name, fc_date): """Generate read group names from item inputs. """ if fc_name and fc_date: lane_name = "%s_%s_%s" % (item["lane"], fc_date, fc_name) else: lane_name = item["description"] return {"rg": item["lane"], "sample": item["descri...
def get_channel_name(sample_rate, is_acceleration=True, is_vertical=False, is_north=True): """Create a SEED compliant channel name. SEED spec: http://www.fdsn.org/seed_manual/SEEDManual_V2.4_Appendix-A.pdf Args: sample_rate (int): Sample rate of sensor in Hz. is_accele...
def do_apply(ctx, lst): """Given a list, do apply""" if len(lst) == 1: return lst[0] if len(lst) == 2: return ctx['ap('](lst[-2], lst[-1]) return do_apply(ctx, lst[:-2] + [do_apply(ctx, lst[-2:])])
def risk_level(value): """ Returns a string based risk level from a number. 1: Low 2: Medium 3: Medium 4: High """ if value == 1: return 'low' if value == 2 or value == 3: return 'medium' if value == 4: return 'high'
def unpack_tensor_from_indices(inputs, indices): """Separated from function above because it can be useful in the case were a packed_sequence.data has been modified (ex, through a neural network) but is not an instance of packed_sequence anymore.""" outputs = [inputs[indices[i]] for i in range(len(indic...
def extract_keys(dic, keys): """Return two copies of the dict. The first has only the keys specified. The second has all the *other* keys from the original dict. :: >> extract_keys({"From": "F", "To": "T", "Received", R"}, ["To", "From"]) ({"From": "F", "To": "T"}, {"Received": "R"}) ...
def remove_config_prefix(config, prefix, skip=None): """Iterate over keys in dict and remove given prefix. Arguments --------- config : dict The configuration data. prefix : str The prefix to remove. skip : List[str], optional A list of keys which should not be altered. ...
def deg_to_qt(deg): """ Converts from degrees to QT degrees. 16 deg = 1 QTdeg Parameters ---------- deg : float The value to convert. Returns ------- float The value converted. """ # Angles for Qt are in units of 1/16 of a degree return deg * 16
def tokenize(lines, token='word'): """Split text lines into word or character tokens. Defined in :numref:`sec_utils`""" assert token in ('word', 'char'), 'Unknown token type: ' + token return [line.split() if token == 'word' else list(line) for line in lines]
def helper(n, x, ans): """ :param n: int, original input :param x: int, numbers of digit :param ans: int, the largest digit return: This function will return the largest digit. """ digit = pow(10, x) # numbers of digit # base case: finish examining all the digits if n // digit == 0: return ans else: ...
def _custom_tbl_dtype_compare(dtype1, dtype2): """This is a custom equality operator for comparing table data types that is less strict about units when unit is missing in one and dimensionless in the other. """ for d1, d2 in zip(dtype1, dtype2): for k in set(list(d1.keys()) + list(d2.keys(...
def massage_error_list(error_list, placeholder_description): """ Returns a best-effort attempt to make a nice error list """ output_error_list = [] if error_list: for error in error_list: if not error.get('message'): output_error_list.append({'message': error, 'er...
def make_comma_list_a_list(elements_to_rocess): """Process a list with commas to simple list. For example: ['elem1','elem2,elem3'] => ['elem1', 'elem2', 'elem3'] :param elements_to_rocess: list to process :return: processed list with elemnts separated """ output_list = [] for element i...
def walk(node1, node2, parent_name=''): """Walk through each node in tree and compare difference""" diff_results = [] if type(node1) != type(node2): return (["[Type] {} vs {}".format(node1, node2)], False) elif type(node1) not in [list, dict] and type(node2) not in [list, dict]: retur...
def get_items_except(seq, indices, seq_constructor=None): """Returns all items in seq that are not in indices Returns the same type as parsed in except when a seq_constructor is set. """ sequence = list(seq) index_lookup = dict.fromkeys(indices) result = [sequence[i] for i in range(len(seq)) \ ...
def cat2(l): """ %timeit cat2(slist) 10000 loops, best of 3: 23.3 us per loop """ l = l * 100 slist = [x for x in l] return ''.join(slist)
def write_data_file(data, filename): """Compile lines into a file.""" data_file = open(filename, 'w') # write for line in data: assert type(line) == type([]) assert all(type(item) == type('') for item in line) data_line = ' '.join(line) + '\n' # join together and add a carriage retur...
def syllable_count(word): """Calculates and returns the number of syllables in a given word""" count = 0 vowels = "aeiouy" if word[-1] in ".,?!": word = word[:-1] word = word.lower() if word[0] in vowels: count += 1 for i in range(1, len(word)): if word[i] in vowels ...
def correct_score(list_of_possible_mvs, probable_mvs): """ Corrects original scores by comparing string distance to probable_mvs INPUT: list_of_possible_mvs: ex: [(mv, 0.3), (branch, 0.2)] probable_mvs: ex ['nan', 'none'] OUTPUT: list_of_possible_mvs: ex[(nan, 0.9), (branch,...
def human_readable_time(seconds): """Returns human readable time :param seconds: Amount of seconds to parse. :type seconds: string. """ seconds = int(seconds) hours = seconds / 3600 seconds = seconds % 3600 minutes = seconds / 60 seconds = seconds % 60 return "{:02....
def max_n_consecutive_1s(binary_str): """This function takes a number's binary representation and return the maximum number of consecutive 1 digits in the string. Parameters ---------- binary_str : str Binary representation of an integer. Returns ------- max_n_1s : int ...
def unpack_error_data(data): """Unpack the dictionary-like structure used in Error and Notice responses. keys are 1 character codes followed by a String. A '\0' key signals the end of the data.""" pos = 0 result = {} while pos < len(data): k = data[pos] if k == '\0': ...
def get_account_info(connection_string): """Get Account info from a connection string.""" account_name = connection_string.split(";")[1].split("=")[-1] account_key = connection_string.split(";")[2].replace("AccountKey=", "") return (account_name, account_key)
def deparameterize(inp, sep='+'): """ Somewhat-undo parameterization in string. Replace separators (sep) with spaces. :param inp: (str) :param sep: (str) default: '+' :return: "deparameterized" string """ return inp.replace(sep, ' ')
def replace_string_contents(raw_string, renaming_dictionary): """ Takes a string and replaces it with any changes provided in a renaming dictionary :param raw_string: a raw string with which to pass through the renaming dictioanary :param renaming_dictionary: a dictionary containing keys to be replaced ...
def remove_xa0(text): """Remove weird hex texts""" return text.replace("\xa0", " ")
def isnumeric(a): """ Returns ``True`` is an array contains numeric values. :param array a: An array. :return: bool """ import numpy as np if type(a) == str: return False if np.issubdtype(a.dtype, np.number): return True return False
def skip_special_members(app, what, name, obj, skip, options): """Skip some special members in the documentation.""" skip_modules = ['__module__', '__doc__', '__dict__', '__weakref__', '__init__', '_params'] if name in skip_modules: return True else: return False
def combine_privacy_values(user_privacy_value: float, data_point_privacy_value: float) -> float: """ Combine privacy values of user and user for data point Parameters ---------- user_privacy_value privacy value of user data_point_privacy_value privacy value of user for a data point ...
def validate_enum(datum, schema, **kwargs): """ Check that the data value matches one of the enum symbols. i.e "blue" in ["red", green", "blue"] Parameters ---------- datum: Any Data being validated schema: dict Schema kwargs: Any Unused kwargs """ retur...
def determine_range(prices): """Approximates the range to eliminate accessories""" max_price = prices[0] for x in range(1, len(prices)): if prices[x] > max_price: max_price = prices[x] min_price = 100000000 for x in range(0, len(prices)): if prices[x] < min_price an...
def _validate_data_codons(dataset): """ Helper function to validate user input as codon sequence. """ if len(dataset) % 3 != 0: return -1
def get_len(filename): """get len of wordtype from the filename""" return int(filename.rstrip('.pt').split('len')[-1])
def boundary_distance(i: int, elv: float, n: int) -> float: """Calculates the distance of the boundaries to an elevated origin point :param i: index of the boundary of interest :type i: int :param elv: elevation of the point :type elv: float :param n: distance granularity :type n: int :...
def rem(x, a): """ x: a non-negative integer argument a: a positive integer argument returns: integer, the remainder when x is divided by a. """ if x == a: return 0 elif x < a: return x else: return rem(x-a, a)
def make_links_dict(pairs_dict): """ Creates links_dict by pruning pairs_dict to a single best link for each scaffold end """ links_dict = {} for end1 in pairs_dict: if (end1 in pairs_dict) and (len(pairs_dict[end1])) > 0: best_pair = max(pairs_dict[end1], key = p...
def rotate_90(grid): """ Rotate a given grid by 90 degrees. Args: grid: Grid to rotate. Returns: Grid after being rotated by 90 degrees. """ new_grid = [] for col, _ in enumerate(grid): new_row = [] # Go through the rows, # and form new rows dependin...
def find_max_subarray_linear(A, low, high): """ Find the max subarray in O(n) # Also listed as Ex4.1-5 :param A: array :param low: leftmost index of the array :param high: rightmost index of the array :return: leftmost index of the max crossing subarray ...
def time_switch(x): """ Convenience codes to convert for time text to pandas time codes. """ return { 'min': 'Min', 'mins': 'Min', 'minute': 'Min', 'minutes': 'Min', 'hour': 'H', 'hours': 'H', 'day': 'D', 'days': 'D', 'week': 'W', ...
def extract_top_level_dict(current_dict): """ Builds a graph dictionary from the passed depth_keys, value pair. Useful for dynamically passing external params :param depth_keys: A list of strings making up the name of a variable. Used to make a graph for that params tree. :param value: Param value :...
def spherical_index_k(l, m=0): """ returns the mode k from the degree l and order m """ if not -l <= m <= l: raise ValueError('m must lie between -l and l') return l*(l + 1) + m
def _build_module_seperator(module, submodule=''): """ Creates a string line with a seperator for module and submodule. Args: - module (String): Name of the module for the seperator - submodule (String): Name of the submodule for the seperator (default: empty string) Returns: ...
def find_test_index(test, selected_tests, find_last_index=False): """Find the index of the first or last occurrence of a given test/test module in the list of selected tests. This function is used to determine the indices when slicing the list of selected tests when ``options.first``(:attr:`find_last_index...
def activate(line, active='none'): """Checks if we are reading nodes, elements, or something else Parameters ---------- line : string The line to check for activation Returns ------- active : string 'nodes' if we are going to read nodes, 'elems' if we...
def cartesian_to_ccw_from_north(angle): """ angle minus 90, in degrees""" return angle - 90;
def letters_only(s): """ :param s: string of characters (could be a word or a set of words separated by delimiters) \ :type s: str \ :returns: s without any delimiter, space, or punctuation \ :rtype:str :Example: >>> from bstools import bstools >>> a = "Hello World !" >>> letters_only(a) ...
def classpath(klass): """Return the full class path Args: klass (class): A class """ return f"{klass.__module__}.{klass.__name__}"
def UV_transmision(zenith, obstruction, SVF): """ This function is used to estimate the percentage of UV radiation reaching the street canyons based on hemispherical images and the sun path, there are two major parts of UV radiation reaching the ground, direct beam and diffusion the direct be...
def _deep_update(main_dict, update_dict): """Update input dictionary with a second (update) dictionary https://stackoverflow.com/questions/3232943/update-value-of-a-nested-dictionary-of-varying-depth Parameters ---------- main_dict: dict Input dictionary update_dict: d...
def get_num_layer_for_replknet(var_name): """ Divide [2, 2, 18, 2] layers into 12 groups; each group is 2 RepLK BLocks + 2 ConvFFN blocks, including possible neighboring transition; adapted from https://github.com/microsoft/unilm/blob/master/beit/optim_factory.py """ # num_max_layer = 12 # ...
def factorial_iterative(n): """ :param n: Integer :return: n * n-1 * n-2 * n-3.......1 """ fac = 1 for i in range(n): fac = fac * (i + 1) return fac
def decodeDegreesStr(valStr): """ Return a signed latitude/longitude value from a string. Only copes with the integer values used in grid cell names. """ val = int(valStr[:-1]) if valStr[-1] in ("S", "W"): val = -val return val
def intersperse(ls, elem, first=False, last=False): """ Args: ls: A list of elements elem: The element to insert in between each element first: Whether to add the element at the beginning of the sequence last: Whether to add the element at the end of the sequence Returns: ...
def get_callable_name(c): """ Get a displayable name for the callable even if __name__ is not available. """ try: return c.__name__ + '()' except: return str(c)
def allowed_file(filename): """ Utility function that checks that the filename has an allowed extension. Used when uploading the file. Checks the module-level variable `ALLOWED_EXTENSIONS` for allowed uploads. :param filename: The name of the file that is being uploaded. :type filename:...
def get_ban_query(bans, team, enemy): """ Helper function for ban query """ ban_query = "(" if bans != None: for ban in bans: ban_query += """(Matchup!="{}") AND """.format(ban) for t in list(team.values()): if t != "": ban_query += """(Matchup!=...
def generateDimText(dim,dataType): """ This is used to generate a string with the new dimensions of the array """ text="" for d in dim: text=text+" ["+str(d)+" x" text=text+" "+dataType+("]"*len(dim)) return text
def normalize(columns, atts): """Creates an output record according to the columns schema from a set of attributes. Args: columns: the columns of the output record. atts: the attribute values of the output record. Returns: row: a normalized row ready for dataframe integration. ...
def normalize_url(url): """If passed url doesn't include schema return it with default one - http.""" if not url.lower().startswith('http'): return 'http://%s' % url return url
def flattenList(listOfLists): """ flatten 2D list return [1, 2, 3, 4, ...] for input [[1, 2], [3, 4, ...], ...] """ return [item for subList in listOfLists for item in subList]
def check_directions(y, x, lst): """ Check all directions of a seat for the first seen seats. Args: y: The column index of the seat. x: The row index of the seat. list: The list the seat is in. Returns: The sum of the first visible occupied seats in all eight di...
def get_item_charge(amount_of_items: int) -> float: """ This function calculates extra item fee and adds it to delivery fee. --- Args: amount_of_items (int): amount of items in the basket Returns: item_charge (float): fee for extra items """ item_limit = 5 free_items...
def convert_float(string): """Convert string into a float, otherwise return string.""" try: return float(string) except (ValueError, TypeError): return string
def _psd_params_checker(params): """Utility function to check parameters to be passed to `power_spectrum`. Parameters ---------- params : dict or None Optional parameters to be passed to :func:`mne_features.utils.power_spectrum`. If `params` contains a key which is not an option...
def intersection(lst1, lst2): """ >>> intersection([1, 2, 3], [2, 4, 6]) [2] >>> intersection([1, 2, 3], [4, 5, 6]) [] >>> intersection([2, 3, 2, 4], [2, 2, 4]) [2, 4] """ in_both = [] for item1 in lst1: for item2 in lst2: if item1 == item2 and item2 not in i...
def title_case(title, minor_words=''): """ Converts a string into title case, given an optional list of exceptions (minor words). :param title: a string of words. :param minor_words: a string of words. :return: the title in title case form. """ return " ".join(x.capitalize() if x not in mino...
def acc_stats(stats_list): """Accumulate a list of sufficient statistics. Parameters ---------- stats_list : list List of sufficient statistics. Returns ------- stats : dict Accumulated sufficient statistics. """ new_stats = {} for stats in stats_list: ...
def _get_sm_proj_id(proj: str, namespace='main'): """ Matching the project ID to a sample-metadata project. """ if proj == 'csiro-als': # We don't have a project for ALS yet proj = 'nagim' if namespace != 'main': proj = f'{proj}-test' return proj
def _has_missing_exe_output(output: str) -> bool: """Take output and check for exe missing errors""" if "is not recognized as an internal or external command" in output: return True # AOD linux match if ": not found" in output: return True return False
def sort(nodes, total_order, dedup=False): """Sorts nodes according to order provided. Args: nodes: nodes to sort total_order: list of nodes in correct order dedup: if True, also discards duplicates in nodes Returns: Iterable of nodes in sorted order. """ total_order_idx = {} for i, nod...
def get_epoch_num_from_model_file_name(model_file_name): # Unchanged from original work """ :param model_file_name: string """ return int(model_file_name.split("_")[2].split(".")[0])
def is_point_in_rect_circular_boundary(distance, circular_radius, boundary_range): """ judge whether a point is in boundary area for top center rect """ if distance < circular_radius + boundary_range: return True else: return False
def wrap_argument(text): """ Wrap command argument in quotes and escape when this contains special characters. """ if not any(x in text for x in [' ', '"', "'", '\\']): return text else: return '"%s"' % (text.replace('\\', r'\\').replace('"', r'\"'), )
def overlap(x1, w1, x2, w2): """ :param x1: center_x :param w1: bbox_w :param x2: center_x :param w2: bbox_w :return: """ l1 = x1 - w1 / 2.0 l2 = x2 - w2 / 2.0 left = l1 if l1 > l2 else l2 r1 = x1 + w1 / 2.0 r2 = x2 + w2 / 2.0 right = r1 if r1 < r2 else r2 ret...
def remove_heterotachy_info(l): """Remove any information in brackets - ete3 does not support this format of newick""" # --- Ensure tree is NaN value, if so return NoTree --- if type(l) == float: return "NoTree" if ("[" not in l) and ("]" not in l): return l open_brackets = [...
def createdecryptedfilename(filename): """ Determine a filename to save the decrypted diskimage to. """ i = filename.rfind(".") if i<0: return filename + "-decrypted" return filename[:i] + "-decrypted" + filename[i:]
def get_chunk_type(tok, idx_to_tag): """ Args: tok: id of token, ex 4 idx_to_tag: dictionary {4: "B-PER", ...} Returns: tuple: "B", "PER" """ tag_name = idx_to_tag[tok] tag_class = tag_name.split('-')[0] tag_type = tag_name.split('-')[-1] return tag_class, tag_t...
def stripnull(string): """Return string truncated at first null character. Clean NULL terminated C strings. >>> stripnull(b'string\\x00') b'string' """ i = string.find(b'\x00') return string if (i < 0) else string[:i]
def copyfile(infile, outfile, chunksize=8192): """Read all data from infile and write them to outfile. """ size = 0 while True: chunk = infile.read(chunksize) if not chunk: break outfile.write(chunk) size += len(chunk) return size
def force_str_2_bool(bool_str, raise_if_unknown=False): """convent 'True' or 'False' to bool, using on query_param""" if bool_str in ["True", "true"]: return True elif bool_str in ["False", "false"]: return False if raise_if_unknown: raise ValueError("str should be 'True/true' o...
def is_backtrack(previous_label, next_label): """If we've already processes a header with 22(c) in it, we can assume that any following headers with 1111.22 are *not* supposed to be an analysis of 1111.22""" previous_label = previous_label or [] next_label = next_label or [] trimmed = previous_l...
def int_to_balt(n): """ Convert an integer to a list of its digits in balanced ternary """ D = [] while n != 0: n,r = divmod(n,3) if r == 2: n += 1 D.append(-1) else: D.append(r) return tuple([i for i in reversed(D)])
def chain_max_non_cyclables(non_cyclables, cyclabe_increase: int, minimal_cyclable: int): """ clean the non_cyclables so that each chain has only one value, the highest, and each value below minimal is removed :param non_cyclables: the disequalities whether we allow taking the cycle :param cyclabe_incre...
def clamp(value, min_value, max_value): """Clamps the given value between min and max""" if value > max_value: return max_value if value < min_value: return min_value return value
def index_table_from_name_table(elements, name_table): """Converts a table (list of lists) of strings into a table (list of lists) of ints.""" return [[elements.index(elem_name) for elem_name in row] for row in name_table]
def image_alt_value_passthrough(image, *args, **kwargs): """Passthrough replacement for v1.jinja2tags.image_alt_value. This is needed because, as written, the info unit template assumes that it will get passed a Wagtail image object. We want to pass a dict which contains the various image properties, i...
def search_list(l, k, v): """Search a list for an entry with a specific value.""" for item in l: if k not in item: continue if item[k] == v: return item return None
def get_orthogonal_scope_name(backbone_name): """Returns scope name of convolutions for orthogonal regularization. :param backbone_name: Name of backbone :return: Name of scope """ if backbone_name == 'rmnet' or backbone_name == 'twinnet': return 'dim_red' elif backbone_name == 'shuffl...
def capitalLettersCipher(ciphertext): """ Returns the capital letters in the ciphertext Example: Cipher Text: dogs are cuter than HorsEs in a LooP. Decoded Text: HELP """ return "".join([i for i in ciphertext if i.isupper()])
def _handle_to_bytearray(handle): """Packs the 16-bit handle into a little endian bytearray""" assert handle <= 0xFFFF assert handle >= 0 return bytearray([handle & 0xFF, (handle >> 8) & 0xFF])
def dict_from_mappings(data, mappings): """create a dict in Activitypub format, using mappings supplies by the subclass""" result = {} for mapping in mappings: # sometimes there are multiple mappings for one field, don't # overwrite earlier writes in that case if mapping.local_fi...
def parse_physloc_adapter_output(output): """ Parses the physical location command output from an IVM command. :param output: The output from an IVM physical loction command :returns: The output formatted into a dictionary """ # Output example: # ['ent4:Virtual I/O Ethernet Adapter (l-lan):...
def autoalign(netapi, selection): """ Autoalign nodes or nodespaces.""" if len(selection) == 1: # if there's only one item selected, we assume it's a nodespace # so we align its contents. If it's not, we return an error try: nodespace = netapi.get_nodespace(selection[0]) ...
def gcd(x, y): """ assume always x > y :param x: :param y: :return: gcd value """ if x < y: z = x x = y y = z if y == 0: print(f'gcd = {x}\n') return x else: print(f'{x} = {(x - x % y) / y}*{y} + {x % y}') return gcd(y, x % y)
def int2bytes(a, b): """ Converts a given integer value (a) its b-byte representation, in hex format. :param a: Value to be converted. :type a: int :param b: Byte size to be filled. :type b: int :return: The b-bytes representation of the given value (a) in hex format. :rtype: hex str ""...
def relu(x: float) -> float: """A testing implementation of relu.""" if x < 0: return 0 return x