content
stringlengths
42
6.51k
def get_leaf_node_attribute(tree, attribute): """Recursively find an attribute of the leaf nodes of a tree. Parameters ---------- tree : dict A dictionary of dictionaries tree structure attribute : str The attribute to find at the root nodes Returns ------- list A list of attributes """ ...
def _heuristic_is_identifier(value): """ Return True if this value is likely an identifier. """ first = str(value)[0] return first != '-' and not first.isdigit()
def getattr_chain(obj, attr_chain, sep='.'): """Get the last attribute of a specified chain of attributes from a specified object. E.g. |getattr_chain(x, 'a.b.c')| is equivalent to |x.a.b.c|. @param obj: an object @param attr_chain: a chain of attribute names @param sep: separator for the cha...
def index_batch_iterator(batch_size, n_sents): """ Return batch indices """ n_batches = n_sents//batch_size if (n_sents % batch_size) != 0: n_batches += 1 low = 0 high = 0 range_list = [] for i in range(n_batches): high = low + batch_size if high > n_sents: ...
def normalise_period(val): """Return an integer from 1 to 12. Parameters ---------- val : str or int Variant for period. Should at least contain numeric characters. Returns ------- int Number corresponding to financial period. Examples -------- >>> normalise_...
def getShortestPaths(paths): """ Returns a list containing only the shortest paths. The list may contain several shorters paths with the same length. """ shortestPaths = [] shortestLength = 99999 for path in paths: if len(path) < shortestLength: shortestLength = len(path) ...
def first_non_zero(arr): """ Return the index of the first element that is not zero, None, nan, or False (basically, what ever makes "if element" True) The other way to do this would be where(arr)[0][0], but in some cases (large array, few non zeros)) this function is quicker. Note: If no elemen...
def flatten(l): """ Concatentates and flattens all numbers together in list of lists """ final = [] for i in range(0, len(l)): if isinstance(l[i], list): final = final + flatten(l[i]) else: final.append(l[i]) return final
def legal(puzzle, i, j, k, diagonal=False): """ Check if k can be placed at the jth column of ith row. Parameters: puzzle (nested list): sudoku grid i (int): row to be checked j (int): column to be checked k (int): number to be placed in puzzle[i][j] ...
def get_dataset_size(data_cfg): """ Note that this is the size of the training dataset """ name = data_cfg['name'] if name == 'mnist': if data_cfg['binary']: N = 10397 else: N = 54000 elif name in ['cifar10', 'cifar10_pretrain','cifar10_cnn']: if data_cfg[...
def get_indices_of_A_in_B(A, B): """Return the set of indices into B of the elements in A that occur in B Parameters ---------- A : list The "needles" B : list The "haystack" Returns ------- list Indices into B of elements in A occuring in B """ s = s...
def _all_none(*args): """Returns a boolean indicating if all arguments are None""" for arg in args: if arg is not None: return False return True
def parse_csl(value, lower=True): """ reads a string that is a comma separated list and converts it into a list of strings stripping out white space along the way :param value: the string to parse :param lower: should we also lowercase everything (default true) :return: a list of strings """...
def convert_faces_into_triangles(faces): """ Converts the faces into a list of triangles :param faces: List of faces containing the triangles :return: A list of the triangles that make a face """ triangles = [] for face in faces: triangles_in_face = len(face) - 2 triangles.ex...
def merge_input_bam(info_dict,path_start): """ Find the input files in the sample info sheet and merge them into one single bam file """ input_files = [] NA_index = [i for i, x in enumerate(info_dict["Input"]) if x == "NA"] all_files = info_dict["Sample"] #full file name with path for i in N...
def filter_staff(thread_url): """ Dirty and quick way to trim some stuff off the end of a url """ if "/page" in thread_url: index = thread_url.rfind("/page") elif "#p" in thread_url: index = thread_url.rfind("#p") else: return thread_url + "/filter-account-type/staff" ...
def get_string_value(value_format, vo): """Return a string from a value or object dictionary based on the value format.""" if "value" in vo: return vo["value"] elif value_format == "label": # Label or CURIE (when no label) return vo.get("label") or vo["id"] elif value_format == "...
def get_response_text(response): """ Combines message and errors returned by a function to create an HTML to be displayed in a modal """ messageHTML = "" if "message" in response: messageHTML += "<h4>" + response["message"] + "</h4>" if "error" in response: for key in re...
def is_same_rectangle(node1, node2, use_ids=False): """ :param node1: :param node2: :param use_ids: :return: """ return (node1["in_element"] == "rectangle" and node1["in_element_ids"] == node2["in_element_ids"] and use_ids) or node1["box"] == node2["box"]
def get_named_parent(decl): """ Returns a reference to a named parent declaration. :param decl: the child declaration :type decl: :class:`declaration_t` :rtype: reference to :class:`declaration_t` or None if not found """ if not decl: return None parent = decl.parent whi...
def parse_ps_results(stdout): """Parse result of `ps` command Parameters ---------- stdout : str Output of running `ps` command Returns ------- list A List of process id's """ # ps returns nothing if not stdout.replace('\n', '').strip(): return [] # ps returns something return [ in...
def sls_cmd(command, spec): """Returns a shell command string for a given Serverless Framework `command` in the given `spec` context. Configures environment variables (envs).""" envs = ( f"STAGE={spec['stage']} " f"REGION={spec['region']} " f"MEMORY_SIZE={spec['memory_size']} " )...
def get_level_name(verbose): """Return the log levels for the CLI verbosity flag in words.""" if verbose > 3: verbose = 3 level_dict = { 0: 'ERROR/FATAL/CRITICAL', 1: 'WARNING', 2: 'INFO', 3: 'DEBUG', } return level_dict[verbose]
def get_sum3(a: int, b: int) -> int: """ My third version, that is just an even more concise version of the first one. """ return sum([i for i in range(min(a, b), max(a, b)+1)])
def sc(txt): """ >>> print(sc('gentle shout')) <span class="sc">gentle shout</span> >>> print(sc('I wish I could be in small caps', tags=False)) I wish I could be in small caps """ return f'<span class="sc">{txt}</span>'
def parse_codesys(info): """ Operating System: Nucleus PLUS Operating System Details: Nucleus PLUS version unknown Product: 3S-Smart Software Solutions """ infos = info.split('\n') data = {} for info in infos: if ':' not in info: continue k, v = info.split(':'...
def streams_to_named_streams(*streams): """ >>> stream_0 = [1, 2, 3, 4, 5, 6] >>> stream_1 = [-1, -2, -3, 0, -5, -6] >>> streams_to_named_streams(stream_0, stream_1) {0: [1, 2, 3, 4, 5, 6], 1: [-1, -2, -3, 0, -5, -6]} """ return dict(enumerate(streams))
def is_key_matured(key, key_params): """ key_params provides full information for key or not """ try: key.format(**key_params) except KeyError: return False else: return True
def replace_in_list(my_list, idx, element): """Replace an element of a list at a specific position.""" if idx >= 0 and idx < len(my_list): my_list[idx] = element return (my_list)
def meanPoint(coordDict): """Compute the mean point from a list of cordinates.""" x, y, z = zip(*list(coordDict.values())) mean = (float(format(sum(x) / len(coordDict), '.2f')), float(format(sum(y) / len(coordDict), '.2f'))) return mean
def humanize_duration(seconds: float) -> str: """Format a time for humans.""" value = abs(seconds) sign = "-" if seconds < 0 else "" if value < 1e-6: return f"{sign}{value*1e9:.1f}ns" elif value < 1e-3: return f"{sign}{value*1e6:.1f}us" if value < 1: return f"{sign}{value...
def tuple_pull_to_front(orig_tuple, *tuple_keys_to_pull_to_front): """ Args: orig_tuple: original tuple of type (('lS', 5.6), ('lT', 3.4000000000000004), ('ZT', 113.15789473684211), ('ZS', 32.10526315789474)) *tuple_keys_to_pull_to_front: keys of those tuples that (in the given order) should be ...
def indexLinePivot(tableaux, minOrMax, _colPivot, _linePivot): #seach index var from base that'll come out """ [seach the index of the variable that is come out] Arguments: tableaux {[matrix]} -- [matrix with all elements] minOrMax {[int]} -- [<= or >=] _colPivot {[int]} -- [ind...
def convert_into_nb_of_days(freq: str, horizon: int) -> int: """Converts a forecasting horizon in number of days. Parameters ---------- freq : str Dataset frequency. horizon : int Forecasting horizon in dataset frequency units. Returns ------- int Forecasting ho...
def unsigned_int(param): """validate if the string param represents a unsigned integer, raises a ValueError Exception on failure""" if param.isdigit(): return True error = 'unsigned integer expected got "{0}" instead'.format(param) raise ValueError(error)
def replace_unknown_letter_in_ref(ref_seq, residue_seq): """ replace unknown letters in the reference sequence, such as "X" or "N" :return: the updated reference sequence which only contains "ACGU" """ if len(ref_seq) != len(residue_seq): return None ref_seq_list = list(ref_seq) for...
def _find_union(lcs_list): """Finds union LCS given a list of LCS.""" return sorted(list(set().union(*lcs_list)))
def merge_elements(el1, el2): """ Helper function to merge 2 element of different types Note: el2 has priority over el1 and can override it The possible cases are: dict & dict -> merge keys and values list & list -> merge arrays and remove duplicates list & str -> add str to array and remo...
def content_is_image(maintype): """Check if HTML content type is an image.""" return maintype in ("image/png", "image/jpeg", "image/gif")
def index_map(args): """Return a dict mapping elements to their indices. Parameters ---------- args : Iterable[str] Strings to be mapped to their indices. """ return {elm: idx for idx, elm in enumerate(args)}
def analyticalMSD(D, t, d): """ Analytical Mean Squared Displacement D = diffusion coefficient t = time step d = dimesion """ return 2 * d * D * t
def bisect_root(f, x0, x1, err=1e-7): """Find a root of a function func(x) using the bisection method""" f0 = f(x0) #f1 = f(x1) while (x1 - x0) / 2.0 > err: x2 = (x0 + x1) / 2.0 f2 = f(x2) if f0 * f2 > 0: x0 = x2 f0 = f2 else: x1 = x2...
def solution(array_size, queries): # O(M * N) """ Starting with a 1-indexed array of zeros and a list of operations, for each operation add a value to each of the array element between two given indices, inclusive. Once all operations have been performed, return the ...
def broadcast(dct): """Convenience function for broadcasting a dictionary of lists. Parameters ---------- dct : dict Input parameter ranges. All parameter ranges must have only 1 or N values. Returns ------- list List of N dictionaries; the input parameters with N values ar...
def get_up_down_filter(filters, field, direction): """ This function returns the appropriate mask to filter on the given field in the given direction. It assumes the filters are in the same order as the output of get_up_and_down_masks. Parameters ---------- filters : tup...
def _small_mie(m, x): """ Calculate the efficiencies for a small sphere. Typically used for small spheres where x<0.1 Args: m: the complex index of refraction of the sphere x: the size parameter of the sphere Returns: qext: the total extinction efficiency qsca: the...
def getFolder(file): """ Gets folder of a specific file """ if "/" in file: return file[:file.rfind("/")+1] else: return ""
def format_decimal(value, mask): """ Format an integer as a decimal string """ if mask is None: return str(value) return "{:d}/{:d}".format(value, mask)
def value2TagName(value): """ The @value2TagName@ class method converts the *value* object into a value XML tag name. """ tagname = [] if not isinstance(value, str): value = str(value) if value.lower().startswith('xml'): tagname.append('_') for c in value: if c in ' !...
def eh_labirinto (maze): """Esta funcao indica se o argumento dado eh um labirinto \ nas condicoes descritas no enunciado do projeto""" if not isinstance(maze,tuple): return False else: for coluna in range(len(maze)): if maze[coluna] == () or type(maze[coluna]) != tuple: ...
def count_words(text): """A function to count the number of times each word occurs in a text. All punctuation marks are skipped. The function returns a dictionary object whose keys are the unique words and values are word counts This function is adapted from the HarvardX course - using python for researc...
def csr_ctype(field_data): """ The type passed to, or returned from, the assembler instruction. """ if "width" in field_data: width=str(field_data["width"]) if width.find("xlen") > 0: return "uint_xlen_t" else: return "uint_csr" + str(width) + "_t" return ...
def _set_main_iv_label(main_iv, main_iv_label): """ Set default main iv label as main iv """ if main_iv_label is None: return main_iv else: return main_iv_label
def TailFile(fname, lines=20): """Return the last lines from a file. @note: this function will only read and parse the last 4KB of the file; if the lines are very long, it could be that less than the requested number of lines are returned @param fname: the file name @type lines: int @param lines...
def is_negated_term(term): """ Checks if a provided element is a term and is a negated term. """ return isinstance(term, tuple) and len(term) > 0 and term[0] == 'not'
def auto_intercept(with_intercept, default): """A more concise way to handle the default behavior of with_intercept""" if with_intercept == "auto": return default return with_intercept
def convert_int(value): """ Try to convert value to integer and do nothing on error :param value: value to try to convert :return: value, possibly converted to int """ try: return int(value) except ValueError: return value
def treeify(node, tree_id, pos=1, level=0): """Set tree properties in memory. """ node['tree_id'] = tree_id node['level'] = level node['left'] = pos for child in node.get('children', []): pos = treeify(child, tree_id, pos=pos + 1, level=level + 1) pos = pos + 1 node['right'] = po...
def hello(name='you'): """The function returns a nice greeting Keyword Arguments: name {str} -- The name of the person to greet (default: {'you'}) Returns: [str] -- The greeting """ return 'Hello, {0}!'.format(name)
def dateIsBefore(year1, month1, day1, year2, month2, day2): """Returns True if year1-month1-day1 is before year2-month2-day2. Otherwise, returns False.""" if year1 < year2: return True if year1 == year2: if month1 < month2: return True if month1 == month2: ret...
def GetCircleArea(r): """Get a circle area. Args: r: the radius. Returns: the area of the circle. """ return 3.14 * r * r
def mean(nums): """ Computes and returns mean of a collection. """ return sum(nums)/len(nums)
def _GreedyMatch(er): """er is list of (weight,e,tl,tr). Find maximal set so that each triangle appears in at most one member of set""" # sort in order of decreasing weight er.sort(key=lambda v: v[0], reverse=True) match = set() ans = [] while len(er) > 0: (_, _, tl, tr) = q = ...
def _get_key_str(key): """ returns full name for collections in TM API """ keys = { 'TM_ID': 'Trismegistos', 'EDB': 'Epigraphic Database Bari', 'EDCS': 'Epigraphik-Datenbank Clauss / Slaby', 'EDR': 'Epigraphic Database Roma', 'CIL': 'Corpus Inscriptionum Latinarum...
def normalize_grobid_id(grobid_id: str): """ Normalize grobid object identifiers :param grobid_id: :return: """ str_norm = grobid_id.upper().replace('_', '').replace('#', '') if str_norm.startswith('B'): return str_norm.replace('B', 'BIBREF') if str_norm.startswith('TAB'): ...
def is_unknown_license(lic_key): """ Return True if a license key is for some lesser known or unknown license. """ return lic_key.startswith(('unknown', 'other-',)) or 'unknown' in lic_key
def SumTotals(dictTotal): """ Summing values in a dictionary. Parameters ---------- dictTotal : TYPE DESCRIPTION. Returns ------- TYPE DESCRIPTION. """ totalVal = 0.0 for keyVal in dictTotal.keys(): for keyVal2 in dictTotal[keyVal].keys(): ...