content
stringlengths
42
6.51k
def derivative_of_binary_cross_entropy_loss_function(y_predicted, y_true): """ Use the derivative of the binary cross entropy (BCE) loss function. Parameters ---------- y_predicted : ndarray The predicted output of the model. y_true : ndarray The actual output value. Returns ------- float The derivative of the BCE loss function. """ numerator = (y_predicted - y_true) denominator = (y_predicted * (1 - y_predicted)) y = numerator / denominator return y
def alwayslist(value): """If input value if not a list/tuple type, return it as a single value list.""" if value is None: return [] if isinstance(value, (list, tuple)): return value else: return [value]
def quote_arg(arg): """Return the quoted version of the given argument. Returns a human-friendly representation of the given argument, but with all extra quoting done if necessary. The intent is to produce an argument image that can be copy/pasted on a POSIX shell command (at a shell prompt). :param arg: argument to quote :type arg: str """ # The empty argument is a bit of a special case, as it does not # contain any character that might need quoting, and yet still # needs to be quoted. if arg == "": return "''" need_quoting = ( "|", "&", ";", "<", ">", "(", ")", "$", "`", "\\", '"', "'", " ", "\t", "\n", # The POSIX spec says that the following # characters might need some extra quoting # depending on the circumstances. We just # always quote them, to be safe (and to avoid # things like file globbing which are sometimes # performed by the shell). We do leave '%' and # '=' alone, as I don't see how they could # cause problems. "*", "?", "[", "#", "~", ) for char in need_quoting: if char in arg: # The way we do this is by simply enclosing the argument # inside single quotes. However, we have to be careful # of single-quotes inside the argument, as they need # to be escaped (which we cannot do while still inside. # a single-quote string). arg = arg.replace("'", r"'\''") # Also, it seems to be nicer to print new-line characters # as '\n' rather than as a new-line... arg = arg.replace("\n", r"'\n'") return "'%s'" % arg # No quoting needed. Return the argument as is. return arg
def check_filename(filename): """ checks if the filename is correct and adapts it if necessary Parameters: filename - media filename return: string: updated filename """ # delete all invaild characters from filename filename = filename.strip() # remove leading and training blanks filename=filename.replace("\n","") filename=filename.replace("\r","") filename=filename.replace(">","") filename=filename.replace("'"," ") filename=filename.replace('"',' ') filename = filename.strip() # remove leading and training blanks #----------------------------------------- # check if filename needs to be adapted to new naming convention # # e.g. old naming convention: " DV_D0017'20051022 16.44.03.avi " # new naming convention: "20051022164403_D0017.avi" # #----------------------------------------- testfilename = filename.lower() test1 = testfilename.find("dv_") # test for old filenames of DV files and correct them test2 = testfilename.find("d8_") # test for old filenames of DV files and correct them test3 = testfilename.find("video_") # test for old filenames of files with video_xx and correct them test4 = testfilename.find("v00") # test for old filenames of files with v00xx and correct them if test1 == 0 or test2 == 0 or test3 == 0 or test4==0: filename_comp = filename.split(" ") if len(filename_comp) >=2: filename_descr = filename_comp[0] filename_date = filename_comp[1] filename_time = filename_comp[2] filename_time_comp = filename_time.split(".") filename = filename_date + filename_time_comp[0] + filename_time_comp[1] + filename_time_comp[2] + "_" + filename_descr + ".avi" return filename
def pull_all_metrics(email): """Obtains list of timestamps/corresponding processes for a user Args: email (str): user email (primary key) Returns: all_metrics """ # check database # print list of timestamps/actions all_metrics = [] return all_metrics
def minmax(array): """Find both min and max value of arr in one pass""" minval = maxval = array[0] for e in array[1:]: if e < minval: minval = e if e > maxval: maxval = e return minval, maxval
def list_remove(list_a, list_b): """ Fine all elements of a list A that does not exist in list B. Args list_a: list A list_b: list B Returns list_c: result """ list_c = [] for item in list_a: if item not in list_b: list_c.append(item) return list_c
def nearest_larger(arr, i): """Finds the nearest item in `arr` which is larger than arr[i]""" distance = 1 while True: left = i - distance right = i + distance if (left < 0) and (right >= len(arr)): return None if (left >= 0) and (arr[left] > arr[i]): return left if (right < len(arr)) and (arr[right] > arr[i]): return right distance += 1 return None
def ratio(value, count): """compute ratio but ignore count=0""" if count == 0: return 0.0 return value / count
def parse_mitie_output(raw_json): """ :param dict raw_json: dict of JSON values :returns list: List of entities """ if 'entities' not in raw_json: return list() return list(set([elem['text'] for elem in raw_json['entities'] if 'text' in elem]))
def human_size(size: int) -> str: """Converts size in bytes to a human-friendly format.""" if size > 1_000_000_000: return f"{size / 1_000_000_000:.1f} GB" if size > 1_000_000: return f"{size // 1_000_000} MB" if size > 1_000: return f"{size // 1_000} KB" return f"{size} B"
def fabclass_2_umax(fab_class=None): # Docstring """ Max dimple displacement. Returns the maximum displacement for a dimple imperfection on a cylindrical shell. The values are taken from table 8.4 of EN1993-1-6[1] for a given fabrication quality class, A, B or C. Parameters ---------- fab_class : {'fcA', 'fcB', 'fcC'} The fabrication quality class. Returns ------- float u_max / l, where u_max is the maximum deviation and l the dimple's size (circumferencial or meridional) References ---------- .. [1] Eurocode 3: Design of steel structures - Part 1-6: Strength and stability of shell structures. Brussels: CEN, 2006. """ # default values if fab_class is None: fab_class = 'fcA' # Assign imperfection amplitude, u_max acc. to the fabrication class if fab_class is 'fcA': u_max = 0.006 elif fab_class is 'fcB': u_max = 0.010 else: u_max = 0.016 # Return values return u_max
def update_name(name, mapping): """ Update the street name using the mapping dictionary. """ for target_name in mapping: if name.find(target_name) != -1: a = name[:name.find(target_name)] b = mapping[target_name] c = name[name.find(target_name)+len(target_name):] name = a + b + c return name
def depends_on_unbuilt(item, deps, built): """ See if item depends on any item not built """ if not item in deps: return False return any(d not in built for d in deps[item])
def str_reindent(s, num_spaces): # change indentation of multine string """ if args: aux= name1+'.'+obj.__name__ +'('+ str(args) +') \n' + str(inspect.getdoc(obj)) aux= aux.replace('\n', '\n ') aux= aux.rstrip() aux= aux + ' \n' wi( aux) """ s = s.split("\n") s = [(num_spaces * " ") + line.lstrip() for line in s] s = "\n".join(s) return s
def output(s: str) -> str: """Returns the string output cyan""" return '\033[96m' + s + '\033[0m'
def root(num,pow): """ Do the roots """ return 1.0*num**(1.0/pow)
def mirror_letter(letter): """ Returns the letter in the same position on the other side of the alphabet. >>> mirror_letter('a') 'z' >>> mirror_letter('z') 'a' >>> mirror_letter('B') 'Y' >>> mirror_letter('C') 'X' """ if letter.isupper(): return chr(155 - ord(letter)) return chr(219 - ord(letter))
def base36encode(num): """Converts a positive integer into a base36 string.""" if not isinstance(num, int): raise TypeError("Positive integer must be provided for base36encode. " + repr(num) + " provided instead.") if not num >= 0: raise ValueError('Negative integers are not permitted for base36encode.') digits = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ' res = '' while not res or num > 0: num, i = divmod(num, 36) res = digits[i] + res return res
def partition_at_level(dendrogram, level): """Return the partition of the nodes at the given level A dendrogram is a tree and each level is a partition of the graph nodes. Level 0 is the first partition, which contains the smallest communities, and the best is len(dendrogram) - 1. The higher the level is, the bigger are the communities Parameters ---------- dendrogram : list of dict a list of partitions, ie dictionaries where keys of the i+1 are the values of the i. level : int the level which belongs to [0..len(dendrogram)-1] Returns ------- partition : dictionary A dictionary where keys are the nodes and the values are the set it belongs to Raises ------ KeyError If the dendrogram is not well formed or the level is too high See Also -------- best_partition : which directly combines partition_at_level and generate_dendrogram : to obtain the partition of highest modularity Examples -------- >>> G=nx.erdos_renyi_graph(100, 0.01) >>> dendrogram = generate_dendrogram(G) >>> for level in range(len(dendrogram) - 1) : >>> print("partition at level", level, "is", partition_at_level(dendrogram, level)) # NOQA """ partition = dendrogram[0].copy() for index in range(1, level + 1): for node, community in partition.items(): partition[node] = dendrogram[index][community] return partition
def sign(a, b): """Return a with the algebraic sign of b""" return (b/abs(b)) * a
def command_friendly_kv_pair(dict): """Converts a dictionary into a list of key=value pairs for use in subprocess run""" # subprocess.run expects parameters to be in the foo=bar format. We build this format here and return a list output = [] for key, value in dict.items(): output.append('%s=%s' % (key, value)) return output
def optimize_distance_with_mistake(distance: float, mistake: float) -> float: """ Using mistake to optimize the walk during runtime Using mistake to shorten or lengthen the walk, but never more then a single hop """ distance_diff = (min(mistake, 1) - 0.5) / 0.5 return distance + distance_diff
def merge(json, firstField, secondField): """ merge two fields of a json into an array of { firstField : secondField } """ merged = [] for i in range(0, len(json[firstField])): merged.append({ json[firstField][i] : json[secondField][i] }) return merged
def hex_to_rgb(col_hex): """Convert a hex colour to an RGB tuple.""" col_hex = col_hex.lstrip('#') return bytearray.fromhex(col_hex)
def up_diagonal_contains_only_os(board): """Check whether the going up diagonal contains only os""" i = len(board) - 1 j = 0 while i >= 0 and j < len(board): if board[i][j] != "O": return False i -= 1 j += 1 return True
def iterative_binary_search(data: list, left: int, right: int, key: str) -> int: """Iterative Binary Search Implementation""" while right >= left: mid = (left + right) // 2 if data[mid] == key: return mid elif key < data[mid]: right = mid - 1 else: left = mid + 1 return -1
def strip_version(r: str) -> str: """ :param r: required package name and required version matcher :return: just the package name """ for symbol in [" ", "~", "<", ">", "="]: i = r.find(symbol) if i != -1: return r[:i].rstrip() return r
def lenient_lowercase(lst): """Lowercase elements of a list. If an element is not a string, pass it through untouched. """ lowered = [] for value in lst: try: lowered.append(value.lower()) except AttributeError: lowered.append(value) return lowered
def concat_classnames(classes): """Concatenate a list of classname strings (without failing on None)""" # SEE: https://stackoverflow.com/a/20271297/11817077 return ' '.join(_class for _class in classes if _class)
def is_a(cls, x): # noqa: F811 """ Check if x is an instance of cls. Equivalent to isinstance, but auto-curried and with the order or arguments flipped. Args: cls: Type or tuple of types to test for. x: Instance. Examples: >>> is_int = sk.is_a(int) >>> is_int(42), is_int(42.0) (True, False) """ return isinstance(x, cls)
def split_pkg(pkg): """nice little code snippet from isuru and CJ""" if not pkg.endswith(".tar.bz2"): raise RuntimeError("Can only process packages that end in .tar.bz2") pkg = pkg[:-8] plat, pkg_name = pkg.split("/") name_ver, build = pkg_name.rsplit("-", 1) name, ver = name_ver.rsplit("-", 1) return plat, name, ver, build
def calcular_tiempo_recorrido(distancias, velocidad): """ Definicion de la funcion calcular_tiempo_recorrido: Funcion de calculo del tiempo de recorrido Parametros ---------- distancias: Pandas Dataframe Dataframe que contiene las distancias entre nodos velocidad: float float con velocidad media del coche Returns ------ tiempos_recorrido: Pandas Dataframe Pandas Dataframe que el tiempo de recorrido para cada arista Ejemplo ------- >>> df_distancias_reduced["Time_h"] = Tiempos.calcular_tiempo_recorrido(df_distancias_reduced["Distance_km"],velocidad_coche) """ tiempos_recorrido = (1.2*distancias)/velocidad return tiempos_recorrido
def get_starting_datetime_of_timetable(timetable): """ Get the starting_datetime of a timetable, which corresponds to the departure_datetime of the first timetable entry. :param timetable: timetable_document :return: starting_datetime_of_timetable: datetime """ timetable_entries = timetable.get('timetable_entries') starting_timetable_entry = timetable_entries[0] starting_datetime_of_timetable = starting_timetable_entry.get('departure_datetime') return starting_datetime_of_timetable
def get_lines(filename): """ return list of lines read from filename """ with open(filename) as infile: return infile.readlines()
def count_positives_sum_negatives(arr): """Return count of postive and sum of negatives""" return [len([elem for elem in arr if elem > 0]), \ sum([elem for elem in arr if elem < 0])] if arr!=[] else arr
def html_escape(text): """Escape text so that it will be displayed safely within HTML""" text = text.replace('&','&amp;') text = text.replace('<','&lt;') text = text.replace('>','&gt;') return text
def smart_pop(word, greek_text): """refactor: this used to have some hackish logic to deal with text nodes with no text, it still prevents a fatal error if something goes wrong and we run out of greeked words """ # if we run out of words, just keep going... if len(greek_text) == 0: return "ERROR" pop_off = greek_text.pop(0) return pop_off
def same_type(t1, t2): """ :return bool: True if 't1' and 't2' are of equivalent types """ if t1 is None or t2 is None: return t1 is t2 if not isinstance(t1, type): t1 = t1.__class__ if not isinstance(t2, type): t2 = t2.__class__ if issubclass(t1, str) and issubclass(t2, str): return True return t1 == t2
def sumList(alist): """ To calcualte the sum of a list of numbers. """ sum = 0 for value in alist: sum += value return sum
def calcSquaredError(actualResult, forecastResult): """ Calculate squared error. returns float """ return (actualResult - forecastResult)**2
def _get_rows_helper(iterableObj, key=None): """ Takes an object and returns a list of rows to use for appending. :param iterableObj: Iterable :param key: If iterableObj had a key to assigned it it's given here """ row = [key] if key else [] if isinstance(iterableObj, (list, tuple)): row.extend(iterableObj) elif isinstance(iterableObj, dict): for _, value in sorted(iterableObj.items()): row.append(value) return row
def get_dict_keys(data, files): """ filters all the keys out of data Args: data: (list of lists of dictionaries) files: (list) Returns: keys: (list) set of keys contained in data """ key_list = [] for i in range(len(data)): data_file = data[i] # iterating over the dicts- list (extracting the essence again) key_list.append(list(data_file)) keys = [] for n in range(len(files)): for i in range(len(key_list[n])): keys.append(key_list[n][i]) keys = list(set(keys)) return sorted(keys)
def round_of_rating(number): """Round a number to the closest half integer. 1.5 2.5 3.0 4.0""" return round(number * 2) / 2
def string_validation(state_input, county_input): """ WHAT IT DOES: Processes the State and County variables to ensure that they are strings PARAMETERS: Two strings representing a state and county in the US RETURNS: A boolean """ has_errors = False try: int_variable = int(state_input) int_variable2 = int(county_input) has_errors = True except: pass return has_errors
def rx_mix(rx_tuple, value): """Build up the regular expression string for the XML When the value has a % in the lead, we need to build a tuple and prepare the string for use in building an XML template for NetLogo invocation. Otherwise, we are reading the .nlogo file in and just adding capture groups to populate the Behavior Space metadata for the model. """ if value[:1] == "%": return rx_tuple[0].replace("__VALUE__", "%s") % tuple( [value.replace("__KEY__", x) for x in rx_tuple[1]] ) else: return rx_tuple[0].replace("__VALUE__", value)
def getFileDialogTitle(msg ,title): """ Create nicely-formatted string based on arguments msg and title :param msg: the msg to be displayed :param title: the window title :return: None """ if msg and title: return "%s - %s" % (title, msg) if msg and not title: return str(msg) if title and not msg: return str(title) return None
def pad_int_str(int_to_pad: int, n: int = 2) -> str: """Converts an integer to a string, padding with leading zeros to get n characters. Intended for date and time formatting. """ base = str(int_to_pad) for k in range(n - 1): if int_to_pad < 10 ** (k + 1): base = "0" + base return base
def generate_positionnal_changes_indicator(string1, string2): """ Generate a string showing the differences between two strings """ changes = "" if len(string1) < len(string2): string_iteration = string1 string_to_compare = string2 else: string_iteration = string2 string_to_compare = string1 for i in range(len(string_iteration)): if string_iteration[i] == string_to_compare[i]: changes += " " else: changes += "^" return changes
def bitVector2num(bitVec: list): """Convert a bit list to a number. The list is assumed to be in "MSB-at-index-0" ordering. Args: bitVec (list): The bit list that we want to convert to a number. Returns: Integer value of input bit vector. """ bitStr = ''.join(str(b) for b in bitVec) return int(bitStr, 2)
def group_property_types(row : str) -> str: """ This functions changes each row in the dataframe to have the one of five options for building type: - Residential - Storage - Retail - Office - Other this was done to reduce the dimensionality down to the top building types. :param: row (str) : The row of the pandas series :rvalue: str :return: One of 5 building types. """ if row == 'Multifamily Housing' or\ row == 'Residence Hall/Dormitory' or\ row == 'Hotel' or\ row == 'Other - Lodging/Residential' or\ row == 'Residential Care Facility': return 'Residential' elif row == 'Non-Refrigerated Warehouse' or\ row == 'Self-Storage Facility' or\ row == 'Refrigerated Warehouse': return 'Storage' elif row == 'Financial Office' or\ row == 'Office': return 'Office' elif row == 'Restaurant' or\ row == 'Retail Store' or\ row == 'Enclosed Mall' or\ row == 'Other - Mall' or\ row == 'Strip Mall' or\ row == 'Personal Services (Health/Beauty, Dry Cleaning, etc.)' or\ row == 'Lifestyle Center' or\ row == 'Wholesale Club/Supercenter': return 'Retail' else: return 'Other'
def get_precision_recall(confusion_table): """ Get precision and recall for each class according to confusion table. :param confusion_table: :return: {class1: (precision, recall), class2, ...} """ precision_recall = {} relations = confusion_table.keys() for target_relation in relations: # true_positive = get_num_pred(confusion_table, target_relation, target_relation) true_positive = confusion_table[target_relation][target_relation] num_target_true = 0 num_target_pred = 0 for relation in relations: # num_target_true += get_num_pred(confusion_table, target_relation, relation) # num_target_pred += get_num_pred(confusion_table, relation, target_relation) num_target_pred += confusion_table[relation][target_relation] num_target_true += confusion_table[relation][target_relation] if true_positive == 0: precision = 0 recall = 0 else: precision = (true_positive + 0.0) / num_target_pred recall = (true_positive + 0.0) / num_target_true precision_recall[target_relation] = (precision, recall) return precision_recall
def air_density(virtual_temperature_k, pressure_hPa): """ Calculate the density of air based on the ideal gas law, virtual temperature, and pressure. Args: virtual_temperature_k: The virtual temperature in units K. pressure_hPa: The pressure in units hPa. Returns: The density of air in units kg m-3. """ gas_constant = 287.0 return pressure_hPa * 100.0 / (gas_constant * virtual_temperature_k)
def to_unit_memory(number): """Creates a string representation of memory size given `number`.""" kb = 1024 number /= kb if number < 100: return '{} Kb'.format(round(number, 2)) number /= kb if number < 300: return '{} Mb'.format(round(number, 2)) number /= kb return '{} Gb'.format(round(number, 2))
def edit_distance(word_one, word_two): """ Find the edit distance between two words """ # short-circuit conditions if word_one == word_two: return 0 shorter = min(word_one, word_two, key=len) longer = max(word_one, word_two, key=len) if not shorter and longer: return len(longer) edit_matrix = [] for _ in range(len(word_one)): row = [0] * len(word_two) edit_matrix.append(row) for idx_one, char_one in enumerate(word_one): for idx_two, char_two in enumerate(word_two): edit = 0 if char_one == char_two else 1 prev_edits = [] # check above if idx_one > 0: prev_edits.append(edit_matrix[idx_one-1][idx_two]) # check left if idx_two > 0: prev_edits.append(edit_matrix[idx_one][idx_two-1]) # check diagonal if idx_one > 0 and idx_two > 0: prev_edits.append(edit_matrix[idx_one-1][idx_two-1]) prev_edit_min = min(prev_edits) if prev_edits else 0 edit_matrix[idx_one][idx_two] = prev_edit_min + edit return edit_matrix[-1][-1]
def calculate_chunk_slices(items_per_chunk, num_items): """Calculate slices for indexing an adapter. Parameters ---------- items_per_chunk: (int) Approximate number of items per chunk. num_items: (int) Total number of items. Returns ------- list of slices """ assert items_per_chunk > 0 assert num_items > 0 return [slice(i, min(i + items_per_chunk, num_items)) for i in range(0, num_items, items_per_chunk)]
def sizeof_fmt(num, suffix='B'): """ Adapted from https://stackoverflow.com/a/1094933 Re: precision - display enough decimals to show progress on a slow (<5 MB/s) Internet connection """ precision = {'': 0, 'Ki': 0, 'Mi': 0, 'Gi': 3, 'Ti': 6, 'Pi': 9, 'Ei': 12, 'Zi': 15} for unit in ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi']: if abs(num) < 1024.0: format_string = "{number:.%df} {unit}{suffix}" % precision[unit] return format_string.format(number=num, unit=unit, suffix=suffix) num /= 1024.0 return "%.18f %s%s" % (num, 'Yi', suffix)
def cal_rmse(actual_readings, predicted_readings): """Calculating the root mean square error""" square_error_total = 0.0 total_readings = len(actual_readings) for i in range(0, total_readings): error = predicted_readings[i] - actual_readings[i] square_error_total += pow(error, 2) rmse = square_error_total / float(total_readings) return rmse
def get_choice(text = None): """ gets users choice from a numbered list """ try: choice = int(input(text if text else "Choose something...\n")) return choice except Exception as error: print("Please don't be a douche, input a valid number.") return 0
def convert(text): """Convert digits to alphanumeric text""" if text.isdigit(): return int(text) else: return text
def sanitize_device(device): """returns device id if device can be converted to an integer""" try: return int(device) except (TypeError, ValueError): return device
def render_tile(tile): """ For a given tile, render its character :param tile: :returns str value of tile """ # each tile list has the meaning: [Visible (bool), Mine (bool), Adjacent Mines (int)] # visible, mine, adjacent_mines = tile if tile[0]: # if the tile is visible if tile[1]: # if the tile is a mine return "X" elif tile[2]: # if the tile has neighboring mines return str(tile[2]) else: return " " else: return "+"
def _pkg_curated_namespace(package): """ Strips out the package name and returns its curated namespace. """ return f"curated-{package.split('/', 1)[0]}"
def _check_if_position_on_board(coord: tuple, board_size: int): """ checks whether coordinates are inside of board :param coord: :param board_size: :return: """ in_row = coord[0] in range(board_size) in_col = coord[1] in range(board_size) return in_row and in_col
def param_to_string(param): """ Helper function for random_generator, creates a string from the param dict :param param_dict: param_dict from random_generator :return: string of params """ string = "<p>Search results for these parameters: </p>" if param == {}: return "<p></p>" for key, value in param.items(): if isinstance(value, dict): string += "<p> " + key + ": " + "from " + str(value['from']) + " to " + str(value["to"]) + "</p>" else: if not isinstance(value, list): string += "<p> " + key + ": " + " ".join(value) + "</p>" else: string += "<p> " + key + ": " + str(value) + "</p>" return string
def get_spline_knot_values(order): """Knot values to the right of a B-spline's center.""" knot_values = {0: [1], 1: [1], 2: [6, 1], 3: [4, 1], 4: [230, 76, 1], 5: [66, 26, 1]} return knot_values[order]
def strlen(s): """ Returns the length of string s using recursion. Examples: >>> strlen("input") 5 >>> strlen("") 0 >>> strlen('123456789') 9 >>> strlen("I love software engineering") 27 >>> strlen('a'*527) 527 """ if s == "": return 0 else: return strlen(s[1:]) + 1
def to_from(arr): """Convert two elements list into dictionary 'to-from'. """ try: return {'from':arr[0], 'to':arr[1]} except IndexError: return None
def score_sentences(sen1, sen2): """ Compares two sentences, find intersection and scores them :param sen1: (str) sentence :param sen2: (str) sentence :returns: score """ s1 = set(sen1.lower().split()) s2 = set(sen2.lower().split()) score = 0 if s1 and s2: avg = len(s1) + len(s2) / 2.0 score = len(s1.intersection(s2)) / avg return score
def process_data(data): """ Pre-process the given data to make textual string searches easier. """ return ( data .lower() # Force lowercase .replace('/', '\\') # Force backslashes )
def assert_lrp_epsilon_param(epsilon, caller): """ Function for asserting epsilon parameter choice passed to constructors inheriting from EpsilonRule and LRPEpsilon. The following conditions can not be met: epsilon > 1 :param epsilon: the epsilon parameter. :param caller: the class instance calling this assertion function """ if epsilon <= 0: err_head = "Constructor call to {} : ".format(caller.__class__.__name__) err_msg = err_head + "Parameter epsilon must be > 0 but was {}".format(epsilon) raise ValueError(err_msg) return epsilon
def pretty_print_dict(dtmp): """Pretty prints an un-nested dictionary Parameters ---------- dtmp : dict Returns ------- str pretty-printed dictionary """ ltmp = [] keys = dtmp.keys() maxlen = 2 + max([len(K) for K in keys]) for k, v in sorted(dtmp.items(), key=lambda x: x[0]): if type(v) == type(""): v = "'%s'" % v new_k = "'%s'" % k stmp = (" {0:<%s} : {1}," % maxlen).format(new_k, v) ltmp.append(stmp) sout = "\n".join(ltmp) return "{\n%s\n}\n" % sout
def bytes_filesize_to_readable_str(bytes_filesize: int) -> str: """Convert bytes integer to kilobyte/megabyte/gigabyte/terabyte equivalent string""" if bytes_filesize < 1024: return "{} B" num = float(bytes_filesize) for unit in ["B", "KB", "MB", "GB"]: if abs(num) < 1024.0: return "{:.1f} {}".format(num, unit) num /= 1024.0 return "{:.1f} {}".format(num, "TB")
def create_context(machine, arch, scripts_path): """ Create a context object for use in deferred function invocation. """ context = {} context["machine"] = machine context["arch"] = arch context["scripts_path"] = scripts_path return context
def AB2Jy(ABmag): """Convert AB magnitudes to Jansky""" return 10.**(-0.4*(ABmag+48.60))/1e-23
def IncludeCompareKey(line): """Sorting comparator key used for comparing two #include lines. Returns the filename without the #include/#import prefix. """ for prefix in ('#include ', '#import '): if line.startswith(prefix): return line[len(prefix):] return line
def format_call(__name, *args, **kw_args): """ Formats a function call as a string. (Does not call any function.) >>> import math >>> format_call(math.hypot, 3, 4) 'hypot(3, 4)' >>> format_call("myfunc", "arg", foo=42, bar=None) "myfunc('arg', foo=42, bar=None)" @param __name The name of the function, or the function itself. """ name = __name.__name__ if hasattr(__name, "__name__") else str(__name) args = [ repr(a) for a in args ] args.extend( n + "=" + repr(v) for n, v in kw_args.items() ) return name + "(" + ", ".join(args) + ")"
def parse_path_expr(expr): """ parses the path expresssion passed, expects path to be separated via forward slashes like directory traversing i.e. '1/4/10' """ if expr is not None: return [segment for segment in expr.split("/") if segment != ""] return None
def delta(vec, elem): """ :param vec: list of values :param elem: value being measured between :return: list of delta and index pairs """ return [(abs(elem-item), i) for i, item in enumerate(vec)]
def get_new_size(original_size): """ Returns each width and height plus 2px. :param original_size: Original image's size :return: Width / height after calculation :rtype: tuple """ return tuple(x + 2 for x in original_size)
def exception_exists(results): """Calculate the number of exceptions in the argument 'results' Args: results (list) Retuns: the number of exceptions in results """ if not isinstance(results, list): raise TypeError( f'Expected type is list, but the argument type is {type(results)}' ) exc = list(filter( lambda result: isinstance(result, Exception), results) ) return len(list(exc))
def get_prefixed(strs, prefix): """Get all string values with a prefix applied to them. :param strs: a sequence of strings to be given a prefix. :param prefix: a prefix to be added to the strings :returns: a list of prefixed strings """ return [prefix + n for n in strs]
def bezout(a, b): """ :return s and t st. sa + tb = (a,b) """ s, t, sn, tn, r = 1, 0, 0, 1, 1 while r != 0: q, r = divmod(a, b) st, tt = sn * (-q) + s, tn * (-q) + t s, t = sn, tn sn, tn = st, tt a, b = b, r return s, t
def dict2list(thedict, parmnames, default=None): """ Convert the values in thedict for the given list of parmnames to a list of values. """ return [thedict.get(n, default) for n in parmnames]
def get_pv_status(pv_obj): """ Get the status of the pv object Args: pv_obj (dict): A dictionary that represent the pv object Returns: str: The status of the pv object """ return pv_obj.get("status").get("phase")
def _str2float(s): """Cast string to float if it is not None. Otherwise return None. Args: s (str): String to convert or None. Returns: str or NoneType: The converted string or None. """ return float(s) if s is not None else None
def value_if_found_else_key(some_dict, key): """Lookup a value in some_dict and use the key itself as fallback""" return some_dict.get(key, key)
def mac_addr_reverse_byte_order(mac_addr): """Reverse the byte order of a 48 bit MAC address.""" mac_addr_reversed = 0 for i in range(6): mac_addr_reversed |= ((mac_addr >> 8*i) & 0xFF) << 8*(5-i) return mac_addr_reversed
def get_attr_count(ent, attr_dict, dataset): """ calculate count of attributes of given entity """ if ent not in attr_dict: return 0 return len(attr_dict[ent])
def wrap_traj(traj, start, length): """Wraps the traj such that the original traj starts at frame `start` and is of length `length` by padding beginning with traj[0] and end with traj[-1]. Used to test the slice restricted trajectories.""" if (start < 0) or (length < len(traj)+start): raise ValueError("""wrap_traj: start < 0 or length < len(traj)+start {0} < 0 or {1} < {2}+{0}""".format( start, length, len(traj))) outtraj = traj[:] # shallow copy # prepend for i in range(start): outtraj.insert(0, traj[0]) # append for i in range(length - (len(traj)+start)): outtraj.append(traj[-1]) return outtraj
def reverse(string): """ Reverse the order of the characters in a string. """ return string[::-1]
def spc_queue(runlst, fml): """ Build spc queue from the reaction lst for the drivers. Use the formula to discern if run_lst is SPC or PES :return spc_queue: all the species and corresponding models in rxn :rtype: list[(species, model),...] """ if fml == 'SPC': _queue = runlst else: _ini_queue = [] for (_, chnl) in runlst: _ini_queue += [rgt for rgts in chnl for rgt in rgts] # Remove duplicates from the queue, perserving order _queue = tuple(i for n, i in enumerate(_ini_queue) if i not in _ini_queue[:n]) return _queue
def is_in_coverage(unixtime, weathers_list): """ Checks if the supplied UNIX time is contained into the time range (coverage) defined by the most ancient and most recent *Weather* objects in the supplied list :param unixtime: the UNIX time to be searched in the time range :type unixtime: int :param weathers_list: the list of *Weather* objects to be scanned for global time coverage :type weathers_list: list :returns: ``True`` if the UNIX time is contained into the time range, ``False`` otherwise """ if not weathers_list: return False min_of_coverage = min(weather.reference_time() for weather in weathers_list) max_of_coverage = max([weather.reference_time() \ for weather in weathers_list]) return unixtime >= min_of_coverage and unixtime <= max_of_coverage
def filter_keys(item): """ Returns first element of the tuple or ``item`` itself. :param object item: It can be tuple, list or just an object. >>> filter_keys(1) ... 1 >>> filter_keys((1, 2)) ... 1 """ if isinstance(item, tuple): return item[0] return item
def convert_ds_name(ds): """Convert from dataset ID to more easily understood string.""" ref_name = ['T','C','V','L'] if isinstance(ds, str): ds = ds[-4:] else: ds = f'{int(ds):04d}' for c_idx, c in enumerate(ds): if c == '0': ref_name[c_idx] = '-' return ''.join(ref_name)
def merge(a, b, path=None): """ Merges b into a, mainly: https://stackoverflow.com/questions/7204805/how-to-merge-dictionaries-of-dictionaries/7205107#7205107 """ path = [] if path is None else path for key in b: if key in a: if isinstance(a[key], list) and isinstance(b[key], list): a[key].extend(b[key]) elif isinstance(a[key], dict) and isinstance(b[key], dict): merge(a[key], b[key], path + [str(key)]) elif a[key] == b[key]: pass # same leaf value else: a[key] = b[key] else: a[key] = b[key] return a
def removeDuplicates(nums): """ TimeComplexity: O(n) SpaceComplexity: O(1) """ i = 0 for j in range(len(nums)): if nums[i] != nums[j]: i += 1 nums[i], nums[j] = nums[j], nums[i] return nums[0 : i + 1]
def IsNumber(value): """ Return True if value is float or integer number. """ return bool(not isinstance(value, bool) and (isinstance(value, int) or isinstance(value, float)))
def _prepare_json(paths): """Prepare json.""" return { index: [ cosa for cosa in path ] for index, path in enumerate(paths) }
def keys_from_bucket_objects(objects): """Extract keys from a list of S3 bucket objects.""" return [x["Key"] for x in objects if not x["Key"].endswith("/")]