content
stringlengths
42
6.51k
def acc(FN, TN, TP, FP): """ Returns: accuracy measure """ acc = 1.0 * (TP + TN) / (TP + TN + FP + FN) return acc
def get_iou(bb1, bb2): """ Calculate the Intersection over Union (IoU) of two bounding boxes. Parameters ---------- bb1 : dict Keys: {'x1', 'x2', 'y1', 'y2'} The (x1, y1) position is at the top left corner, the (x2, y2) position is at the bottom right corner bb2 : dict ...
def trimstring(string): """Performs basic string normalization""" string = string.lower() string = string.strip() return string
def comparer(ses_hash, usr_hash): """This provides a function to compare initially hashed flight times with doubly hashed stored flight times.""" total = 0 kmax = 0 for k in usr_hash.keys(): if k in ses_hash: kmax += 1 total += (abs(int(ses_hash[k]) - int(usr_hash[k])) - 24) score = 4.8 - (total/kmax) #4 m...
def rev_transcribe(dna): """ Transcribe DNA to RNA """ replace_dict = {"T": "A", "G": "C", "A": "T", "C": "G"} return "".join([replace_dict[base] for base in dna][::-1])
def _closest_index(dcl, absofs): """:return: index at which the given absofs should be inserted. The index points to the DeltaChunk with a target buffer absofs that equals or is greater than absofs. :note: global method for performance only, it belongs to DeltaChunkList""" lo = 0 hi = len(dcl) while lo < hi: ...
def interpret(block: str): """ Interprets an element block, breaking it into element and number of that element. :param block: string block describing an element :return: composition dictionary :rtype: dict """ if block[0].isdigit() is True: # if isotope number is encountered retur...
def filter_connection_params(queue_params): """ Filters the queue params to keep only the connection related params. """ NON_CONNECTION_PARAMS = ('DEFAULT_TIMEOUT',) #return {p:v for p,v in queue_params.items() if p not in NON_CONNECTION_PARAMS} # Dict comprehension compatible with python 2.6 ...
def area(box): """Calculates area of a given bounding box.""" assert box[1][0] >= box[0][0] assert box[1][1] >= box[0][1] return float((box[1][0] - box[0][0]) * (box[1][1] - box[0][1]))
def filter_devices(devices, wanted): """ Return a list of desired Device objects. :param devices: list of Device dicts :param wanted: list of hostnames you want """ return [d for d in devices if d['hostname'] in wanted]
def strip_parameters(target: str) -> str: """Remove trailing ALGOL-style parameters from a target name; e.g. foo(bar, baz) -> foo.""" if not target.endswith(")"): return target starting_index = target.rfind("(") if starting_index == -1: return target return target[0:starting...
def MakeTuple(object_): """ Returns the given object as a tuple, if it is not, creates one with it inside. @param: Any object or tuple The object to tupleIZE """ if isinstance(object_, tuple): return object_ else: return (object_,)
def dict_to_str_sorted(d): """Return a str containing each key and value in dict d. Keys and values are separated by a comma. Key-value pairs are separated by a newline character from each other, and are sorted in ascending order by key. For example, dict_to_str_sorted({1:2, 0:3, 10:5}) should r...
def quick_sort(arr): """ time complexity: O(n*logn) space complexity: O(1) :prarm arr: list :return: list """ if not isinstance(arr, list): raise TypeError if len(arr) <= 1: return arr else: left = quick_sort([x for x in arr[1:] if x < arr[0]]) mid = [...
def tokenize_message(message): """return a list of normalized words.""" return (message .lower() .replace(".", " .") .replace(",", " ,") .replace("?", " ?") .replace("!", " !") .replace(":", " :") .replace("'s", " 's") ...
def list_replace(values,old,new): """Replace any occurrence of a given value, in a given list. Limitation: Fails to replace np.nan, since == operator yields false on nan, and computed nan fails "is" test with np.nan. Arguments: values (list) : list (or iterable) of input values old (.....
def metric_or_imperial(query, lang, us_ip=False): """ """ # what units should be used # metric or imperial # based on query and location source (imperial for US by default) if query.get('use_metric', False) and not query.get('use_imperial', False): query['use_imperial'] = False ...
def total_letters(transcript: str) -> int: """ Sums the total amount of non-space characters in the transcript. :param transcript: A string containing the contents of the transcribed audio file. :return: Returns the number of letters in the file. """ counter = 0 for i in transcript: ...
def remove_items_from_dict(a_dict, bad_keys): """ Remove every item from a_dict whose key is in bad_keys. :param a_dict: The dict to have keys removed from. :param bad_keys: The keys to remove from a_dict. :return: A copy of a_dict with the bad_keys items removed. """ new_dict = {} for ...
def is_not_a_debit_line(line): """ sometimes there are lines that we would like to be automatically removed from the debits section. AKA for these lines, the system won't even ask if user wants to ignore them. They will be removed before getting to that point """ if ( "str1" in line and "anot...
def make_descriptor_string(attribute, value): """ Create a key-value string to form part of a GTF entry. Example: gene_id and ENSG00000117676.13 becomes gene_id "ENSG00000117676.13"; """ return str(attribute) + ' "' + str(value) + '";'
def to_metric(amount, unit): """ Used to convert common (amount, unit) pairs to metric versions, e.g., (5, 'GALLON') -> (18.9270589, 'LITER') """ if unit == 'POUND': kgs = (amount * 0.45359237, 'KILOGRAM') if kgs[0] < 1.0: return (kgs[0] * 1000, 'GRAM') return kgs...
def get_color_tag(counter): """returns color tag based on parity of the counter""" if counter % 2 == 0: return 'warning' return 'info'
def calc_pad(pad, in_siz, out_siz, stride, ksize): """Calculate padding size. Args: pad: padding, "SAME", "VALID" or manually specified tuple [P, Q]. ksize: kernel size, [I, J]. Returns: pad_: Actual padding width. """ if pad == 'SAME': return (out_siz - 1) * stride...
def number_to_string(number): """ Converts given number to a String(32) representing an objectID primary key. Makes too long strings if the number is over 32 digits. >>> number_to_string(1) '00000000000000000000000000000001' >>> number_to_string(0xdeadbeef) '000000000000000000000000dea...
def sanitize_referers(url): """Given a url sanitize it to a referrer Arguments: - `url`: An url """ if url is None: return "Unknown" elif "google." in url: return url elif "facebook." in url or "fb." in url: return url else: return "Unknown"
def gen_run_entry_str(query_id, doc_id, rank, score, run_id): """A simple function to generate one run entry. :param query_id: query id :param doc_id: document id :param rank: entry rank :param score: entry score :param run_id: run id """ return f'{query_id} Q0 {doc_id} {rank}...
def printSeparator(separatorSize,printToScreen = True): """ Description: Prints out a horizontal seperator of varying sizes Params: separatorSize [INT]: size of separator Output: NONE """ seperatorSegment = "####################" seperator = '' for i in range(...
def _any_instance(var, classes): """Check if var is an instance of any class in classes.""" for cl in classes: if isinstance(var, cl): return True return False
def get_colour(progress, colours): """ Interpolates between colours by a given percent. :param progress: Value 0 <= x <= 1 of how far to interpolate :param colours: List of 2 colours to interpolate betweeen :return str: Hex code of final colour """ if progress >= 0 and progress <= 1: ...
def search(array, key, value): """Generic function to find a particular dictionary in a list of dictionaries, based on one key:value pair in each dict. """ for item in array: if item[key] == value: return item return None
def get_forge_url(version: str) -> str: """Ensures a constant and streamlined string creation for forge urls""" return f"https://files.minecraftforge.net/net/minecraftforge/forge/index_{version}.html"
def json_ld_get_activities_list_from_rawdata(data): """Return list of processes from raw data.""" return list(data["processes"].values())
def merge_dicts(*dicts, **kwargs): """Merges dicts and kwargs into one dict""" result = {} for d in dicts: result.update(d) result.update(kwargs) return result
def rescale(OldValue,OldMin,OldMax,NewMin,NewMax): """ # ============================================================================= # rescale(OldValue,OldMin,OldMax,NewMin,NewMax) # ============================================================================= this function rescale a value b...
def _get_leading(o): """ Parameters ---------- o : any """ return ((len(o) - len(o.lstrip(o[0]))), o[0])
def non_empty_datapoint_values(data): """ From a graphite like response, return the values of the non-empty datapoints """ if data: return [t[0] for t in data[0]['datapoints'] if t[0]] return []
def is_chinese_char(char): """Checks whether CP is the codepoint of a CJK character.""" # This defines a "chinese character" as anything in the CJK Unicode block: # https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block) # # Note that the CJK Unicode block is NOT all Japanese and Kore...
def search_steps_with_states(steps, states): """Search for steps that are in the given states. Arguments: steps -- An iterator over Step like objects. states -- A list of states allowed by the Step like objects e.g., Step.WAIT. Returns: A generator object that will yield step objects whose st...
def is_gzip_file(file_name): """test for gzip compressed file extension""" if file_name.lower().endswith('.gz') or file_name.lower().endswith('.gzip'): return True else: return False
def get_params(space): """ Get params :param space: :return: """ # Params hidden_size = int(space['hidden_size']) cell_size = int(space['cell_size']) feature = space['feature'][0][0] lang = space['lang'][0][0] dataset_start = space['dataset_start'] window_size = int(space...
def pcc_vector(v1, v2): """Pearson Correlation Coefficient for 2 vectors """ len1 = len(v1) len2 = len(v2) if len1 != len2: return None else: length = len1 avg1 = 1.0 * sum(v1) / len(v1) avg2 = 1.0 * sum(v2) / len(v2) dxy = [(v1[i] - avg1) * (v2[i] - avg2) for i in ra...
def _linkify(value): """create link format""" out = [] for link in value: out.append(','.join(list(link))) return '^'.join(out)
def rindex(lst, elem): """Get the last position of elem in lst.""" try: return len(lst) - lst[::-1].index(elem) - 1 except: return 0
def convert_ascii_code_to_decimal(ascii_code: int) -> int: """ Converts ASCII code to six-bit decimal number. """ if ascii_code < 48 or 87 < ascii_code < 96 or ascii_code > 119: raise ValueError(f'Invalid ASCII {ascii_code}.') decimal = ascii_code - 48 if decimal > 40: decimal -=...
def clean_uid(uid): """ Return a uid with all unacceptable characters replaced with underscores """ try: return uid.decode('utf-8').replace(u"/",u"_").replace(u":",u"_") except AttributeError: return uid.replace("/","_").replace(":","_")
def rename_with_schema(file_name): """ This method is used to rename the file with schema postfix. :param file_name: type str :return: """ return file_name.replace('.csv', '_schema.json')
def safe_col_name(args_pair): """Ensure that the column name is safe for SQL (unique value, no spaces, no trailing punctuation). Typically called with `df.columns = [*map(safe_col_name, enumerate(df.columns.to_list()))]` Args: args_pair: tuple of arguments from map function in `(idx, col)` Re...
def parts(doc_urn): """A flat list of all "parts", which are defined as top-level colon-delimited parts, further split by dot-delimited parts, e.g.: urn:cts:copticLit:psathanasius.matthew20.budge:1:56 -> ['urn', 'cts', 'copticLit', 'psathanasius', 'matthew20', 'budge', '1', '56'] """ return [part for ...
def url_to_unc(url: str): """Convert URL und UNC.""" url = url.strip() url = url.replace("smb://", "\\\\") url = url.replace("file://", "\\\\") url = url.replace("/", "\\") url = url.replace("%20", " ") return url
def _get_regular_TYC_name(*args): """Convert a TYC name in *Tycho-2 Catalogue* to its regular form `"TYC NNN-NNN-N"`. """ if len(args) == 1 and isinstance(args[0], str): name = args[0].strip() return 'TYC ' + name[3:].strip() elif len(args) == 3: return 'TYC '+'-'.join([str(a...
def fixbreaks(value): """ fixes line breaks to make markdown happy. Be careful. It won't play nice with para breaks. """ return value.replace('\n', ' \n')
def glyph_order(keys, draw_order=[]): """ Orders a set of glyph handles using regular sort and an explicit sort order. The explicit draw order must take the form of a list of glyph names while the keys should be glyph names with a custom suffix. The draw order may only match subset of the keys and a...
def _c_string_literal(s): """ Convert a python string into a literal suitable for inclusion into C code """ # only these three characters are forbidden in C strings s = s.replace('\\', r'\\') s = s.replace('"', r'\"') s = s.replace('\n', r'\n') return '"{}"'.format(s)
def _is_executable_product(product): """Returns a boolean indicating whether the specified product dictionary is an executable product. Args: product: A `dict` representing a product from package description JSON. Returns: A `bool` indicating whether the product is an exec...
def command_deploy_file(ifname, ofname) : """Returns command to deploys file with calibration constants in the calib store. """ return 'cat %s > %s' % (ifname, ofname)
def _is_number(x): """Checker function for numeric inputs that include float.""" try: float(x) return True except ValueError: return False
def _cb_dist(ctx, param, value): """ Click callback to ensure `--distance` can be either a float or a field name. """ try: return float(value) except ValueError: return value
def bisect_right(arr, target): """Returns the rightmost position that `target` should go to such that the sequence remains sorted.""" left = 0 right = len(arr) while left < right: mid = (left + right) // 2 if arr[mid] > target: right = mid else: left =...
def get_field_and_dtype_from_attribute_field(attribute_field) -> tuple: """ Returns both the field and data type parts of attribute_field (e.g. 'file_size, int'). If no dtype is given, a dtype of "str" is returned. Args: attribute_field: the name of the attribute field Returns: tu...
def compare_payload(json_payload, idrac_attr): """ :param json_payload: json payload created for update operation :param idrac_attr: idrac user attributes case1: always skip password for difference case2: as idrac_attr returns privilege in the format of string so convert payload to string only f...
def _find_missing_and_invalid_fields( required_fields, json_data ): """ Look for missing or invalid fields, and return them. """ missing = [] invalid = [] for req, types in required_fields.items(): if req not in json_data.keys(): missing.append( req ) if...
def get_item_from_obj(config: dict, name_path: str) -> object: """ Follow the name_path to get values from config For example: If we follow the example in in the Parameters section, Timestamp('2008-01-02 00:00:00') will be returned Parameters ---------- config : dict e.g. ...
def straight_line(x, m=1, c=0): """ straight line equation """ return x*m + c
def build_insert(table: str, to_insert: list): """ Build an insert request. Parameters ---------- table : str Table where query will be directed. to_insert: iterable The list of columns where the values will be inserted. Returns ------- str Built query strin...
def convert_bool_value_to_yes_no_string(value): """Convert a boolean value into a 'Yes' or 'No' string representation. Parameters ---------- value: Boolean value. Returns ------- String "YES", "NO" (default). """ if value: return "Yes" return "No"
def getmtime(pathname): """Modification timestamp of file or directory or 0 if it does nor exists""" ##debug("exists: checking timestamp of %r" % pathname) from os.path import getmtime try: return getmtime(pathname) except: return 0
def num_in_numbits(num, numbits): """Does the integer `num` appear in `numbits`? Returns: A bool, True if `num` is a member of `numbits`. """ nbyte, nbit = divmod(num, 8) if nbyte >= len(numbits): return False return bool(numbits[nbyte] & (1 << nbit))
def _create_postgres_url(db_user, db_password, db_name, db_host, db_port=5432, db_ssl_mode=None, db_root_cert=None): """Helper function to construct the URL connection string Args: db_user: (string): the username to connect to the Postgres D...
def parse_path(s3_datapath): """ Return bucket and prefix from full s3 path. Parameters ---------- s3_datapath : str path to a bucket. Should be of the form s3://bucket/prefix/. Returns ------- tuple bucket and prefix. """ bucket_path = str(s3_datapath)....
def circumference_area(radius): """Returns the area of a circumference""" return 3.14159*radius*radius
def pto(pct): """Percentage to odds converter. Take a number like 35, return what odds it represents (x-to-one odds). """ return (1 - pct / 100.0) / (pct / 100.0)
def common_sub(data): """(internal) Finds longest common substring for a list of strings. """ substr = '' if len(data) > 1 and len(data[0]) > 0: for i in range(len(data[0])): for j in range(len(data[0])-i+1): if j > len(substr) and all(data[0][i:i+j] in x for x in dat...
def is_retweet(tweet: dict): """Return True if the passed tweet is a retweet. :param tweet: JSON dict for tweet """ try: text = tweet["tweet"]["full_text"] except KeyError: text = tweet["tweet"]["text"] if text.startswith("RT @"): return True return False
def py3round(number): """Unified rounding in all python versions.""" if abs(round(number) - number) == 0.5: return int(2.0 * round(number / 2.0)) return int(round(number))
def extract_gff3_record_id_from_info_field(info): """Helper function to extract GFF3 record ID from info string""" for tag in info.split(';'): if tag.startswith('ID='): return tag[3:]
def _print_field(field_name, field_value, capitals=False): """ Print a field in bib format if value is not none. :param field_name: name of the field :param field_value: value of the field :param capitals: whether to add :return: field in bib format or blank if field is None """ if field...
def linspace(start,stop,np): """ Emulate Matlab linspace """ return [start+(stop-start)*i/(np-1) for i in range(np)]
def sanitize_branch_name(branch_name): """Replace punctuation that cannot be in semantic version from a branch name with dashes.""" return branch_name.replace('/', '-').replace('_', '-')
def varify_label(temp_symbols): """ Parameters ---------- temp_symbols : list temp_symbols contains the label of the segment that is for every heart beats of the segment. Returns ------- varified_label : str """ label = [] N_class = ['N', 'L', 'R', 'e', 'j'] for i i...
def _look_ahead (index_sentence,context, maximum) : """Generate the look ahead context starting with the sentence index and looking no more than max number of sentences""" context_pairs = [] for i in range(1, context+1): s_index = index_sentence+i if s_index<=maximum: contex...
def ele_Q(w, q, n): """ :param w: Angular frequency [1/s], (s:second) q: CPE coefficient, Constant phase element [s^n/ohm] or named as CPE_T n: Constant phase elelment exponent [-] or name as CPE_P :return: Zcpe: Impedance of a Constant phase element ...
def check_int(school, international): """ Checks if a school is an international school based on a school list and other criteria Parameters ---------- school: current school being checked international: AP/IB school list Returns ------- Y or N """ # list of criteria that ...
def not_none(itemlist): """Return true only if no values of None are present""" if itemlist is None: return False if not isinstance(itemlist,(tuple,list)): return True for x in itemlist: if not not_none(x): return False return True
def is_right_bracket(token): """ returns true if token is right bracket """ return token == ")"
def _text_has_spaces(text): """ :param text: :type text: str :return: True if text has any space or false otherwise. :rtype: bool """ words = text.split(" ") if len(words) > 1: return True else: return False
def get_interval(value, num_list): """ Helper to find the interval within which the value lies """ if value < num_list[0]: return (num_list[0], num_list[0]) if value > num_list[-1]: return (num_list[-1], num_list[-1]) if value == num_list[0]: return (num_list[0], num_list...
def convert_string_to_int_keys(input_dict: dict) -> dict: """ Returns the dict with integer keys instead of string keys Parameters ---------- input_dict: dict Returns ------- dict """ return {int(k): v for k,v in input_dict.items()}
def all_equal(t): """ True if all elements in a table are equal. """ return not t[0] == ' ' and t[1:] == t[:-1]
def isfloat(s): """Test if an object is a float""" try: float(s) return True except (ValueError, TypeError): return False
def float_padding(length, val, decimals=2): """Pads zeros to left and right to assure proper length and precision""" return '{0:0>{fill}.{precision}f}'.format(float(val), fill=length, precision=decimals)
def dss_is_geo(dss_schema): """ Check if the input dataset contains a geopoint (DSS storage type) column If so, specific processing will be applied later on :param dss_schema: schema of a dss dataset >>> dss_schema = {"columns": [{"name": "customer_id", "type": "bigint"}]} :return Boolean{input...
def ExpandPattern(pattern, it): """Return list of expanded pattern strings. Each string is created by replacing all '%' in |pattern| with element of |it|. """ return [pattern.replace("%", x) for x in it]
def get_counts_and_averages(ID_and_ratings_tuple): """Given a tuple (bookID, ratings_iterable) returns (bookID, (ratings_count, ratings_avg)) """ nratings = len(ID_and_ratings_tuple[1]) return ID_and_ratings_tuple[0], (nratings, float(sum(x for x in ID_and_ratings_tuple[1]))/nratings)
def format_dict(adict, prefix='', indent=' ', bullets=('* ', '* '), excludes=('_', ), linelen=79): """Return pretty-print of nested dictionary.""" result = [] for k, v in sorted(adict.items(), key=lambda x: x[0].lower()): if any(k.startswith(e) for e in excludes): contin...
def is_similar_mag(a, b, small=1E-4): """ Evaluates similar magnitudes to within small. """ return abs(a-b) <= small
def gcd(x, y): """Calculate the greatest common divisor of two numbers.""" while y != 0: x, y = y, x % y return x
def createYZlabels(y, z, ylabel, yunits, zlabel, zunits): """ Checks that y and z labels are appropriate and tries to make some if they are not. """ if y is None: if ylabel is None: ylabel='j' if yunits is None: yunits='' else: if ylabel is None: ylabel='Latitude' #if yunits is None: yunits=u'...
def check_cross_turn_repetition(context, pred, is_cn=False): """Check the cross-turn repetition. Calcuate tri-gram repetition. Args: context: Words or tokens or token_ids. pred: Words or tokens or token_ids. is_cn: Chinese version repetition detection. If true, calcuate repetition ...
def _replacer(x, pad_size): """Replace a number with its padded hexadecimal representation. Used to tag temporary variables with their calling scope's id. """ # get the hex repr of the binary char and remove 0x and pad by pad_size # zeros try: hexin = ord(x) except TypeError: ...