content
stringlengths
42
6.51k
def truncate_float(f: float, n: int): """Truncates/pads a float f to n decimal places without rounding""" s = "{}".format(f) if "e" in s or "E" in s: return "{0:.{1}f}".format(f, n) i, p, d = s.partition(".") return ".".join([i, (d + "0" * n)[:n]])
def checkBuried(Nmass1, Nmass2): """ returns True if an interaction is buried """ if (Nmass1 + Nmass2 <= 900) and (Nmass1 <= 400 or Nmass2 <= 400): return False else: return True
def get_target_name(label): """ Try to extract the target_name from a given PDS label. Parameters ---------- label : Object Any type of pds object that can be indexed Returns ------- target_name : str The defined target_name from the label. If this is None a target name...
def check_not_finished_board(board: list) -> bool: """ Check if skyscraper board is not finished, i.e., '?' present on the game board. Returns True if finished, False otherwise. >>> check_not_finished_board(['***21**', '4?????*', \ '4?????*', '*?????5', '*?????*', '*?????*', '*2*1***']) False ...
def remove_rev_dep(stix_objects): """Remove any revoked or deprecated objects from queries made to the data source""" # Note we use .get() because the property may not be present in the JSON data. The default is False # if the property is not set. return list( filter( lambda x: x.get...
def get_indented_block(prefix_lines): """Returns an integer. The return value is the number of lines that belong to block begun on the first line. Parameters ---------- prefix_lines : list of basestring pairs Each pair corresponds to a line of SHPAML source code. The first e...
def find_it(seq): """Return the int that is in seq odd amount of times.""" for num in seq: if seq.count(num) % 2 != 0: return num
def humanise_bytes(bytes): """ Returns humanised tuple of a number, typically bytes. For example, (1, 'MB') for 1'000'000 bytes. """ if bytes >= 1e12: return (bytes/1e12, 'TB') elif bytes >= 1e9: return (bytes/1e9, 'GB') elif bytes >= 1e6: return (bytes/1e6, 'MB') ...
def isHTML (fileS): """If the last file ends with HTML""" if fileS.endswith("htm") or fileS.endswith("html") : return 1 return 0
def _prefix(tree, value): """Find the largest index with all leaves before it aggregating to at most the specified value. Details ------- This does not work unless the binary tree aggregates using `sum` and has exactly a power-of-two number of leaves. """ # XXX the binary tree search l...
def _fullqualname_function_py3(obj): """Fully qualified name for 'function' objects in Python 3. """ if hasattr(obj, "__wrapped__"): # Required for decorator.__version__ <= 4.0.0. qualname = obj.__wrapped__.__qualname__ else: qualname = obj.__qualname__ return obj.__module_...
def insert_row(table_name, values): """Inserts a row in 'table_name' with values as 'values'""" query = f'INSERT INTO {table_name} VALUES (' no_attrs = len(values) # Add values to query for i in range(0, no_attrs - 1): query += f'{values[i]}, ' # Add semicolon for last value query...
def get_current_rid(config): """ returns current radio id """ firstuser_file = '/etc/first_rid' first_user = config['general'].get('id', None) if first_user: with open(firstuser_file,"w") as fi: fi.write(first_user) else: return "0000000" return first_user
def build_mapping(triples, entity_path, relation_path): """build mapping of entities and triples""" entity2id = {} relation2id = {} for triple in triples: head, rel, tail = triple[0], triple[1], triple[2] if head not in entity2id.keys(): entity2id[head] = len(entity2id) ...
def _getOrientation(orig_channel, orient): """ Return a character representing the orientation of a channel. Args: orig_channel (string): String representing the seed channel (e.g. 'HNZ'). The final character is assumed to be the (uppercase) orientation. orient (str ...
def WLF(Temp, RefT, WLF_C1, WLF_C2): """ Calculate the Williams-Landel-Ferry (WLF) equation [1]. Parameters ---------- Temp : numeric Evaluation temperature of the shift factor. RefT : numeric Reference temperature chosen to construct the master curve. WLF_C1, WLF_C2 : n...
def pathify(basenames, examples_dir="examples/"): # pragma: no cover """*nix to python module path""" example = examples_dir.replace("/", ".") return [example + basename for basename in basenames]
def remove_prefix(string, prefix): """Returns |string| without the leading substring |prefix|.""" # Match behavior of removeprefix from python3.9: # https://www.python.org/dev/peps/pep-0616/ if string.startswith(prefix): return string[len(prefix):] return string
def _calc_shortest_path(nodes_process, dist): """ Calculate shortest path Args: nodes_process: nodes that we met on path dist: distances Returns: int: length shortest path """ shortest_path = 10 ** 16 for node in nodes_process[1] + nodes_process[0]: ...
def is_even(x): """ True if obj is even. """ return (x % 2) == 0
def modifier_ve(score: int, attr: str) -> str: # pylint: disable=unused-argument """computes an attribute modifier with Vieja Escuela rules""" result = "" if score > 17: result = "+2" elif score > 14: result = "+1" elif score > 6: result = "" elif score > 3: resu...
def get_provenance_record(ancestor_files): """Create a provenance record.""" record = { 'caption': "Forcings for the PCR-GLOBWB hydrological model.", 'domains': ['global'], 'authors': [ 'aerts_jerom', 'andela_bouwe', 'alidoost_sarah', ...
def poly (*args): """ f(x) = a*x + b * x**2 + c * x**3 + ... *args = (x,a,b) """ if len(args) ==1: raise Exception ("You have only entered a value for x, and no coefficents.") x = args[0] # X value coef = args[1:] result = 0 for power, c in enumerate(coef): result...
def validate_sequences(seed_sequence, extracted_full_seq, rnac=True): """ Validates whether the SEED sequence matches the sequence extracted at specific coordinates seed_sequence: A DNA/RNA sequecne extracted from the SEED alignment extracted_full: A DNA/RNA subsequence extracted at specific locati...
def can_contact_customer_support(botengine): """ Leverages the com.domain.YourBot/domain.py file or organization properties to determine if customer support is available for this bot :return: """ import importlib try: properties = importlib.import_module('properties') except ImportEr...
def _make_col_qual_name(col_name, parent_table_name): """ Generate a standardized qualified name for column entities. :param str col_name: The column name. :param str parent_table_name: The parent table name. :return: The qualified name for the column. :rtype: str """ return f"{parent_...
def _quote_identifier(identifier): """Quote identifiers""" return "\"" + identifier + "\""
def has_variable(formula, variable): """ Function that detects if a formula contains an ID. It traverses the recursive structure checking for the field "id" in the dictionaries. :param formula: node element at the top of the formula :param variable: ID to search for :return: Boolean encoding if...
def remove_duplicates(hashtags): """Removes duplicates from given hashtag list Parameters: hashtags (list): list of hashtags Returns: List of hashtags without duplicate entries """ result = list(dict.fromkeys(hashtags)) return result
def derive_platform_name(input: str) -> str: """ derive platform info, needed to create schemaaspect urn:li:dataset:(urn:li:dataPlatform:{platform},{name},{env}) """ platform_name_env = input.replace("urn:li:dataset:(urn:li:dataPlatform:", "") platform = platform_name_env.split(",")[0] platf...
def cleanup_coords(coords): """ remove coordinates that are closer than 0.01 (1cm) :param coords: list of (x, y) coordinates :return: list of (x, y) coordinates """ result = [] last_coord = coords[-1] for coord in coords: if ((coord[0] - last_coord[0]) ** 2 + (coord[1] - last_coo...
def find_supports(combinations, supports, combination): """ find supports of combinations Parameters ---------- combinations : list combinations to find supports. supports : list support of combinations. combination : list combination to find support from combination...
def determine_linestyle(boundary, boundary_list, kpp, swb, diffusion_type): """ Given the boundary and diffusion of a run we are plotting, specifying which linestyle to use :return: """ if len(boundary_list) is 1: if swb and kpp: if diffusion_type is 'SWB': return...
def get_ancestor(taxid, tree, stop_nodes): """Walk up tree until reach a stop node, or root.""" t = taxid while True: if t in stop_nodes: return t elif not t or t == tree[t]: return t # root else: t = tree[t]
def warmup_linear(x, warmup=0.002): """Specifies a triangular learning rate schedule where peak is reached at `warmup`*`t_total`-th (as provided to BertAdam) training step. After `t_total`-th training step, learning rate is zero.""" if x < warmup: return x / warmup return max((x - 1.0) / (warmup...
def getID(string): """ get ICSD id from strings like "Al1H3O3_ICSD_26830" """ return string.split('_')[-1]
def encode_with(string, encoding): """Encoding ``string`` with ``encoding`` if necessary. :param str string: If string is a bytes object, it will not encode it. Otherwise, this function will encode it with the provided encoding. :param str encoding: The encoding with which to encode string. ...
def check_field(rule: tuple, field: int) -> bool: """check if a field is valid given a rule""" for min_range, max_range in rule: if min_range <= field <= max_range: return True return False
def calculate_building_intersection_matrix(bn): """ :param bn: total number of buildings on both sides :return: matrix of number of buildings between any two building """ int_mat = [[0 for col in range(bn)] for row in range(bn)] bn_eachside = int(bn/2) i = 0 while i < (bn_eac...
def macaddr_unpack(data): """ Unpack a MAC address Format found in PGSQL src/backend/utils/adt/mac.c """ # This is easy, just go for standard macaddr format, # just like PGSQL in src/util/adt/mac.c macaddr_out() if len(data) != 6: raise ValueError('macaddr has incorrect length') return ("%02x:%02x:%02x:%02x:...
def TabSpacer(number_spaces, string): """Configuration indentation utility function.""" blank_space = ' ' return (blank_space * number_spaces) + string
def pretty_len_filterer(words, sol_length): """Filtering by length including underscore and space between words (in the case of multi word solutions) before filtering by length of individual words seperate by underscore Args: words : list of words to filter sol_length : lengthg os olution...
def cosine_similarity(exp1, exp2): """ calculate the cosine similarity of 2 experiments """ words1, vector1 = exp1 words2, vector2 = exp2 similarity = 0.0 for idx1, word in enumerate(words1): # if a word is in both exp1 and exp2, similarity increased by tfidf1 * tfidf2 if word in words2: idx2 =...
def get_size(volume_size: int): """ Convert Mbs to Bytes""" tmp = int(volume_size) * 1024 * 1024 return tmp
def get_header(metrics): """ Get header name from metrics dict. """ return f'{metrics["display_name"]} ({metrics["unit"]})'
def copy_dict(source, destination): """ Populates a destination dictionary with the values from the source :param source: source dict to read from :param destination: destination dict to write to :returns: destination :rtype: dict """ for name, value in source.items(): destina...
def UNKNOWN_BRANCH(project_id, branch_id): """Error message for requests that access project branches. Parameters ---------- project_id: string Unique project identifier. branch_id: string Unique branch identifier. Returns ------- string """ msg = "unknown branc...
def bernoulli2ising(bernoulli: int) -> int: """ Transfers variable form Bernoulli random to Ising random; see https://en.wikipedia.org/wiki/Bernoulli_distribution https://en.wikipedia.org/wiki/Ising_model :param bernoulli: int :return: """ if bernoulli == 1: return 1 elif be...
def deep_merge_dict(dict_x, dict_y, path=None): """ Recursively merges dict_y into dict_x. Args: dict_x: A dict. dict_y: A dict. path: Returns: An updated dict of dict_x """ if path is None: path = [] for key in dict_y: if key in dict_x: if isinstanc...
def get_short_version(framework_version): """Return short version in the format of x.x Args: framework_version: The version string to be shortened. Returns: str: The short version string """ return ".".join(framework_version.split(".")[:2])
def currency(x, pos): """The two args are the value and tick position""" if x >= 1e6: s = '${:1.1f}M'.format(x*1e-6) else: s = '${:1.0f}K'.format(x*1e-3) return s
def cescape(string): """Escapes special characters needed for color codes. Replaces the following symbols with their equivalent literal forms: ===== ====== ``@`` ``@@`` ``}`` ``}}`` ===== ====== Parameters: string (str): the string to escape Returns: (str): the st...
def format_msg(message): """ Used to format user messages. Replaces newline characters with spaces, '\\n' with newlines, etc. :type message: str :rtype: str """ return ( message .strip() .replace('\\n\n', '\\n') .replace('\n', ' ') .rep...
def format_duration(seconds): """ Format a duration into a human-readable string. """ mins, secs = divmod(seconds, 60) fmt = '{:.0f}' if mins: return '{} minutes {} seconds'.format(fmt, fmt).format(mins, secs) else: return '{} seconds'.format(fmt).format(secs)
def is_int(s): """Returns true if s represents an integer""" try: int(s) return True except ValueError: return False
def RPL_INVITING(sender, receipient, message): """ Reply Code 341 """ return "<" + sender + ">: " + message
def _round_to_multiple_of(val, divisor, round_up_bias=0.9): """ Asymmetric rounding to make `val` divisible by `divisor`. With default bias, will round up, unless the number is no more than 10% greater than the smaller divisible value, i.e. (83, 8) -> 80, but (84, 8) -> 88. """ assert 0.0 < round_up_bia...
def format_response(status_code, headers, body): """ Helper function: Generic response formatter """ response = { 'statusCode': status_code, 'headers': headers, 'body': body } return response
def get_data_id(data) -> int: """Return the data_id to use for this layer. Parameters ---------- data Get the data_id for this data. Notes ----- We use data_id rather than just the layer_id, because if someone changes the data out from under a layer, we do not want to use the ...
def process_activities(activities_str: str) -> list: """ Split activities as a pipe-separated string into a list of activities. """ activities_split = activities_str.split(" | ") # Ignore row of no activities, which will be a single null string after # splitting. if len(activities_split) ==...
def blend_color_burn(cb: float, cs: float) -> float: """Blend mode 'burn'.""" if cb == 1: return 1 elif cs == 0: return 0 else: return 1 - min(1, (1 - cb) / cs)
def declare(var_name, var_type): """Creates an SMTLIB declaration formatted string Parameters ---------- var_name: string The name of the variable var_type: The type of the variable (Int, Bool, etc.) """ return "(declare-fun " + var_name + " () " + var_type + ")\n"
def quote_fname(fname): """quote file name or any string to avoid problems with file/directory names that contain spaces or any other kind of nasty characters """ return '"%s"' % ( fname .replace('\\', '\\\\') .replace('"', '\"') .replace('$', '\$') .replace('`', '\`') .replace('!', '\!') )
def cat_ranges_for_reorder(page_count, new_order): """ Returns a list of integers. Each number in the list is correctly positioned (newly ordered) page. Examples: If in document with 4 pages first and second pages were swapped, then returned list will be: [2, 1, 3, 4] If first pa...
def format_iter(iterable, *, fmt='{!r}', sep=', '): """Format and join items in iterable with the given format string and separator""" return sep.join(fmt.format(x) for x in iterable)
def binary_search(x, arr, include_equal = False): """ Returns the index of the smallest element in an array which is larger than a specified element. This assumes that the array is sorted in non-decreasing order. If the element is larger than the largest element in the array, then the length of the array is retu...
def ean_digit(arg): """Calculate UPCA/EAN13/NVE checksum for any given string consiting of an arbitary number of digits. >>> ean_digit('400599871650') '2' >>> ean_digit('34005998000000027') '5' """ factor = 3 summe = 0 for index in range(len(arg) - 1, -1, -1): summe += int(...
def is_posix_path(my_path: str) -> bool: """Return whether or not a given path is Posix-based.""" return "/" in str(my_path)
def _get_member_groups(get_member_group_func, identifier, security_enabled_only): """Call 'directoryObject: getMemberGroups' API with specified get_member_group_func. https://docs.microsoft.com/en-us/graph/api/directoryobject-getmembergroups """ body = { "securityEnabledOnly": security_enabled_o...
def _padded_hex(i, pad_width=4, uppercase=True): """ Helper function for taking an integer and returning a hex string. The string will be padded on the left with zeroes until the string is of the specified width. For example: _padded_hex(31, pad_width=4, uppercase=True) -> "001F" :param i: integ...
def get_dict_modes(dict): """Finds the keys of the modes of a dictionary @param dict: A dictionary of the form {"key":#} """ highest_count = dict[max(dict)] modes = [] for key in dict: if dict[key] == highest_count: modes.append(key) return modes
def add_metadata(data): """ Decorates a set of data (as produced by `normalised_sheet`) with metadata. At this time, this only wraps the results in a `data` key """ # In the future this could add additional top-level fields like # date-created, original data source, alerts, and ...
def average_difference(dictA, dictB): """Return the average difference of values in dictA minus dictB, only using values in dictA. If a value is missing from dictB, raise Exception. """ total_diff = 0.0 for (k, va) in dictA.items(): vb = dictB[k] total_diff += (va - vb) r...
def limit_string(string, limit): """ Cuts off a string on last word instead of max chars and adds ellipsis at the end Args: string (unicode) limit (int) """ string = string.strip() if len(string) > limit: string = string[:limit - 3] string = string.rsplit(' ', 1)[...
def url_for(key): """Return URL for request type.""" return { "query_user": "https://l9ren7efdj.execute-api.us-east-1.amazonaws.com/developStage/user/v1", "get_devices": "https://l9ren7efdj.execute-api.us-east-1.amazonaws.com/developStage/sortdevices/v1/devices", "get_device": "https://l...
def _get_crc_7(message): """ Calculates and returns the integrity verification byte for the given message. Used only by the serial controller. For more details, see section "Cyclic Redundancy Check (CRC) error detection" at https://www.pololu.com/docs/0J71/9 """ crc = 0 for i in range(len(messag...
def delete_duplicated_node(head): """ :param head: head of ListNode :return: head """ cur = head pre = None while cur: pre = cur cur = cur.next while cur and cur.val == pre.val: cur = cur.next pre.next = cur return head
def digit_sum(num: int) -> int: """Calculate the sum of a number's digits.""" total = 0 while num: total, num = total + num % 10, num // 10 return total
def which(program): """works like unix which""" # stolen from https://stackoverflow.com/questions/377017/test-if-executable-exists-in-python import os def is_exe(fpath): return os.path.isfile(fpath) and os.access(fpath, os.X_OK) fpath, fname = os.path.split(program) if fpath: if...
def _a1inv(x): """Compute inverse function. Inverse function of the ratio of the first and zeroth order Bessel functions of the first kind. Returns the value k, such that a1inv(x) = k, i.e. a1(k) = x. """ if 0 <= x < 0.53: return 2 * x + x ** 3 + (5 * x ** 5) / 6 elif x < 0.85: ...
def calculate_color( value ): """! @brief calculates color for given value """ r = 255-int( 255*value**4 ) g = 255-int( 255*value**4 ) b = 255 color = '#%02x%02x%02x' % (r, g, b) return color
def v1_add(matrix1, matrix2): """Add corresponding numbers in given 2-D matrices. Using the zip function to iterate over the 2 matrices at the same time. """ combined = [] for rows in zip(matrix1, matrix2): row = [] for items in zip(rows[0], rows[1]): row.append(items[0]...
def formatbytes(bytes: float): """ Return the given bytes as a human friendly KB, MB, GB, or TB string """ bytes_float = float(bytes) KB = float(1024) MB = float(KB**2) # 1,048,576 GB = float(KB**3) # 1,073,741,824 TB = float(KB**4) # 1,099,511,627,776 if bytes_float < KB: ...
def custom_user_authentication_rule(user): """ Override the default user authentication rule for Simple JWT Token to return true if there is a user and let serializer check whether user is active or not to return an appropriate error :param user: user to be authenticated :return: True if user is not...
def frames_to_ms(num_frames: int) -> int: """at 60 fps, each frame would happen in 16.67 ms""" return int(16.67 * num_frames)
def sub(vector1, vector2): """ Subtracts a vector from a vector and returns the result as a new vector. :param vector1: vector :param vector2: vector :return: vector """ new_vector = [] for index, item in enumerate(vector1): new_vector.append(vector1[index] - vector2[index]) ...
def change_variation(change: float) -> float: """Helper to convert change variation Parameters ---------- change: float percentage change Returns ------- float: converted value """ return (100 + change) / 100
def cleaner(element, accept, level=0, key_only=False): """ Clean a structure (list or dict based) based on cleanfunc() :param element: element to clean :param accept: function to call to determine acceptance :param level: recursion level :return: cleaned element """ if isinstance(elemen...
def _left_child(node): """ Args: node: index of a binary tree node Returns: index of node's left child """ return 2 * node + 1
def reverseWords(s): """ :type s: str :rtype: str """ if len(s) == 0: return s if len(s) == 1 and s[0] == " ": return "" # Brute force: Tokenize on space, add it to list l = s.split() r = " ".join(l[::-1])...
def func_star(a_b, func): """Convert `f([1,2])` to `f(1,2)` call.""" return func(*a_b)
def format_author_line(author_names): """authorLine format depends on if there is 1, 2 or more than 2 authors""" author_line = None if not author_names: return author_line if len(author_names) <= 2: author_line = ", ".join(author_names) elif len(author_names) > 2: author_line...
def create_keypoint(n,*args): """ Parameters: ----------- n : int Keypoint number *args: tuple, int, float *args must be a tuple of (x,y,z) coordinates or x, y and z coordinates as arguments. :: # Example kp1 = 1 kp2 = 2 crea...
def get_shared_values(param_list): """ For the given list of parameter dictionaries, make a dictionary of the keys and values that are the same for every set in the list >>> get_shared_values([{'a':0, 'b':1, 'c':2, 'd':3}, {'a':0, 'b':1, 'c':3}, {'a':0, 'b':'beta'}]) {'a': 0} >>> get_shared_values([{'a':0, 'd'...
def choices_from_list(source, prepend_blank=True): """ Convert a list to a format that's compatible with WTForm's choices. It also optionally prepends a "Please select one..." value. Example: # Convert this data structure: TIMEZONES = ( 'Africa/Abidjan', 'Africa/Accra', 'Africa/Addi...
def make_full_request_type( service_name: str, request_type: str, ) -> str: """Return the full GRPC request type by combining service name and request type Args: service_name (str): ex: magma.lte.LocalSessionManager request_type (str): ex: CreateSession Returns: str: full r...
def flatten(sequence): """Given a sequence possibly containing nested lists or tuples, flatten the sequence to a single non-nested list of primitives. >>> flatten((('META.INSTRUMENT.DETECTOR', 'META.SUBARRAY.NAME'), ('META.OBSERVATION.DATE', 'META.OBSERVATION.TIME'))) ['META.INSTRUMENT.DETECTOR', 'META...
def bigger_max(nums1: set, nums2: set) -> set: """Return the set that has the larger maximum. Return nums1 if there is a tie. This assumes that both sets are non-empty, and that they only contain integers. NOTE: Use the builtin function isinstance to check whether a value has a certain type. For ...
def get_by_path(d, path): """Access an element of the dict d using the (possibly dotted) path. For example, 'foo.bar.baz' would return d['foo']['bar']['baz']. Args: d (dict): (nested) dictionary path (str): path to access the dictionary Returns: the val...
def get_command_name(command): """ Only alpha/number/-/_/+ will be kept. Spaces will be replaced to ".". Others will be replaced to "+". """ name = "" for char in command: if char.isalnum() or char == "-" or char == "_": name += char elif char == " ": name...