content
stringlengths
42
6.51k
def update_label_lst(label_lst): """ Desc: label_lst is a list of entity category such as: ["NS", "NT", "NM"] after update, ["B-NS", "E-NS", "S-NS"] """ update_label_lst = [] for label_item in label_lst: if label_item != "O": update_label_lst.append("B-{}".format(label_item)) update_label_lst.append("E-{}".format(label_item)) update_label_lst.append("S-{}".format(label_item)) else: update_label_lst.append(label_item) return update_label_lst
def fix_dn(dn): """Fix a string DN to use ${CONFIGDN}""" if dn.find("<Configuration NC Distinguished Name>") != -1: dn = dn.replace("\n ", "") return dn.replace("<Configuration NC Distinguished Name>", "${CONFIGDN}") else: return dn
def progress_bar_class(p): """Decide which class to use for progress bar.""" p = int(p) if p < 25: return "progress-bar-danger" elif p > 90: return "progress-bar-success" else: return "progress-bar-warning"
def is_palindrome_without_typecast(number): # This condition is defined by the problem statement """ # When num < 0, num is not a palindrome # Also if last digit is zero and number is not zero, it's not - since num can only be zero """ if number < 0 or (number % 10 == 0 and number != 0): return False rev_number = 0 while number > rev_number: # This while condition indicates it's half completed rev_number = rev_number * 10 + number % 10 number = number // 10 # When the length is an odd number, we can get rid of the middle digit by revertedNumber/10 # For example when the input is 12321, at the end of the while loop we get x = 12, revertedNumber = 123, # since the middle digit doesn't matter in palidrome(it will always equal to itself), we can simply get rid of it.> return number == rev_number or (number == rev_number // 10)
def failed(message: str) -> str: """Simply attaches a failed marker to a message :param message: The message :return: String """ return "Failed: " + message
def format_text(txt, size): """ Format a given text in multiple lines. Args: txt: Text to format size: Line size Returns: List of lines. """ res = [] sepchars = ' \t\n\r' txt = txt.strip(sepchars) while len(txt) > size: # Search end of line enx = size while (enx > 0) and (txt[enx] not in sepchars): enx -= 1 # Check no separator in the line if enx == 0: enx = size # Check for a end of line in the line x = txt.find('\n', 0, enx) if x > 0: enx = x # Append line res.append(txt[:enx]) # Remove line from source txt = txt[enx:].strip(sepchars) # Add last line if txt != "": res.append(txt) return res
def _same_dimension(x, y): """Determines if two `tf.Dimension`s are the same. Args: x: a `tf.Dimension` object. y: a `tf.Dimension` object. Returns: True iff `x` and `y` are either both _unknown_ (i.e. `None`), or both have the same value. """ if x is None: return y is None else: return y is not None and x.value == y.value
def is_requirement(line): """ Return True if the requirement line is a package requirement. Returns: bool: True if the line is not blank, a comment, a URL, or an included file """ return line and not line.startswith(('-r', '#', '-e', 'git+', '-c'))
def document_requests_notifications_filter(record, action, **kwargs): """Filter notifications. Returns if the notification should be sent for given action """ if action == "request_declined": decline_reason = record.get("decline_reason", "") action = "{}_{}".format(action, decline_reason.lower()) action_filter_map = { "request_accepted": True, "request_declined_in_catalog": False, "request_declined_not_found": False, "request_declined_other": False, "request_declined_user_cancel": True, } return action_filter_map[action]
def _next_power_of_two(x): """Calculates the smallest enclosing power of two for an input. Args: x: Positive float or integer number. Returns: Next largest power of two integer. """ return 1 if x == 0 else 2**(int(x) - 1).bit_length()
def _xenumerate(iterable, reverse=False): """Return pairs (x,i) for x in iterable, where i is the index of x in the iterable. It's like enumerate(iterable), but each element is (value, index) and not (index, value). This is useful for sorting. """ if reverse: indices = range(len(iterable) - 1, -1, -1) else: indices = range(len(iterable)) return [(iterable[i], i) for i in indices]
def abs(var): """ Wrapper function for __abs__ """ return var.__abs__()
def range(array): """ Return the range between min and max values. """ if len(array) < 1: return 0 return max(array) - min(array)
def expandJSON(jsondata): """ In CMS lumi jsons LS a run can be (and are usually) compress by writing a range of valid lumis [firstLumiinRange, lastLumiinRange] (inclusive of lastLumiinRange) This function uncompresses that for easier internal handling. Args: jsondata (dict) : CMS json lumi data (dict with run : list of LS) """ LSfromFile = jsondata expandedJSON = {} for run in LSfromFile: expandedLS = [] for block in LSfromFile[run]: firstLS, secondLS = block[0], block[1] for i in range(firstLS, secondLS+1): expandedLS.append(i) expandedJSON[run] = expandedLS return expandedJSON
def dict_merge(dict1, dict2): """Merge two dicts. """ if not isinstance(dict1, dict) or not isinstance(dict2, dict): return dict2 for k in dict2: if k in dict1: dict1[k] = dict_merge(dict1[k], dict2[k]) else: dict1[k] = dict2[k] return dict1
def add_lists(list1, list2): """ Add corresponding values of two lists together. The lists should have the same number of elements. Parameters ---------- list1: list the first list to add list2: list the second list to add Return ---------- output: list a new list containing the sum of the given lists """ output = [] for it1, it2 in zip(list1, list2): output.append(it1 + it2) return output
def regional_indicator(c: str) -> str: """Returns a regional indicator emoji given a character.""" return chr(0x1f1e6 - ord('A') + ord(c.upper()))
def switcher(switch_value, v0, v1, switch_state, verbose): """ It updates the switch state according inp values, either "left" of the switch value or "right", respectively swith_state = 0 and switch_state = 1. """ if abs(v0) < switch_value < abs(v1): switch_state = (switch_state + 1) % 2 if verbose: print("Switch point crossed (bottom > up), switch_state =", switch_state) if abs(v0) > switch_value > abs(v1): switch_state = (switch_state + 1) % 2 if verbose: print("Switch point crossed (up > bottom), switch_state =", switch_state) return switch_state
def get_abc(V, E, dE, ddE): """ Given the volume, energy, energy first derivative and energy second derivative, return the a,b,c coefficients of a parabola E = a*V^2 + b*V + c """ a = ddE / 2. b = dE - ddE * V c = E - V * dE + V ** 2 * ddE / 2. return a, b, c
def limited_join(sep, items, max_chars=30, overflow_marker="..."): """Join a number of strings to one, limiting the length to *max_chars*. If the string overflows this limit, replace the last fitting item by *overflow_marker*. Returns: joined_string """ full_str = sep.join(items) if len(full_str) < max_chars: return full_str n_chars = 0 n_items = 0 for j, item in enumerate(items): n_chars += len(item) + len(sep) if n_chars < max_chars - len(overflow_marker): n_items += 1 else: break return sep.join(list(items[:n_items]) + [overflow_marker])
def read_converged(content): """Check if program terminated normally""" error_msg = ['[ERROR] Program stopped due to fatal error', '[WARNING] Runtime exception occurred', 'Error in Broyden matrix inversion!'] for line in reversed(content.split('\n')): if any([msg in line for msg in error_msg]): return False return True
def no_codeblock(text: str) -> str: """ Removes codeblocks (grave accents), python and sql syntax highlight indicators from a text if present. .. note:: only the start of a string is checked, the text is allowed to have grave accents in the middle """ if text.startswith('```'): text = text[3:-3] if text.startswith(('py', 'sql')): text = '\n'.join(text.split('\n')[1:]) if text.startswith('`'): text = text[1:-1] return text
def parse_string(string, grep_for=None, multiple_grep=None, left_separator=None, right_separator=None, strip=False): """ parses string given as argument greps lines containing grep_for string splits the string and return the text between left_separator and right_separator grep_for can be a string <=> multiple_grep == None or an array <=> multiple_grep in ["OR","AND"] """ if "\r\n" in string: new_line = "\r\n" else: new_line = "\n" if grep_for is not None: if multiple_grep is None: string = new_line.join( [line for line in string.split(new_line) if grep_for in line]) elif multiple_grep == "OR": string = new_line.join( [line for line in string.split(new_line) if any(thing in line for thing in grep_for)]) elif multiple_grep == "AND": string = new_line.join( [line for line in string.split(new_line) if all(thing in line for thing in grep_for)]) if left_separator is not None: string = left_separator.join( [item for item in string.split(left_separator)][1:]) if right_separator is not None: string = right_separator.join( [item for item in string.split(right_separator)][:-1]) if strip: string = string.strip() return string
def newline(lines=1): """Get linebreaks""" return '\n' * lines
def scale_list(c, l): """Scales vector l by constant c.""" return [c*li for li in l]
def step(v, direction, step_size): """move step_size in the direction from v""" return [v_i + step_size * direction_i for v_i, direction_i in zip(v, direction)]
def exists(file_name): """ Checks whether a file with the given name exists. """ try: f = open(file_name, "r") f.close() return True except FileNotFoundError: return False
def is_feature_component_start(line): """Checks if a line starts with '/', ignoring whitespace.""" return line.lstrip().startswith("/")
def bucket_by_length(words): """Bucket a list of words based on their lengths""" num_buckets = list(set([len(x) for x in words])) buckets = dict() for x in num_buckets: buckets[x] = list() for word in words: buckets[len(word)].append(word) return buckets
def getDimmedRGB(color, alpha=255): """Returns dimmed RGB values, with low and high pass to ensure LEDs are fully off or on""" if alpha >= 253: # int is 1 return color elif alpha <= 2: # int is 0 return 0, 0, 0 else: p = alpha/255.0 r, g, b = color return int(r*p), int(g*p), int(b*p)
def resolve_attribute(name, bases, default=None): """Find the first definition of an attribute according to MRO order.""" for base in bases: if hasattr(base, name): return getattr(base, name) return default
def factorial(numero): """Calcula el factorial de numero numero int > 0 returns n! """ if numero == 1: return 1 return numero * factorial(numero -1)
def qs1 (al): """ Algo quicksort for a list """ if not al: return [] return (qs1([x for x in al if x < al[0]]) + [x for x in al if x == al[0]] + qs1([x for x in al if x > al[0]]))
def calculate_similarity(d1, d2): """ d1: frequency dictionary for one text d2: frequency dictionary for another text Returns a float representing how similar both texts are to each other """ diff = 0 total = 0 # when word is in both dicts or just in d1 for word in d1.keys(): if word in d2.keys(): diff += abs(d1[word] - d2[word]) else: diff += d1[word] # when word is just in d2 for word in d2.keys(): if word not in d1.keys(): diff += d2[word] total = sum(d1.values()) + sum(d2.values()) similar = 1-diff/total return round(similar, 2)
def remove_duplicates(a, b,c): """ This function removes duplicate values from a list. The lists are passed as positional arguments. It returns a dictionary of unduplicated lists """ i = 0 while i < len(a): j = i + 1 while j < len(a): if a[i] == a[j]: del a[j] del b[j] del c[j] else: j += 1 i += 1 return { "a": a, "b" : b, "c" : c, }
def rivers_with_station(stations): """The function rivers_with_station returns a set of rivers which have an associated station.""" # creates an array of rivers rivers = [] # appends river into river list for each station for station in stations: rivers.append(station.river) # turns it into a set so that there are no repeats return set(rivers)
def retab(text, newtab=' ', oldtab='\t'): """ Replaces all occurrences of oldtab with newtab """ return text.replace(oldtab, newtab)
def At_SO(at, charge): """ Returns atomic energy correction due to spin orbit coupling Input: at (str): Atomic symbol charge (int): Atomic charge Returns: At_SO (float): Energy correction due to spin orbit coupling """ S_dict_neutral = {"B" : -0.05, "C" : -0.14, "O" : -0.36, "F" : -0.61, "Al" : -0.34, "Si" : -0.68, "S" : -0.89, "Cl" : -1.34, "Ga" : -2.51, "Ge" : -4.41, "Se" : -4.3, "Br" : -5.6, "Fe" : -1.84, "I" : -11.548} S_dict_cation = {"C" : -0.2, "N" : -0.43, "F" : -0.67, "Ne" :-1.19, "Si" : -0.93, "P" : -1.43, "Cl" : -1.68, "Ar" : -2.18, "Ge" : -5.37, "As" : -8.04, "Br" : -6.71, "Kr" : -8.16, "I" :-14.028} S_dict_anion = {"B" : -0.03, "O" : -0.26, "Al": -0.28, "P" : -0.45, "S" : -0.88} At_SO = 0.0 # default if charge == 0: if at in S_dict_neutral: At_SO = S_dict_neutral[at] elif charge == +1: if at in S_dict_cation: At_SO = S_dict_cation[at] elif charge == -1: if at in S_dict_anion: At_SO = S_dict_anion[at] return(At_SO)
def paragraphReplacements(tex): """ Replace the Latex command "\CONST{<argument>}" with just argument. """ while (tex.find("\\paragraph") != -1): index = tex.find("\\paragraph") startBrace = tex.find("{", index) endBrace = tex.find("}", startBrace) tex = tex[:index] + ".SH " + tex[startBrace+1:endBrace] + "\n" + tex[endBrace+1:] return tex
def convert_number(number): """ Convert number to , split Ex: 123456 -> 123,456 :param number: :return: """ if number is None or number == 0: return 0 number = int(number) return '{:20,}'.format(number)
def next_question_id(next_ids, id_base): """ Incrementally fetches the next question ID based on the base passage ID. Some questions have the same ID in the RACE dataset (if they are in the same file). We try to make those unique by appending an index before the id. @q_ids is used to keep the counter for each question ID - it is essentially a map from the file name to the count. It will generate ids as follows: 1) 1-middle1548.txt 2) 2-middle1548.txt 3) 3-middle1548.txt 4) ... Use this function to get incremental question IDs. """ index = next_ids.get(id_base, 1) next_ids[id_base] = index + 1 return "{}-{}".format(index, id_base)
def split_path(path): """ Normalise GCSFS path string into bucket and key. """ if path.startswith('gs://'): path = path[5:] path = path.rstrip('/').lstrip('/') if '/' not in path: return path, "" else: return path.split('/', 1)
def get1dgridsize(sz, tpb = 1024): """Return CUDA grid size for 1d arrays. :param sz: input array size :param tpb: (optional) threads per block """ return (sz + (tpb - 1)) // tpb, tpb
def list_product(num_list): """Multiplies all of the numbers in a list """ product = 1 for x in num_list: product *= x return product
def is_critical_error(alarm_name): """Is this a critical error (True) or just a warning (False)?""" # Alarms for the API or Loris are always critical. if any(p in alarm_name for p in ["catalogue-api", "loris", "storage-api"]): return True # Any alarms to do with healthy/unhealthy hosts are critical. if alarm_name.endswith( ( "-not-enough-healthy-hosts", "-unhealthy-hosts", "-5xx-alarm", "_TerminalFailure", ) ): return True # DLQ errors are warnings, not errors. if alarm_name.endswith(("_dlq_not_empty",)): return False # Lambda errors are warnings, not errors. if alarm_name.startswith("lambda-") and alarm_name.endswith("-errors"): return False # Otherwise default to True, because we don't know what this alarm is. return True
def get_corrected_email(email, env_type): """ If you are transfering users from qa to qa, you have to add +migration to make the users unique. (cheating a bit) """ if (env_type): return email # I should add functionality to handle an initial email with a +qa part split_array = email.split("@") return split_array[0] + "+migration" + "@" + split_array[1]
def convert_to_list(element): """ This funciton... :param element: :return: """ if element is None: return "" return [element]
def get_inactive_users(groups): """ Take group list and return groups only with inactive users :param groups: :return: """ inactive_users_list = [] for group in groups: inactive_users = { "group_name": group["group_name"], "users": [ {"name": user["name"], "active": user["active"]} for user in group["users"] if not user["active"] ], } inactive_users_list.append(inactive_users) return inactive_users_list
def printdict(d: dict) -> str: """print a dict in a json-like format""" outstr = "" for item in d.keys(): outstr += "\t" + item + ": " + str(d[item]) + "\n" return outstr.rstrip("\n")
def deep_get(deep_key, dictionary, sep=':'): """Fetches through multiple dictionary levels, splitting the compound key using the specified separator. """ keys = deep_key.split(sep) while keys: dictionary = dictionary[keys.pop(0)] return dictionary
def is_hex(value): """ Returns True if value is a hexadecimal string, otherwise returns False """ try: int(value, 16) return True except (TypeError, ValueError): return False
def is_in_adr_lexicon(text, adr_lexicon_dict): """checks if given text is present in ADR Lexicon dict # Arguments text - text to check adr_lexicon_dict - dict with ADR Lexicon entries # Returns True if present, False otherwise """ for item in adr_lexicon_dict: if item.lower() == text.lower(): return True return False
def inverse_linear(variable, gradient, intercept, factor=1.0): """ Solution to linear function Parameters ---------- integ: float integral value B, C: float (Gradient, intercept) Calibration parameters dil: float Dilution factor. IS: float Internal standard concentration. Returns ------- Operation on integ """ return factor * (variable - intercept) / gradient
def get_invalid_reposlug(reposlugs): """ Checks invalid reposlug """ for x in reposlugs: if len(x.split('/', 1)) != 2 or '' in x.split('/'): return x return None
def count_doubles(val): """Count repeated pair of chars ins a string""" total = 0 for c1, c2 in zip(val, val[1:]): if c1 == c2: total += 1 return total
def ostr(string): """ Truncates to two decimal places. """ return '{:1.2e}'.format(string)
def number(n): """ Receive a number and print it only if is an integer """ return '%d is a number' % n
def wrap_text_to_lines(string, max_chars): """wrap_text_to_lines function A helper that will return a list of lines with word-break wrapping :param str string: The text to be wrapped :param int max_chars: The maximum number of characters on a line before wrapping :return list the_lines: A list of lines where each line is separated based on the amount of max_chars provided """ def chunks(lst, n): """Yield successive n-sized chunks from lst.""" for i in range(0, len(lst), n): yield lst[i : i + n] string = string.replace("\n", "").replace("\r", "") # Strip confusing newlines words = string.split(" ") the_lines = [] the_line = "" for w in words: if len(w) > max_chars: if the_line: # add what we had stored the_lines.append(the_line) parts = [] for part in chunks(w, max_chars - 1): parts.append("{}-".format(part)) the_lines.extend(parts[:-1]) the_line = parts[-1][:-1] continue if len(the_line + " " + w) <= max_chars: the_line += " " + w elif not the_line and len(w) == max_chars: the_lines.append(w) else: the_lines.append(the_line) the_line = "" + w if the_line: # Last line remaining the_lines.append(the_line) # Remove any blank lines while not the_lines[0]: del the_lines[0] # Remove first space from first line: if the_lines[0][0] == " ": the_lines[0] = the_lines[0][1:] return the_lines
def list_depth_count(input_list): """ This function count the maximum depth of a nested list (recursively) This is used to check compatibility of users' input and system API only to be used for list or tuple """ if not isinstance(input_list, (list, tuple)): return 0 if len(input_list) == 0: return 1 return 1 + max(map(list_depth_count, input_list))
def as_list(val): """ Helper function, always returns a list of the input value. :param val: the input value. :returns: the input value as a list. :Example: >>> as_list('test') ['test'] >>> as_list(['test1', 'test2']) ['test1', 'test2'] """ treat_single_value = str if isinstance(val, treat_single_value): return [val] if hasattr(val, "__iter__"): return list(val) return [val]
def remove_dice_from_roll(roll, dice_to_remove): """ This function remove the dice we got in a round if we got an existing combination. """ values = list(roll.values()) for eyes in dice_to_remove: if eyes in values: values.remove(eyes) else: raise ValueError("Value not in list and therefore can not be removed.") return {index: value for index, value in enumerate(values)}
def maybe(x, f): """Returns [f(x)], unless f(x) raises an exception. In that case, [].""" try: result = f(x) output = [result] # pylint:disable=broad-except except Exception: # pylint:enable=broad-except output = [] return output
def get_last_pair(words): """ returns a tuple of the last two words in the list """ return tuple(words[-2:])
def combineImagePaths(centerImagePath, leftImagePath, rightImagePath, centerMeasurement, leftMeasurement, rightMeasurement): """ combines cnter/left/right images and measurements to one list """ # combine measurements measurements = [] measurements.extend(centerMeasurement) measurements.extend(leftMeasurement) measurements.extend(rightMeasurement) # combine image paths imagePaths = [] imagePaths.extend(centerImagePath) imagePaths.extend(leftImagePath) imagePaths.extend(rightImagePath) return imagePaths, measurements
def translate_param(val): """ To use in get_params """ if val in ['taxonomy_terms']: return '{0}[]'.format(val) else: return val
def _read_quoted_string(s, start): """ start: offset to the first quote of the string to be read A sort of loose super-set of the various quoted string specifications. RFC6265 disallows backslashes or double quotes within quoted strings. Prior RFCs use backslashes to escape. This leaves us free to apply backslash escaping by default and be compatible with everything. """ escaping = False ret = [] # Skip the first quote i = start # initialize in case the loop doesn't run. for i in range(start + 1, len(s)): if escaping: ret.append(s[i]) escaping = False elif s[i] == '"': break elif s[i] == "\\": escaping = True else: ret.append(s[i]) return "".join(ret), i + 1
def unique(seq): """Returns unique values in a sequence while preserving order""" seen = set() # Why assign seen.add to seen_add instead of just calling seen.add? # Python is a dynamic language, and resolving seen.add each iteration is more costly # than resolving a local variable. seen_add = seen.add return [x for x in seq if not (x in seen or seen_add(x))]
def fix_coord(screen_size, coord): """Fix coordinates for use in OpenCV's drawing functions PIL images have upside-down co-ordinates and it shafts me every goddamn time, so this function "deals with it" Args: screen_size (tuple): The screen size (width, height) coord (tuple): The x, y coordinate to fix (x, y) Returns: (tuple): The coordinates flipped upside-down """ return (coord[0], ((screen_size[1] - 1) - coord[1]))
def isa_temperature(flightlevel): """ International standard atmosphere temperature at the given flight level. Reference: For example, H. Kraus, Die Atmosphaere der Erde, Springer, 2001, 470pp., Sections II.1.4. and II.6.1.2. Arguments: flightlevel -- flight level in hft Returns: temperature (K) """ # Convert flight level (ft) to m (1 ft = 30.48 cm; 1/0.3048m = 3.28...). z = flightlevel * 30.48 if z <= 11000.: # ICAO standard atmosphere between 0 and 11 km: T(z=0km) = 15 degC, # p(z=0km) = 1013.25 hPa. Temperature gradient is 6.5 K/km. T0 = 288.15 gamma = 6.5e-3 return T0 - gamma * z elif z <= 20000.: # ICAO standard atmosphere between 11 and 20 km: T(z=11km) = -56.5 degC, # p(z=11km) = 226.32 hPa. Temperature is constant at -56.5 degC. T = 216.65 return T elif z <= 32000.: # ICAO standard atmosphere between 20 and 32 km: T(z=20km) = -56.5 degC, # p(z=20km) = 54.75 hPa. Temperature gradient is -1.0 K/km. z0 = 20000. T0 = 216.65 gamma = -1.0e-3 return T0 - gamma * (z - z0) elif z <= 47000.: # ICAO standard atmosphere between 32 and 47 km: T(z=32km) = -44.5 degC, # p(z=32km) = 8.68019 hPa. Temperature gradient is -2.8 K/km. z0 = 32000. T0 = 228.65 gamma = -2.8e-3 return T0 - gamma * (z - z0) elif z <= 47820.070345213892438: # ICAO standard atmosphere between 47 and 47820.070345213892438 km: T(z=47km) = -2.5 degC, # p(z=47km) = 1.10906 hPa. Temperature is constant at -2.5 degC. T = 270.65 return T else: raise ValueError("ISA temperature from flight level not " "implemented for z > 71km")
def mass(item): """Calculate the fuel required for an item, and the fuel required for that fuel, and so on""" fuel = item // 3 - 2 if fuel < 0: return 0 return fuel + mass(fuel)
def error_j(Dj,Pap,Pdc,PolError,exp_loss_jt): """ Calculates the conditional probability for a pulse of intensity mu_j to cause an error, after sifting, in the time slot t. Defined as e_k in Sec. IV of [1]. Parameters ---------- Dj : float, array Expected detection rate. Pap : float Probability of an afterpulse event. Pdc : float Dark count probability. PolError : float Errors in polarisation basis. exp_loss_jt : float, array Loss, per intensity per time slot, decay function. Returns ------- float, array Error rate per intensity per time slot. """ return Pdc + (0.5*Pap*Dj) + PolError*(1 - exp_loss_jt)
def get_prf(tp, fp, fn, get_str=False): """Get precision, recall, f1 from true pos, false pos, false neg.""" if tp + fp == 0: precision = 0 else: precision = float(tp) / (tp + fp) if tp + fn == 0: recall = 0 else: recall = float(tp) / (tp + fn) if precision + recall == 0: f1 = 0 else: f1 = 2 * precision * recall / (precision + recall) if get_str: return '\n'.join([ 'Precision: %.2f%%' % (100.0 * precision), 'Recall : %.2f%%' % (100.0 * recall), 'F1 : %.2f%%' % (100.0 * f1)]) return precision, recall, f1
def process_state(term, valid_transitions): """Process a state and return next state.""" try: return valid_transitions[term] except KeyError as error: raise KeyError(f"Indefinition , Invalid Transition: {error}.")
def human_delta(duration): """Converts seconds into a human-readable delta""" delta = [] if duration // (60**2 * 24 * 365) > 0: delta.append(f"{duration // (60**2 * 24 * 365)} years") duration %= 60**2 * 24 * 365 if duration // (60**2 * 24 * 30) > 0: delta.append(f"{duration // (60**2 * 24 * 30)} months") duration %= 60**2 * 24 * 30 if duration // (60**2 * 24) > 0: delta.append(f"{duration // (60**2 * 24)} days") duration %= 60**2 * 24 if duration // 60**2 > 0: delta.append(f"{duration // 60**2} hours") duration %= 60**2 if duration // 60 > 0: delta.append(f"{duration // 60} minutes") duration %= 60 if duration > 0: delta.append(f"{duration} seconds") if len(delta) == 0: delta = ["Forever"] return ", ".join(delta)
def get_define(name, defines): """Return define value from defines list""" try: return next(d for d in defines if name in d).split('=')[-1] except StopIteration: return None
def get_number(tokens, exclude_comment=True): """Given a list of tokens, gives a count of the number of tokens which are not space tokens (such as ``NEWLINE``, ``INDENT``, ``DEDENT``, etc.) By default, ``COMMMENT`` tokens are not included in the count. If you wish to include them, set ``exclude_comment`` to ``False``. """ nb = len(tokens) for token in tokens: if token.is_space(): nb -= 1 elif exclude_comment and token.is_comment(): nb -= 1 return nb
def compute_rotation_frequency(delta_exponent_b, f_rotation_b, delta_exponent_c, f_rotation_c): """Calculate the rotation frequency between two rotated power spectra. Parameters ---------- delta_exponent_b : float The applied change in exponent value for power spectrum 'B'. f_rotation_b : float The rotation frequency applied to power spectrum 'B'. delta_exponent_c : float The applied change in exponent value for power spectrum 'C'. f_rotation_c : float The rotation frequency applied to power spectrum 'C'. Returns ------- float The frequency rotation point between spectra 'B' & 'C'. Notes ----- **Code Notes** This computes the rotation frequency for two power spectra 'B' & 'C', under the assumption that they are both rotated versions of a the same original power spectrum 'A'. **Derivation** Given an original power spectrum A, then: - B = A*(f_rotation_b/freqs)^delta_exponent_b - C = A*(f_rotation_c/freqs)^delta_exponent_c Therefore, what you want is f_rotation_bc, which is the frequency where B==C. To find this, we can plug everything back into the equation, to find where B[freqs] == C[freqs], which is how we arrive at the solution below. Examples -------- Calculate the rotation frequency between two transformed power spectra: >>> f_rotation = compute_rotation_frequency(0.5, 25, -0.25, 10) """ return (((f_rotation_c**delta_exponent_c) / (f_rotation_b**delta_exponent_b))) ** \ (1/(delta_exponent_c-delta_exponent_b))
def isPerfect(x): """Returns whether or not the given number x is perfect. A number is said to be perfect if it is equal to the sum of all its factors (for obvious reasons the list of factors being considered does not include the number itself). Example: 6 = 3 + 2 + 1, hence 6 is perfect. Example: 28 is another example since 1 + 2 + 4 + 7 + 14 is 28. Note, the number 1 is not a perfect number. """ factors = [] # first taking an empty list # iterate over range from 1 to number x for i in range(1, x): # we dont want to include the number itself so we took the range till x # check if i divides number x evenly if (x % i == 0): factors.append(i) # add factors of the number to the list 'factors' summation = sum(factors) # add the factors of a number if summation == x: # check if sum of factors is equal to the number return True else: return False
def merge(config, defaults={}): """ Merge @config and @defaults In the case of a conflict, the key from config will overide the one in config. """ return dict(defaults, **config)
def safe_split(text, split_chars=' ', start_protected_chars='[', end_protected_chars=']'): """Safely split text even in split_chars are inside protected regions. Protected regions starts with any character from the start_protected_chars argument and ends with any character from the end_protected_chars argument. If a char from split_chars is found inside a protected region it will be ignored and the text will not be splited at that position. """ parts = [] inside_protected_region = False last_part = [] for char in text: if char in start_protected_chars: inside_protected_region = True if char in end_protected_chars: inside_protected_region = False if char in split_chars: if inside_protected_region: last_part.append(char) else: parts.append(u''.join(last_part)) last_part = [] else: last_part.append(char) if last_part: parts.append(u''.join(last_part)) return parts
def termTypeIdentifier(element, dataType): """ Identifies the termtype of the object 'element' based on itself and its datatype 'dataType' and returns it """ if(len(str(element).split(":")) == 2 or "http" in str(element) or dataType == "anyURI"): return 'IRI', '~iri' else: return 'Literal', ''
def count_calls(callers): """Sum the caller statistics to get total number of calls received.""" nc = 0 for calls in callers.values(): nc += calls return nc
def strip_angle_brackets_from_url(url): """Normalize URL by stripping angle brackets.""" return url.lstrip("<").rstrip(">")
def _make_value_divisible(value, factor, min_value=None): """ It ensures that all layers have a channel number that is divisible by 8 :param v: value to process :param factor: divisor :param min_value: new value always greater than the min_value :return: new value """ if min_value is None: min_value = factor new_value = max(int(value + factor / 2) // factor * factor, min_value) if new_value < value * 0.9: new_value += factor return new_value
def s(a,b): """ Similarity matrix """ if a == b: return 2 elif a != b: return -1
def python_include(filename: str): """Syntax conversion for python imports. :param filename: filename to import """ return f'from {filename} import *'
def convert_big_str_numbers(big_num): """Convert big number written with numbers and words to int. Args: big_num (str): number, written with numbers and words. Returns: int: same number as an int. Examples: >>>print(convert_big_str_numbers('101.11 billions')) 101110000000 """ big_num = big_num.replace("$", "") big_num = big_num.split(" ") if "million" in str(big_num): zero = "000000" elif "billion" in str(big_num): zero = "000000000" elif "trillion" in str(big_num): zero = "000000000000" else: zero = "000000000" big_num = big_num[0].split(".") try: big_num = f"{big_num[0]}{big_num[1]}{zero[len(big_num[1]):]}" except IndexError: big_num = f"{big_num[0]}{zero}" return int(big_num)
def rle_kenny(seq: str) -> str: """ Run-length encoding """ compressed = '' last_base = '' rep = 1 for base in seq: if base != last_base: if rep > 1: compressed += str(rep) compressed += base rep = 1 else: rep += 1 last_base = base if rep > 1: compressed += str(rep) return compressed
def parseNeighbors_rank(urls): #Hve to fix this splitting and converting to string """Parses a urls pair string into urls pair.""" parts = urls.split(',') res=float(float(parts[2])/float(parts[3])) return parts[1], res
def _build_link_header(links): """ Builds a Link header according to RFC 5988. The format is a dict where the keys are the URI with the value being a dict of link parameters: { '/page=3': { 'rel': 'next', }, '/page=1': { 'rel': 'prev', }, ... } See https://tools.ietf.org/html/rfc5988#section-6.2.2 for registered link relation types. """ _links = [] for uri, params in links.items(): link = [f"<{uri}>"] for key, value in params.items(): link.append(f'{key}="{str(value)}"') _links.append('; '.join(link)) return ', '.join(_links)
def uptime(total_seconds): """ Gives a human-readable uptime string Thanks to http://thesmithfam.org/blog/2005/11/19/python-uptime-script/ (modified to look like the real uptime command) """ total_seconds = float(total_seconds) # Helper vars: MINUTE = 60 HOUR = MINUTE * 60 DAY = HOUR * 24 # Get the days, hours, etc: days = int(total_seconds / DAY) hours = int((total_seconds % DAY) / HOUR) minutes = int((total_seconds % HOUR) / MINUTE) # 14 days, 3:53 # 11 min s = '' if days > 0: s += str(days) + " " + (days == 1 and "day" or "days") + ", " if len(s) > 0 or hours > 0: s += '{}:{}'.format(str(hours).rjust(2), str(minutes).rjust(2, '0')) else: s += '{} min'.format(str(minutes)) return s
def get_status_code_value(status_code): """function to return appropriate status code value from the dictionary""" status_code_dict = { "100": "Continue", "101": "Switching Protocols", "200": "OK", "201": "Created", "202": "Accepted", "203": "Non-authoritative Information", "204": "No Content", "205": "Reset Content", "206": "Partial Content", "300": "Multiple Choices", "301": "Moved Permanently", "302": "Found", "303": "See Other", "304": "Not Modified", "305": "Use Proxy", "306": "Unused", "307": "Temporary Redirect", "400": "Bad Request", "401": "Unauthorized", "402": "Payment Required", "403": "Forbidden", "404": "Not Found", "405": "Method Not Allowed", "406": "Not Acceptable", "407": "Proxy Authentication Required", "408": "Request Timeout", "409": "Conflict", "410": "Gone", "411": "Length Required", "412": "Precondition Failed", "413": "Request Entity Too Large", "414": "Request-url Too Long", "415": "Unsupported Media Type", "416": "Requested Range Not Satisfiable", "417": "Expectation Failed", "500": "Internal Server Error", "501": "Not Implemented", "502": "Bad Gateway", "503": "Service Unavailable", "504": "Gateway Timeout", "505": "HTTP Version Not Supported", "No Response": "" } return status_code_dict[status_code]
def ap(fs, xs): """ap applies a list of functions to a list of values. Dispatches to the ap method of the second argument, if present. Also treats curried functions as applicatives""" acc = [] for f in fs: for x in xs: acc.append(f(x)) return acc
def _get_sig_data(word: dict): """HELPER: extracts if the sig is in word dictionary :param word: dictionary from the json word :type word: dict :return: if sig, ':' and '$' in the word dictionary, it returns it. otherwise it returns False. :rtype: list """ if "sig" in word: if ":" in word["sig"] and "$" in word["sig"]: return [word["sig"][word["sig"].find(":") + 1:word["sig"].find("=")], word["sig"][word["sig"].find("$") + 1:]] return False
def str_to_int(s): """ Convert a fanfiction number string to an integer. @param s: string to parse/convert @type s: L{str} @return: the number @rtype: L{int} """ s = s.strip().lower() s = s.replace("(", "") s = s.replace(")", "") if s.count(".") > 1: # period can not indicate start of decimal s = s.replace(".", ",") s = s.replace(",", "") if s.endswith("k"): multiplier = 1000 s = s[:-1] elif s.endswith("m"): multiplier = 1000000 s = s[:-1] else: multiplier = 1 if not s: return 0 return int(float(s) * multiplier)
def min_int(la,lb,ia,ib,tol=0.01): """ Given two complete drillholes A, B (no gaps and up to the end of the drillhole), this function returns the smaller of two intervals la = FromA[ia] lb = FromB[ib] and updates the indices ia and ib. There are three possible outcomes - FromA[ia] == FromB[ib]+/- tol. Returns mean of FromA[ia], FromB[ib] and ia+1, ib+1 - FromA[ia] < FromB[ib]. Returns FromA[ia] and ia+1, ib - FromA[ia] > FromB[ib]. Returns FromB[ia] and ia, ib+1 """ if la==lb: return ia+1, ib+1, la if la<lb: return ia+1, ib, la # lb < la ? if lb<la: return ia, ib+1, lb
def _compute_size(start, stop, step): """Algorithm adapted from cpython rangeobject.c """ if step > 0: lo = start hi = stop else: lo = stop hi = start step = -step if lo >= hi: return 0 return (hi - lo - 1) // step + 1
def recorded_views(label): """ Get the dimensions of the view from recorded ones. Parameters ---------- label: string Dictionary key for the view. Returns ------- view: 4-tuple of floats The view ('xmin', 'xmax', 'ymin', 'ymax'). """ views = {} views['snake'] = (-1.0, 2.0, -1.5, 1.5) views['wake'] = (-1.0, 15.0, -4.0, 4.0) views['domain'] = (-15.0, 15.0, -15.0, 15.0) views['default'] = (-1.0, 1.0, -1.0, 1.0) if label not in views.keys(): label = 'default' return views[label]
def roundToMultiple(x, y): """Return the largest multiple of y < x Args: x (int): the number to round y (int): the multiplier Returns: int: largest multiple of y <= x """ r = (x+int(y/2)) & ~(y-1) if r > x: r = r - y return r
def construct_address(host, port, route, args): """ {host}:{port}{route}?{'&'.join(args)} :param str host: '172.0.0.1' :param str port: '5000' :param str route: '/store/file/here' :param list[str] args: ['a=b', 'c=d'] """ return f"http://{host}:{port}{route}?{'&'.join(args)}"