content
stringlengths
42
6.51k
def merge_dicts(*dict_args): """ Given any number of dicts, shallow copy and merge into a new dict, precedence goes to key value pairs in latter dicts. """ # source: # http://stackoverflow.com/questions/38987/how-to-merge-two-python-dictionaries-in-a-single-expression result = {} for ...
def make_divisors(n, reversed=False): """create list of divisors O(root(N)) Args: number (int): number from which list of divisors is created reversed (bool, optional): ascending order if False. Defaults to False. Returns: list: list of divisors """ divisors = set()...
def _min(*args): """Returns the minimum value.""" return min(*args)
def f1x_p(x, p): """ General 1/x function: :math:`a + b/x` Parameters ---------- x : float or array_like of floats independent variable p : iterable of floats parameters (`len(p)=2`) - `p[0]` = a - `p[1]` = b Returns ------- float functio...
def color_based_on_operation(data, matching_criteria, matching_color, not_matching_color): """ :param data: :param matching_criteria: :param matching_color: :param not_matching_color: :return: """ color_associated = list(map(lambda x: matching_color if matching_criteria(x) else not_matc...
def decint2binstr(n): """Convert decimal integer to binary string. """ if n < 0: return '-' + decint2binstr(-n) s = '' while n != 0: s = str(n % 2) + s n >>= 1 return s or '0'
def map_to_parent(t_class, parents_info_level): """ parents_info_level: {<classid>: [parent]}, only contains classid that has a super-relationship """ if t_class in parents_info_level: assert len(parents_info_level[t_class]) < 2, f"{t_class} has two or more parents {parents_info_level[t_class]}...
def _parse_constraint(expr_string): """ Parses the constraint expression string and returns the lhs string, the rhs string, and comparator """ for comparator in ['==', '>=', '<=', '>', '<', '=']: parts = expr_string.split(comparator) if len(parts) == 2: # check for == because...
def GetHotkey(text): """Return the position and character of the hotkey""" # find the last & character that is not followed # by & or by the end of the string curEnd = len(text) + 1 text = text.replace("&&", "__") while True: pos = text.rfind("&", 0, curEnd) # One found was at ...
def returnYear(date): """ Return the year """ y = str(date)[:4] x = int(y) return x
def merge_args_and_kwargs(param_names, args, kwargs): """Merges args and kwargs for a given list of parameter names into a single dictionary.""" merged = dict(zip(param_names, args)) merged.update(kwargs) return merged
def run(result): """Function to test empty dict return""" ret = {} return ret
def divide(x, y): """Divide function""" if y == 0: raise ValueError("Cannot divide by 0") return x / y
def sqrt(number): """ Calculate the floored square root of a number Args: number(int): Number to find the floored squared root Returns: int: Floored Square Root """ if number is None or number < 0: return None if number * number == number or number == 1: retu...
def lsearch(l,pattern): """ Search for items in list l that have substring match to pattern. """ rvals = [] for v in l: if not v.find(pattern) == -1: rvals.append(v) return rvals
def parse_config_sections(conf, section_defs): """Parse the sections of the configuration file Args: conf (dict): Loaded configuration file information section_defs (dict): Mapping of configuration file values and defaults Returns: (dict): Final configuration to use with the script...
def fail(string: str) -> str: """Add fail colour codes to string Args: string (str): Input string Returns: str: Fail string """ return "\033[91m" + string + "\033[0m"
def is_user_defined_new_style_class(obj): """Returns whether or not the specified instance is a user-defined type.""" return type(obj).__module__ != '__builtin__'
def isotopeMaxBD(isotope): """Setting the theoretical max BD shift of an isotope (if 100% incorporation). Parameters ---------- isotope : str name of isotope Returns ------- float : max BD value """ psblIsotopes = {'13C' : 0.036, '15N' : 0.016} ...
def _calculate_slope(x_data): """Calculate the trend slope of the data :param x_data: A list of the result percentages, e.g. [98, 54, 97, 99] :type x_data: list :rtype float: """ if all(x == 100 for x in x_data): return 100 y_data = list(range(len(x_data))) x_avg = sum(x_data) ...
def defaults(obj, *sources): """ Assigns properties of source object(s) to the destination object for all destination properties that resolve to undefined. Args: obj (dict): Destination object whose properties will be modified. sources (dict): Source objects to assign to `obj`. Ret...
def clean_material_name(material_name): """Make sure the material name is consistent.""" return material_name.lower().replace('\\', '/')
def expand_grid(grid): """Expand grid by one in every direction.""" new_length = len(grid) + 2 row = [0 for _ in range(new_length)] new_grid = [[0] + row + [0] for row in grid] return [row[:]] + new_grid + [row[:]]
def _atomic_symbol(anum): """ convert atomic number to atomic symbol """ anum2asymb = ['X', 'H', 'HE', 'LI', 'BE', 'B', 'C', 'N', 'O', 'F', 'NE', 'NA', 'MG', 'AL', 'SI', 'P', 'S', 'CL', 'AR', 'K', 'CA', 'SC', 'TI', 'V', 'CR', 'MN', 'FE', 'CO', 'NI', 'CU', 'ZN', ...
def dict_difference(one, two): """ Return new dictionary, with pairs if key from one is not in two, or if value of key in one is another then value of key in two. """ class NotFound: pass rv = dict() for key, val in one.items(): if val != two.get(key, NotFound()): ...
def tup_to_vs(tup): """tuple to version string""" return '.'.join(tup)
def make_grid_row(length): """Create a row of length with each element set to value.""" row = [] for _ in range(0, length): row.append(False) return row
def uniq_list(in_list): """ Takes a list of elements and removes duplicates and returns this list :param in_list: Input list :return: List containing unique items. """ seen = set() result = [] for item in in_list: if item in seen: continue seen.add(item) result.append(item) return result
def mean_and_median(values): """Gets the mean and median of a list of `values` Args: values (iterable of float): A list of numbers Returns: tuple (float, float): The mean and median """ mean = sum(values) / len(values) midpoint = int(len(values) / 2) if len(values) % 2 == 0: ...
def strip_space(tokens): """ strip spaces """ return [t.strip() for t in tokens]
def is_sorted(l): """Checks if the list is sorted """ return all(l[i] <= l[i+1] for i in range(len(l)-1))
def implode(exploded): """Convert a list of lists representing a screen display into a string.""" return '\n'.join([''.join(row) for row in exploded])
def slope_to_pos_interp(l: list) -> list: """Convert positions of (x-value, slope) pairs to critical pairs. Intended for internal use. Inverse function of `pos_to_slope_interp`. Result ------ list [(xi, yi)]_i for i in len(function in landscape) """ output = [[l[0][0], 0]] ...
def _local(tag): """Extract the local tag from a namespaced tag name (PRIVATE).""" if tag[0] == '{': return tag[tag.index('}') + 1:] return tag
def compute_padding(J_pad, T): """ Computes the padding to be added on the left and on the right of the signal. It should hold that 2**J_pad >= T Parameters ---------- J_pad : int 2**J_pad is the support of the padded signal T : int original signal support size Ret...
def flttn(lst): """Just a quick way to flatten lists of lists""" lst = [l for sl in lst for l in sl] return lst
def isTerminated( lines ): """Given .cpp/.h source lines as text, determine if assert is terminated.""" x = " ".join(lines) return ';' in x \ or x.count('(') - x.count(')') <= 0
def parse_slate(slate): """Parses slate document Args: slate (dict): slate document Returns: dict """ wanted = ['_id', 'slateTypeName', 'siteSlateId', 'gameCount', 'start', 'end', 'sport'] return {k: slate[k] for k in wanted}
def main( argv ): """ Script execution entry point @param argv Arguments passed to the script @return Exit code (0 = success) """ # return success return 0
def piecewise_attractor_function(x, max_positive=1.0, max_negative=0.5): """ This shunts the input to one value or the other depending on if its greater or less than 0.5. :param x: x-value :return: y-value """ if x < 0.5: return max_positive else: return -max_negative
def validate_inferred_freq(freq, inferred_freq, freq_infer): """ If the user passes a freq and another freq is inferred from passed data, require that they match. Parameters ---------- freq : DateOffset or None inferred_freq : DateOffset or None freq_infer : bool Returns ------...
def squared(x): """ Input: x, float or int Base value Output: float, base to the power 2. """ return float(x) * float(x)
def update_h_w_curr(h_rem, w_rem): """Helper function to downsample h and w by 2 if currently greater than 2""" h_curr, w_curr = min(h_rem, 2), min(w_rem, 2) h_rem = h_rem // 2 if h_rem > 1 else 1 w_rem = w_rem // 2 if w_rem > 1 else 1 return h_rem, w_rem, h_curr, w_curr
def fileExtension(filename): """Returns file extension if exists Arguments: filename (str): file name Returns: str: file extension or None """ if not isinstance(filename, str): return None fext = filename.split('.') if len(fext) < 2: re...
def create_fixed_income_regex(input_symbol: str) -> str: """Creates a regular expression pattern to match the fixed income symbology. To create the regular expression patter, the function uses the fact that within the ICE consolidated feed, all the fixed income instruments are identified by the root sy...
def normalize_alef_maksura_bw(s): """Normalize all occurences of Alef Maksura characters to a Yeh character in a Buckwalter encoded string. Args: s (:obj:`str`): The string to be normalized. Returns: :obj:`str`: The normalized string. """ return s.replace(u'Y', u'y')
def calc_horizontal_depth_part2(lines): """ Calculate horizontal depth with aim :param lines:List of tuples of lines from file :returns: Horizontal position multiplied by final depth """ horizontal, depth, aim = 0, 0, 0 for command in lines: # command = ('forward', '5') uni...
def empty_list(number_of_items=0, default_item=None): """ Convenience fn to make a list with a pre-determined number of items. Its more readable than: var = [None] * number_of_items :param number_of_items: (int) how many items in the list :param default_item: the list wi...
def to_consistent_data_structure(obj): """obj could be set, dictionary, list, tuple or nested of them. This function will convert all dictionaries inside the obj to be list of tuples (sorted by key), will convert all set inside the obj to be list (sorted by to_consistent_data_structure(value)) >>>...
def process_schema_name(name): """ Extract the name out of a schema composite name by remove unnecessary strings :param name: a schema name :return: a string representing the processed schema """ new_raw_name = name.replace("_schema.json", '').replace('.json', '') name_array = new_raw_name.spli...
def backend_anything(backends_mapping): """ :return: Anything backend """ return list(backends_mapping.values())[1]
def parse_bint(bdata): """ Convert bencoded data to int """ end_pos = bdata.index(ord("e")) num_str = bdata[1:end_pos] bdata = bdata[end_pos + 1 :] return int(num_str), bdata
def unindent_text(text, pad): """ Removes padding at the beginning of each text's line @type text: str @type pad: str """ lines = text.splitlines() for i,line in enumerate(lines): if line.startswith(pad): lines[i] = line[len(pad):] return '\n'.join(lines)
def action_list_to_string(action_list): """Util function for turning an action list into pretty string""" action_list_string = "" for idx, action in enumerate(action_list): action_list_string += "{} ({})".format(action["name"], action["action"]["class_name"]) if idx == len(action_list) - 1: ...
def jekyllpath(path): """ Take the filepath of an image output by the ExportOutputProcessor and convert it into a URL we can use with Jekyll. This is passed to the exporter as a filter to the exporter. Note that this will be directly taken from the Jekyll _config.yml file """ return path.replace...
def parseBoardIdentifier(lsusbpattern): """ Parse the lsusb identifier assigned to the board. Note that some boards such as the PyBoard won't be enumerated by lsusb unless they are in DFU programming mode. Array values are as follows: key: lsusb identifier 0: name of the device 1: Is the b...
def convertRegionDisplayNameToRegionNameWithoutDot(regionDisplayName): """Converts given region display name to region name without dot. For ex; 'East US' to 'eastus'""" return str(regionDisplayName).lower().replace(" ", "")
def find_subclass(cls, subname): """Find a subclass by name. """ l = [cls] while l: l2 = [] for c in l: if c.__name__ == subname: return c l2 += c.__subclasses__() l = l2 return None
def mag2flux(mags, mag_zeropoint=0): """ Magnitude to flux convertion (arbitrary array shapes) """ return 10 ** (-0.4 * (mags + mag_zeropoint))
def check_selfLink_equal(url1, url2): """ 'https://googleapi/project/project_id/...' == '/project/project_id/...' """ traced_url1 = url1.split('project')[1] traced_url2 = url2.split('project')[1] return traced_url1 == traced_url2
def rev_c(seq): """ simple function that reverse complements a given sequence """ tab = str.maketrans("ACTGN", "TGACN") # first reverse the sequence seq = seq[::-1] # and then complement seq = seq.translate(tab) return seq
def get_all_files(target_dir): """Recurse the all subdirs and list os abs paths :param str target_dir: Indicates whether the target is a file :rtype: List[str] """ import os res = [] for root, d_names, f_names in os.walk(target_dir): for f in f_names: res.append(os.pa...
def soft_mask(sequence, left, right): """Lowercase the first left bases and last right bases of sequence >>> soft_mask('ACCGATCGATCGTAG', 2, 1) 'acCGATCGATCGTAg' >>> soft_mask('ACCGATCGATCGTAG', 0, 2) 'ACCGATCGATCGTag' >>> soft_mask('ACCGATCGATCGTAG', 2, 0) 'acCGATCGATCGTAG' >>> soft_ma...
def convert_bytes(n): """ Convert a size number to 'K', 'M', .etc """ symbols = ('K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y') prefix = {} for i, s in enumerate(symbols): prefix[s] = 1 << (i + 1) * 10 for s in reversed(symbols): if n >= prefix[s]: value = float(n) / pre...
def transformed_name(key: str) -> str: """Generate the name of the transformed feature from original name.""" return key + '_xf'
def deg2tenths_of_arcminute(deg): """ Return *deg* converted to tenths of arcminutes (i.e., arcminutes * 10). """ return 10 * deg * 60
def can_slice(input_shape, output_shape): """Check if the input_shape can be sliced down to match the output_shape.""" if len(input_shape) != len(output_shape): print("Slice dimensions differ:", input_shape, output_shape) return False for in_size, out_size in zip(input_shape, output_shape):...
def dumps(name, namelist): """ Writes a namelist to a string. Parameters ---------- name : str The name of the namelist namelist : dict Members of the namelist Returns ------- str String representation of the namelist """ # start with the opening mar...
def is_gt_seq_non_empty(annotations, empty_category_id): """ True if there are animals etc, False if empty. """ category_on_images = set() for a in annotations: category_on_images.add(a['category_id']) if len(category_on_images) > 1: return True elif len(category_on_images) =...
def file_is_pdf(filename: str) -> bool: """ Check if `filename` has the .pdf extension. Args: filename (str): Any filename, including its path. Returns: True if `filename` ends with .pdf, false otherwise. """ return filename.endswith(".pdf")
def merge(*args, **kwargs): """Merges any dictionaries passed as args with kwargs""" base = args[0] for arg in args[1:]: base.update(arg) base.update(kwargs) return base
def to_x_bytes(bytes): """ Take a number in bytes and return a human-readable string. :param bytes: number in bytes :type bytes: int :returns: a human-readable string """ x_bytes = bytes power = 0 while x_bytes >= 1000: x_bytes = x_bytes * 0.001 power = power + 3 ...
def mean_precision(j1, j2): """ Calculate the Precision Index among judges for a given set of evaluations. In particular, the function takes in input two sets of evaluations (one for each judges) referring to a single score for a given systems. For *each* judge, the function computes $P(ji) = P(j1 \...
def addr_to_address(addr: int) -> str: """ Converts a MAC address integer (48 bit) into a string (lowercase hexidecimal with colons). """ out = "{0:012x}".format(addr) return ":".join(out[2 * i : 2 * i + 2] for i in range(6))
def validate_int(s): """convert s to int or raise""" try: return int(s) except ValueError: raise ValueError('Could not convert "%s" to int' % s)
def dict_sum(A, B): """ Sum the elements of A with the elements of B """ if isinstance(A, dict) and isinstance(B, dict): return {key:dict_sum(value, B[key]) for key, value in A.items()} else: return A+B
def format_num(number): """add commas""" return "{:,d}".format(round(number))
def validate_ous(requested_ous, existing_ous): """ Confirms that the specified organizational unit IDs exist. Also converts an asterisk to all known OUs. Raises an error on an unknown OU. """ if not requested_ous: raise ValueError("No organizational units specified") requested = set(requ...
def generate_net_file_paths(experiment_path_prefix, net_count): """ Given an 'experiment_path_prefix', return an array of net-file paths. """ assert net_count > 0, f"'net_count' needs to be greater than zero, but was {net_count}." return [f"{experiment_path_prefix}-net{n}.pth" for n in range(net_count)]
def listrange2dict(L): """ Input: a list Output: a dictionary that, for i = 0, 1, 2, . . . , len(L), maps i to L[i] You can use list2dict or write this from scratch """ return { i:L[i] for i in range(len(L))}
def sort_labels(labels): """ Deal with higher up elements first. """ sorted_labels = sorted(labels, key=len) # The length of a Subpart label doesn't indicate it's level in the tree subparts = [l for l in sorted_labels if 'Subpart' in l] non_subparts = [l for l in sorted_labels if 'Subpart' not in l...
def capitalLettersCipher(ciphertext): """ Returns the capital letters in the ciphertext Parameters: ciphertext (str): The encrypted text Returns: plaintext (str): The decrypted text Example: Cipher Text: dogs are cuter than HorsEs in a LooP. Decoded Text: HELP """ plai...
def convert_bytes(num): """ this function will convert bytes to MB.... GB... etc """ for x in ['bytes', 'KB', 'MB', 'GB', 'TB']: if num < 1024.0: return "%3.1f %s" % (num, x) num /= 1024.0
def progessbar(new, tot): """Builds progressbar Args: new: current progress tot: total length of the download Returns: progressbar as a string of length 20 """ length = 20 progress = int(round(length * new / float(tot))) percent = round(new/float(tot) * 100.0, 1) ...
def split_lambda(some_list, some_function, as_list=False): """ Splits a list into a dict such that all elements 'x' in 'some_list' that get one value from 'some_function(x)' end up in the same list. Example: split_lambda([1,2,3,4,5,6,7], lambda x: x%2) -> {0: [2, 4, 6], 1: [1, 3, ...
def _is_regex(q): """Check if q is a regular expression. Parameters ---------- q : str Query string. Returns ------- bool True if q starts with "/" and ends with "/". """ return q.startswith("/") and q.endswith("/")
def output_args(kwargs): """ :param kwargs: input parameters :return: args: dictionary of arguments related to output format :return: kwargs: dictionary of remaining arguments relating to query """ args = {'opendap': kwargs.pop("opendap"), 'ncss': kwargs.pop("ncss"), 'variable': kwargs.pop("v...
def flip_transpose(arr): """ Flip a 2D-list (i.e. transpose). """ m = len(arr) n = len(arr[0]) res = [[-1 for _ in range(n)] for _ in range(m)] for i in range(m): for j in range(n): res[i][j] = arr[j][i] return res
def pascal(n, i): """Get the element value at the nth level and the ith index for Pascal's triangle. Levels are 0 at top, and increasing number descending; e.g. indexes Level 0 0 Level 1 0 1 Level 2 0 1 2 Level 3 0 1 2 3 etc to return ...
def insertion_sort(arr): """ Choose any element in original list and insert in order in newly partitioned list. """ # Iterate over list once for i in range(len(arr)): j = i # Iteratively check current and left element and swap if current is smaller while (j != 0 and arr[j] < ...
def get_fully_qualified_name(obj): """ Fully qualifies an object name. For example, would return "usaspending_api.common.helpers.endpoint_documentation.get_fully_qualified_name" for this function. """ return "{}.{}".format(obj.__module__, obj.__qualname__)
def _add_suffix(name, suffix): """Add a suffix to a name, do nothing if suffix is None.""" suffix = "" if suffix is None else "_" + suffix new_name = name + suffix return new_name
def test_sequence(value): """Return true if the variable is a sequence. Sequences are variables that are iterable. """ try: len(value) value.__getitem__ except: return False return True
def firstEmail(m, d): """ Engage stores emails and phone numbers in the 'contacts' section of a supporter record. This function finds the first email. If there's not an email record, then we'll return a None. Parameters: m dict supporter record d string default value ...
def multi_byte_xor(byte_array, key_bytes): """XOR the 'byte_array' with 'key_bytes'""" result = bytearray() for i in range(0, len(byte_array)): result.append(byte_array[i] ^ key_bytes[i % len(key_bytes)]) return result
def runSafely(funct, fmsg, default, *args, **kwds): """Run the function 'funct' with arguments args and kwds, catching every exception; fmsg is printed out (along with the exception message) in case of trouble; the return value of the function is returned (or 'default').""" try: return funct...
def cross_data(clusters, flist): """ Matches names in flist to the numbers in clusters. """ named_clusters = [] for cl in clusters: ncl = [flist[s] for s in cl] named_clusters.append(ncl) return named_clusters
def broadcast_rule(shape_a, shape_b): """Return output shape of broadcast shape_a, shape_b. e.g. broadcast_rule((3,2), (4,3,2)) returns output_shape = (4,3,2) Check out explanations and more examples at https://docs.scipy.org/doc/numpy-1.10.0/user/basics.broadcasting.html http://eli.thegreenplace.net/2015/broadc...
def C2F(degC): """degC -> degF""" return 1.8*degC+32.
def bool_xor(a, b): """Python's ^ operator is a bitwise xor, so we need to make a boolean equivalent function.""" return (a and not b) or (not a and b)