content
stringlengths
42
6.51k
def path2FormatPath(path, hasFormat=None): """Answers the path where the extension is changed to format If format is None, then the extension is removed.""" if path is not None: path = '.'.join(path.split('.')[:-1]) if hasFormat is not None: path += '.' + hasFormat return...
def old_taueff_evo(z): """ F-G taueff. Mainly for testing Parameters ---------- z Returns ------- """ tauevo = 0.001845 * (1+z)**3.924 return tauevo
def unpack(iterable): """ Helper function to unpack an iterable """ unpacked = [] for tt in iterable: for t in tt: unpacked.append(t) return unpacked
def binary_search(array, val): """Binary search.""" sorted_array = sorted(array) i = 0 j = len(array) - 1 while i <= j: mid = (i + j) // 2 if sorted_array[mid] == val: return mid if sorted_array[mid] < val: i = mid + 1 else: j = mid...
def _isArrayLike(obj): """ check if this is array like object. """ return hasattr(obj, '__iter__') and hasattr(obj, '__len__')
def merge(L, R): """Merge two lists.""" ordered_list = [] while len(L) != 0 and len(R) != 0: if L[0] < R[0]: ordered_list.append(L[0]) L.remove(L[0]) else: ordered_list.append(R[0]) R.remove(R[0]) if len(L) == 0: ordered_list +...
def groupby(key, iterable, transform=None): """Group items in `iterable` in a dictionary according to `key`. Parameters ---------- key : function Returns a hashable when given an item in `iterable`. iterable : tuple, list, generator, or array-like The items to be grouped. transf...
def IsFalse(v): """Assert that a value is false, in the Python sense. (see :func:`IsTrue` for more detail) >>> validate = Schema(IsFalse()) >>> validate([]) [] """ if v: raise ValueError return v
def set_title_str(season, day_of_week): """ Generate title string for plot """ dow_str = 'Per Month' if day_of_week == 'All' else "Per Month For {}s".format(day_of_week.title()) return "Season {} | Average Daily Trailhead Users {}".format(season, dow_str)
def extract_results(raw): """Extract results from raw data JSON. Args: raw (list): Pages of raw elections JSON. Returns: list: Results extracted from all pages. """ results = [] for page in raw: results.extend(page["results"]) return results
def check_answer(guess, a_follower, b_follower): """Chcek if the user guessed the correct option""" if a_follower > b_follower: return guess == "a" else: return guess == "b"
def parse_part(part): """Converts KiCad's string representation of a part to a dict.""" if not '\nF ' in part: return None lines = part.split('\n') name = None desc = '' tags = [] link = '' for line in lines: if not ' ' in line: continue key, rest = ...
def retimePadding(frame, retime, size): """ Return the frame with the padding size specified. """ return str(int(frame) + int(retime)).zfill(int(size))
def matches(top, symbol): """ checks if the last found symbol matches with the stack top element """ openingSymbols = "({[" closingSymbols = ")}]" return openingSymbols.index(top) == closingSymbols.index(symbol)
def cal_calculation_sequence_of_all_fireworks(firework_hierarchy_dict): """ Calculate the calculation sequence of all fireworks. The sequence is represented by integers. The smaller the integer of a firework is, the earlier that firework starts. The first firework is labelled by 1 Example: Suppo...
def prune(bushy: dict) -> dict: """ Prune entries in the given dict with false-y values. Boto3 may not like None and instead wants no key. """ pruned = dict() for key in bushy: if bushy[key]: pruned[key] = bushy[key] return pruned
def find_uniq_preserve_order(orig_keys, orig_values=None): """remove duplicate keys while preserving order. optionally return values.""" seen = {} keys = [] values = [] for i, item in enumerate(orig_keys): if item in seen: continue seen[item] = 1 keys.append(item) if orig_values: v...
def prefix(directory, files): """Add a directory as prefix to a list of files. :param str directory: Directory to add as prefix :param List[str] files: List of relative file path :rtype: List[str] """ return ['/'.join((directory, f)) for f in files]
def test_for_scientific_notation_str(value_as_str: str) -> bool: """ Returns True if 'elem' represents a python float in scientific "e notation". e.g. 1.23e-3, 0.09e5 Returns False otherwise """ test_for_float = False try: float(value_as_str) test_for_float = True exc...
def nodekeys_list_table(nodekeys): """Converts List of nodekeys to XML ABAP internal table""" body = '\n'.join(map(lambda key: f'<TV_NODEKEY>{key}</TV_NODEKEY>', nodekeys)) return f'<DATA>\n{body}\n</DATA>'
def bold(s): """Returns the string bold. Source: http://stackoverflow.com/a/16264094/2570866 :param s: :type s: str :return: :rtype: str """ return r'\textbf{' + s + '}'
def optimize(expr, optimizations): """ Apply optimizations to an expression. Parameters ========== expr : expression optimizations : iterable of ``Optimization`` instances The optimizations will be sorted with respect to ``priority`` (highest first). Examples ======== >>> fro...
def get_all_individuals_to_be_vaccinated( vaccinated_compartments, non_vaccination_state, virus_states, areas ): """Get sum of all names of species that have to be vaccinated. Parameters ---------- vaccinated_compartments : list of strings List of compartments from which individuals are vac...
def xy2idx(x, y): """convert a x-y-coordinate to the index of a Cell. Used for testing only""" return x + 9 * y - 10
def diff_dict(dict1: dict, dict2: dict) -> dict: """ find difference between src dict and dst dict Args: src(dict): src dict dst(dict): dst dict Returns: (dict) dict contains all the difference key """ diff_result = {} for k, v in dict1.items(): if k not in...
def updateDictUpdatingValue(dictA, dictB): """ Update `dictA` using `dictB`. However, if key already exists in dictA, does not overwrite dictA[key] with dictB[key], as the defautl update() function does, instead does an update: dictA[key].update( dictB[key] ). Warnings -------- Only works if di...
def _not_cal(not_sign, right): """ Reverse number Args: not_sign (bool): if has not sign right (bool): right number Returns: bool """ if not_sign: right = not right return right
def dec2hex(n): """return the hexadecimal string representation of integer n""" val = '0%X' % n return val[len(val)-2:]
def check_json_keys(json_dict): """ Checks if all required keys are set :param json_dict: dict parsed from json :return: True if required key are set """ required_keys = ["command", "runtime", "weight", "actual_stretch", "graph_information"] required_graph_information = ["nodes", "edges", "d...
def _join_strings(strings, delimiter = ", "): """Joins the given strings with a delimiter. Args: strings: A list of strings to join. delimiter: The delimiter to use Returns: The joined string. """ _ignore = [strings, delimiter] return ""
def skip_i_delete_j(head, i, j): """ :param: head - head of linked list :param: i - first `i` nodes that are to be skipped :param: j - next `j` nodes that are to be deleted return - return the updated head of the linked list """ if i == 0: return None if j == 0: return h...
def outsum(arr): """Fast summation over the 0-th axis. Faster than numpy.sum() """ # cdef np.ndarray thesum return sum([a for a in arr])
def n_gram(token_list, n, c = " "): """ given a token list, return the n-gram version of it """ ret = [] for l in range(1, n+1): for i in range(len(token_list)): if i + l <= len(token_list): ret.append(c.join(token_list[i:i+l])) return ret
def stripe_to_eta(stripe): """Convert from SDSS great circle coordinates to equatorial coordinates. Parameters ---------- stripe : :class:`int` or :class:`numpy.ndarray` SDSS Stripe number. Returns ------- :class:`float` or :class:`numpy.ndarray` The eta value in the SDSS (...
def hsv_to_rgb (h, s, v, a = 1): """ Convert hue, saturation, value (0..1) to RGBA. """ import math f,i = math.modf(h * 6) p = v * (1-s) q = v * (1-f*s) t = v * (1-(1-f)*s) i %= 6 if i == 0: r,g,b = v,t,p elif i == 1: r,g,b = q,v,p elif i == 2: r,g,b = p,v,t elif i == 3: r,g,b = p,q,v ...
def class_test(node): """Determine if a term is a property or a class. Returns True if class, returns False if property.""" its_a_class = False if ":" in node: node = node.split(":")[-1] if node[0].isupper() == True: its_a_class = True return its_a_class
def fixedValue(value, U2): """ Dirichlet boundary condition Assume that value of variable at BC is fixed. Please see any numerical analysis text book for details. Return: float """ Ug = 2 * value - U2 return Ug
def get_cover_image(beatmapset_id: int): """Return url of cover image from beatmapset_id.""" return f"https://assets.ppy.sh/beatmaps/{beatmapset_id}/covers/cover.jpg"
def escape(s): """Escape characters forbidden by Telegram API""" # to_escape = '_*~[]()`#+-|{}.!' # for c in to_escape: # s = s.replace(c, '\\' + c) return s
def month2label(month): """ Convert month to four season numbers :param month: :return: """ if month in [1,2,3]: return 1 elif month in [4,5,6]: return 2 elif month in [7,8,9]: return 3 else: return 4
def transform_input_data(data): """Transform input data dictionary into format ready to use with model.predict""" return {key: [value] for key, value in data.items()}
def unicode_to_ascii(us): """ The data in unicode string actually is utf-8, so we need to convert it to ascii string. Then convert it via decode. """ return "".join([chr(ord(c)) for c in us])
def replace_tree_marks(key, arguments): """ Replace TREE markers from key to proper argument :param key: The currently processed key from .yaml file :param arguments: Arguments already typed for command :return: Key string with replaced marks """ tree_mark_index = key.find('TREE~') while tr...
def downsample(l, n): """Returns every nth element from list l. Returns the original list if n is set to 1. Used to reduce the number of GPS points per activity, to improve performance of the website. """ return l[0::n]
def guess_scheme(environ): """Return a guess for whether 'wsgi.url_scheme' should be 'http' or 'https' """ if environ.get("HTTPS") in ('yes','on','1'): return 'https' else: return 'http'
def sm_section(name): """:return: section title used in .gitmodules configuration file""" return 'submodule "%s"' % name
def match_parentheses(dot, position): """Find matching parenthesis in bracket notation. Args: dot: Bracket notation. position: Position where there is an opening parenthesis to match. Returns: i: Index of matching parenthesis (-1 if nothing was found). """ stack = 0 for...
def frequency(lst, search_term): """Return frequency of term in lst. >>> frequency([1, 4, 3, 4, 4], 4) 3 >>> frequency([1, 4, 3], 7) 0 """ count=0 for num in lst: if num == search_term: count = count+1 return count
def Number_Pad(Number): """Format Dollars amounts to strings & Pad Right 10 Spaces""" Number_Display = f"{Number:,}" Number_Display = f"{Number_Display:>10}" return Number_Display
def strip_trailing_semicolons(source, function): """ Give the source of a cell, filter out lines that contain a specified function call and end in a semicolon. """ filtered=[] for line in source.splitlines(): if line.endswith(f'{function}();'): filtered.append(line[:-1]) ...
def _make_endpoint(entity, exp_id, kwargs): """Return the correct endpoint, given the entity name and experiment_id.""" if "fcs" in entity: entity = "fcsfiles" if exp_id: if "experiment" in entity: endpoint = "/experiments" else: endpoint = f"/experiments/{exp...
def tostr(value,dtype,default_value): """String represenation of a value""" try: value = dtype(value) except: value = default_value value = repr(value) return value
def label_to_pseudochar(label): """ int (0..63) - str ('0' .. 'o') """ return chr(ord('0') + label)
def split_overlap(seq, size, overlap, is_dataframe=False): """(seq,int,int) => [[...],[...],...] Split a sequence into chunks of a specific size and overlap. Works also on strings! It is very efficient for short sequences (len(seq()) <= 100). Set "is_dataframe=True" to split a pandas.DataFrame ...
def fibonacci(end=None, start=0, inclusive=True, length=None): """This function returns a Fibonacci series list: - either upto an end number - or with a length argument which defines the length of the list start number is default to 0 and optinal to change for both. All items in the returnin...
def binary_search(array, key) -> int: """ Binary search algorithm. :param array: the sorted array to be searched. :param key: the key value to be searched. :return: index of key value if found, otherwise -1. >>> array = list(range(10)) >>> for index, item in enumerate(array): ... as...
def indent_n_space(text, n): """ Add indent for each line. """ indent = " " * n return "\n".join([indent + line for line in text.split("\n")])
def isascii(word: str) -> bool: """Check if the characters in string s are in ASCII, U+0-U+7F.""" return len(word) == len(word.encode())
def is_correct_bracket_sequence(brackets: str) -> bool: """ Checks that the obtained bracket sequence is correct. The sequence may consist of characters '(', ')', '[', ']', '{', '}'. >>> is_correct_bracket_sequence('()[]{}') True >>> is_correct_bracket_sequence('([{}])') True >>> is_corr...
def _dict_grouped(date_list, hour_list, value_list, start=0): """Join three list and return as dictionary""" item_list = enumerate(zip(date_list, hour_list, value_list), start=start) return { i: date + hour + value for i, (date, hour, value) in item_list }
def get_character_ngrams(w, n): """Map a word to its character-level n-grams, with boundary symbols '<w>' and '</w>'. Parameters ---------- w : str n : int The n-gram size. Returns ------- list of str """ if n > 1: w = ["<w>"] + list(w) + ["</w>"] else:...
def FindMid(list1): """integer division to find "mid" value of list or string""" length = len(list1) mid = length//2 return mid
def run_model(temperature: int): """ dummy model """ anomaly = temperature < 10 or temperature > 25 return {"anomaly": anomaly}
def add(lh_arg, rh_arg, neg=False): """Helper function to sum arguments. Negates rh_arg if neg is True. """ if rh_arg is not None and neg: rh_arg = -rh_arg if lh_arg is None and rh_arg is None: return None elif lh_arg is None: return rh_arg elif rh_arg is None: ...
def _make_filetags(attributes, default_filetag = None): """Helper function for rendering RPM spec file tags, like ``` %attr(0755, root, root) %dir ``` """ template = "%attr({mode}, {user}, {group}) {supplied_filetag}" mode = attributes.get("mode", "-") user = attributes.get("user", "-"...
def __create_question(indent, question, options, short_descriptions): """ Build the question by attaching the available options with short descriptions. :param indent: How much to indent the description. :type indent: str :param question: The question to ask the user. :type question: str :p...
def list_attr_types_obj(obj): """ return a list of attribute types """ return [type(getattr(obj, name)).__name__ for name in dir(obj) if name[:2]!= '__' and name[-2:] != '__']
def check_melanoma(metadata): """Checking if a image is confirmed melanocytic by ISIC's API. Parameter: metadata: The metadata of the image getting through the API Return: True if the image is confirmed melanocytic, False if it isn't """ if "melanocytic" not in metadata["meta"]["clin...
def is_number(s, cast=float): """ Check if a string is a number. Use cast=int to check if s is an integer. """ try: cast(s) # for int, long and float except ValueError: return False return True
def fatorial_3(number): """Fatorial calculation recursively.""" if number == 0: return 1 else: return number * fatorial_3(number - 1)
def check_diagonals(board): """ Check board by diagonal :param board: list :return: 1, 2, or None """ i = 0 temp = set() for row in board: temp.add(row[i]) i += 1 if len(temp) == 1: return temp.pop() i = 2 temp = set() for row in board: temp.add(row[i]) i -= 1 if len(temp) == 1: return temp...
def __get_list_str(x): """Get value of the categorical variable, and put 3 value in one line :param x: str :return: list """ str_list = x.split('\001') s = '' for i in range(len(str_list)): s += str_list[i] + ',' if (i + 1) % 3 == 0 and i + 1 != len(str_list): s ...
def which_layer(integer): """ Work out which layer an integer is in. """ c = 1 while ((2*c - 1)*(2*c - 1)) <= integer: c += 1 return c
def covariance(a, b): """ Calcula a covariancia entre dois pontos :param a: ponto a :param b: ponto b :return: covariancia entre a e b """ covariance_result = 0 for i in range(len(a)): covariance_result += (a[i] * b[i]) / (len(a) - 1) return covariance_result
def _prepare_pylint_args(args): """ Filter and extend Pylint command line arguments. --output-format=parsable is required for us to parse the output. :param args: list of Pylint arguments. :returns extended list of Pylint arguments. """ # Drop an already specified output format, as we nee...
def is_power_of_2(value): """Check if a value is a power of 2 using binary operations. Parameters ---------- value : `number` value to check Returns ------- `bool` true if the value is a power of two, False if the value is no Notes ----- c++ inspired implementa...
def get_fp_spec(sig_bit: int, exp_bit: int): """Create fp spec which defines precision for floating-point quantization. Args: sig_bit: the number of bits assigned for significand. exp_bit: the number of bits assigned for exponent. Returns: fp spec """ exp_bound = 2**(exp_bit - 1) - 1 prec = {'...
def get_entry_by_id(keys, keyid): """ Returns the first child of keys with ID='keyid'. """ for key in keys: if key.getAttribute("ID") == keyid: return key return False
def _is_latin_1_encodable(value: str) -> bool: """Header values are encoded to latin-1 before sending. We need to generate valid payload. """ try: value.encode("latin-1") return True except UnicodeEncodeError: return False
def format_with_trailing_slash(path): """ :param path: String representing a file path :return: path, but with one "/" at the end """ return path if path[-1] == "/" else path + "/"
def remove_duplicates_by_key(list_to_clear, key_name): """Removes from list_to_clear, a list of dictionaries, all the elements which have 'key_name' and key values equals, lefting only one""" result_list = [] key_values_list = [] for i in list_to_clear: if str(i[key_name]) in key_values_lis...
def to_int(string): """Convert a one element byte string to int for python 2 support.""" if isinstance(string, str): return ord(string[0]) else: return string
def left_child_index(i): """ :param i: int Index of node in array (that is organized as heap) :return: int Position in array of left child of node """ return 2 * (i + 1) - 1
def _to_values(df): """To return dataframe single value as scalar or multiple as numpy array""" return df.values if hasattr(df, 'values') else df
def is_full_slice(obj, l): """ We have a full length slice. """ return ( isinstance(obj, slice) and obj.start == 0 and obj.stop == l and obj.step is None )
def _pkgname_ui(ayum, pkgname, ts_states=None): """ Get more information on a simple pkgname, if we can. We need to search packages that we are dealing with atm. and installed packages (if the transaction isn't complete). """ if ayum is None: return pkgname if ts_states is None: ...
def combine_lines(lines_list): """ Combines a list of lines into one string with newlines. """ # Store the result string. result_string = "" for line in lines_list: result_string += (line + "\n") # Leaves an additional newline at the end which is the same as in the original files. ...
def n_gram_score(n_gram_reference_repeated_list, n_gram_output_repeated_list): """ Returns a score accordingly to repetitions of n-grams that are not present on the target. Only n-grams that appear in the output more than once are checked. """ score = [0 for _ in range(len(n_gram_reference_repeated_lis...
def parse_data(data): """Function that takes the data and parses it.""" type = 'select' if 'INSERT' in data: type = 'insert' command = data return type, command
def truncate_if_str(value, n): """Truncate a value if it's a string, otherwise return the value itself. Args: value: Object to truncate, if it's a string n (int): Number of chars after which to truncate. Returns: truncated: A truncated string, otherwise the original value itself...
def update_parent_child_relationships(links_dict, old_id, new_id): """ Update the parent-child relationships after clustering a firework by replacing all the instances of old_id with new_id Args: links_dict (list): Existing parent-child relationship list old_id (int): Existing id of the ...
def fibonacci_iterative(n): """ Compute the Fibonacci numbers with given number by iterative method :param n: given number :type n: int :return: the Fibonacci numbers :rtype: int """ if n == 0: return 0 elif n == 1: return 1 elif n < 0: return -1 fn,...
def point_num_to_text(num_fita): """ Transform point's order number into text """ num_fita = int(num_fita) num_fita_str = str(num_fita) if len(num_fita_str) == 1: num_fita_txt = "00" + num_fita_str elif len(num_fita_str) == 2: num_fita_txt = "0" + num_fita_str else: num_f...
def climb_stairs(steps): """ :type steps: int :rtype: int """ arr = [1, 1] for _ in range(1, steps): arr.append(arr[-1] + arr[-2]) return arr[-1]
def find_similar_chars_n_sqr(str1, str2): """Returns a string containing only the characters found in both strings Complexity: O(N^2) """ similars = [] for char1 in str1: for char2 in str2: if char1 is char2: similars.append(char1) return ''.join(sorted(similars))
def get_cache_key(archive, browser_type, url): """ Return redis key for given url and cache""" return 'r:' + browser_type + ':' + archive + ':' + url
def contains(latitude_bounds,longitude_bounds,point_to_check): """ This method passes in all the points from the database and then checks for containment in an area. @latitude_bounds - the latitudes of the bounding box @longitude - the longitudes of the bounding box @point_to_check - the point to ch...
def isnamedtupleinstance(x): """ :param x: :return: """ t = type(x) b = t.__bases__ if len(b) != 1 or b[0] != tuple: return False f = getattr(t, '_fields', None) if not isinstance(f, tuple): return False return all(type(n) == str for n in f)
def get_service_dependency_tree(yml_dict, run_exclude_images): """Method to generate a dict of services and services it depends on :param yml_dict: dict generated from docker-compose yml :type yml_dict: dict :param run_exclude_images: List of name of dependency services which ...
def _AsLong(array): """Casts arrays elements to long type. Used to convert from numpy tf.""" return [int(x) for x in array]