content
stringlengths
42
6.51k
def get_assume_role_input(role_arn, duration): """Create input for assume_role.""" return { 'RoleArn': role_arn, 'RoleSessionName': 'cwe_update_target_LambdaFunction', 'DurationSeconds': duration }
def make_length_code(length): """ A websockets frame contains an initial length_code, and an optional extended length code to represent the actual length if length code is larger than 125 """ if length <= 125: return length elif length >= 126 and length <= 65535: return 126 else: return 127
def sweep_trailing_and_stringify(state_data): """At the end of the input stream, close the current field and record, then transform the input character lists into strings""" curr_field, curr_string, curr_rec, past_recs = state_data if curr_string: curr_field += curr_string if curr_field: curr_rec += [curr_field] if curr_rec: past_recs += [curr_rec] records = [] for rec in past_recs: record = [] for fld in rec: record.append("".join(fld)) records.append(record) return records
def GetSourceFile(file, sourcepath): """Return a relative file if it is embedded in a path.""" for root in sourcepath: if file.find(root) == 0: prefix_length = len(root) if not root.endswith('/'): prefix_length += 1 relative_file = file[prefix_length:] return relative_file return None
def escape_string(value): """escape_string escapes *value* but not surround it with quotes. """ value = value.replace('\\', '\\\\') value = value.replace('\0', '\\0') value = value.replace('\n', '\\n') value = value.replace('\r', '\\r') value = value.replace('\032', '\\Z') value = value.replace("'", "\\'") value = value.replace('"', '\\"') return value
def is_empty(obj): """is_empty: Check if str object is empty. :obj: :returns: Bool """ if isinstance(obj, str): return not bool(obj.strip() and ' ' not in obj) elif obj is None: return True else: return obj == '' or str(obj).isspace()
def rgb_to_dec(value): """ Converts rgb to decimal colours (i.e. divides each value by 256) value: list (length 3) of RGB values Returns: list (length 3) of decimal values""" return [v / 256 for v in value]
def int_def(value, default=0): """Parse the value into a int or return the default value. Parameters ---------- value : `str` the value to parse default : `int`, optional default value to return in case of pasring errors, by default 0 Returns ------- `int` the parsed value """ try: return int(value) except ValueError: return default
def round_down(num, factor): """Rounds num to next lowest multiple of factor.""" return (num // factor) * factor
def definition_list(term: str, *definitions: str) -> str: """Return a Markdown definition list.""" definitions_markdown = "".join(f": {definition}\n" for definition in definitions if definition) return f"{term}\n{definitions_markdown}\n" if definitions_markdown else ""
def seg_list(generate_test_segments): """A preset list of segments for testing.""" return generate_test_segments(['bar', ' \t ', 'foo', 'baar', ' \t '])
def ising_trans(x): """ Transformation to Ising notation. :param x: (int) Value of a single binary bit from {0, 1}. :return: Transformed bit value from {-1, 1}. :rtype: Integer. """ if x == 1: return -1 else: return 1
def separate_callback_data(data): """ Separate the callback data""" return data.split(";")[1:]
def levenshtein(a, b, max_dist=float("inf")): """Calculates the Levenshtein distance between a and b.""" n, m = len(a), len(b) if abs(n - m) > max_dist: return float("inf") if n > m: # Make sure n <= m, to use O(min(n,m)) space a, b = b, a n, m = m, n current = range(n + 1) for i in range(1, m + 1): previous, current = current, [i] + [0] * n for j in range(1, n + 1): add, delete = previous[j] + 1, current[j - 1] + 1 change = previous[j - 1] if a[j - 1] != b[i - 1]: change = change + 1 current[j] = min(add, delete, change) return current[n]
def fix_pages(p): """update the hyphenation between page ranges""" if p is None: return None return p.replace("--", "&ndash;")
def filename_id_mapping(imgs_info: list): """ create id mapping among filename and img id. """ filename_to_id = dict() id_to_filename = dict() id_lists = list() for img in imgs_info: filename = img['file_name'] img_id = img['id'] id_lists.append(img_id) filename_to_id[filename] = img_id id_to_filename[img_id] = filename return filename_to_id, id_to_filename, id_lists
def convertHEXtoDEC(hexString, N): """ Return 2's compliment of hexString """ for hexChar in hexString: asciiNum = ord(hexChar) if not ((asciiNum >= 48 and asciiNum <= 57) or (asciiNum >= 65 and asciiNum <= 70) or (asciiNum >= 97 and asciiNum <= 102)): val = float('nan') return val if len(hexString) == N: val = int(hexString, 16) bits = 4*len(hexString) if (val & (1 << (bits-1))) != 0: val = val - (1 << bits) return val
def _safe_len(an_object): """Returns len(an_object), or 0 if the object doesn't support len().""" return len(an_object) if hasattr(an_object, "__len__") else 0
def extract_age(s): """Regularize age data.""" if s in ["16+", "Yes"]: return "16" if s in ["No"]: return "18" return ""
def hopcroft_karp(graph, n, m): """ Maximum bipartite matching using Hopcroft-Karp algorithm, running in O(|E| sqrt(|V|)) """ assert(n == len(graph)) match1 = [-1]*n match2 = [-1]*m # Find a greedy match for possible speed up for node in range(n): for nei in graph[node]: if match2[nei] == -1: match1[node] = nei match2[nei] = node break while 1: bfs = [node for node in range(n) if match1[node] == -1] depth = [-1] * n for node in bfs: depth[node] = 0 for node in bfs: for nei in graph[node]: next_node = match2[nei] if next_node == -1: break if depth[next_node] == -1: depth[next_node] = depth[node] + 1 bfs.append(next_node) else: continue break else: break pointer = [len(c) for c in graph] dfs = [node for node in range(n) if depth[node] == 0] while dfs: node = dfs[-1] while pointer[node]: pointer[node] -= 1 nei = graph[node][pointer[node]] next_node = match2[nei] if next_node == -1: # Augmenting path found while nei != -1: node = dfs.pop() match2[nei], match1[node], nei = node, nei, match1[node] break elif depth[node] + 1 == depth[next_node]: dfs.append(next_node) break else: dfs.pop() return match1, match2
def indent(text, indent=4): """Indents text with spaces.""" return u'\n'.join([u' ' * indent + x for x in text.splitlines()])
def is_fiat(currency): """ Returns true if the specified currency is a fiat currency. """ return currency == 'EUR' or currency == 'USD'
def boolify(value): """ Convert a string to a bool, if not possible, raise a ValueError. Parameters ---------- value : str value to convert. """ if value.lower() == "true": return True elif value.lower() == "false": return False raise ValueError("{} is not a bool".format(value))
def frenchTextNull(frenchInputNull): """ This function returns true if input is empty """ if frenchInputNull == '': return True
def get_is_absolute_path(s_command: str) -> bool: """ >>> assert get_is_absolute_path('/home/user/test test/test test.sh') >>> assert not get_is_absolute_path('./test test/test test.sh') >>> assert not get_is_absolute_path('test test/test test.sh') """ if s_command.startswith('/'): return True else: return False
def set_payload(e: str, p: str, t: str) -> dict: """ e: email p: password t: token -> returns a dict """ payload = { 'email': e, 'password': p, '_token': t, 'remember': 'off' # it's off because why not? } return payload
def clamp(x, min_val, max_val): """Return min(max_val, max(min_val, x)), with x and y floats or float vectors.""" return min(max_val, max(min_val, x))
def factorial_recur(n): """Nth number of factorial series by recursion. - Time complexity: O(n) - Space complexity: O(n). """ # Base case. if n <= 1: return 1 return n * factorial_recur(n - 1)
def monomial_lcm(a, b): """Least common multiple of tuples representing monomials. Lets compute LCM of x**3*y**4*z and x*y**2: >>> monomial_lcm((3, 4, 1), (1, 2, 0)) (3, 4, 1) which gives x**3*y**4*z. """ return tuple([ max(x, y) for x, y in zip(a, b) ])
def simple_first(kv): """Helper function to pass to sort_keys to sort simple elements to the top, then container elements. """ return isinstance(kv[1], (list, dict, tuple)), kv[0]
def name_paths(name_article): """ provide article type make the needed files """ name_src = str(name_article + '_search') name_dst = str('df_' + name_article + '_search') name_summary = str('sum_' + name_article) name_unique = str(name_article + '_unique') plot_unique = str(name_article + '_unique_plot') return name_src, name_dst, name_summary, name_unique, plot_unique
def slice_dict(in_dict, subslice): """Create a new `dict` by taking a slice of of every array in a `dict` Parameters ---------- in_dict : `dict` The dictionary to conver subslice : `int` or `slice` Used to slice the arrays Returns ------- out_dict : `dict` The converted dicionary """ out_dict = {} for key, val in in_dict.items(): try: out_dict[key] = val[subslice] except (KeyError, TypeError): out_dict[key] = val return out_dict
def list_to_string(list_in): """ Converts a list to a string """ string_out = '' for tu in list_in: string_out = string_out + str(tu) return string_out
def fasta_name_seq(s): """ Interprets a string as a FASTA record. Does not make any assumptions about wrapping of the sequence string. """ DELIMITER = ">" try: lines = s.splitlines() assert len(lines) > 1 assert lines[0][0] == DELIMITER name = lines[0][1:] sequence = "".join(lines[1:]) return (name, sequence) except AssertionError: raise ValueError("String not recognized as a valid FASTA record")
def _empty_or_whitespaces_only(a_string: str) -> bool: """ Utility function: evaluates whether a_string is None or contains only whitespaces. :param a_string: string to be evaluated :type string: str :return: True if a_string is None or contains only whitespaces :rtype: Boolean """ if a_string is None or len(a_string.strip()) == 0: return True return False
def clean_data(data) -> list: """ Clean the data up by removing "->" and returning a list that contains lists that contain the starting coordinates, and the ending coordinates :param data: a list that represents the data for this problem :return: -> [[(x1, y1), (x2, y2)], ..., [(x1, y1), (x2, y2)]] """ cleaned_data = list() for datum in data: cleaned_data.append([ tuple(map(int, datum[0].split(","))), tuple(map(int, datum[1].split(","))) ]) return cleaned_data
def writeHeader(filename, meta_dict): """Write raw header mhd file Arguments: filename (str): file name of header meta_dict (dict): dictionary of meta data Returns: str: header file name """ header = '' # do not use tags = meta_dict.keys() because the order of tags matters tags = ['ObjectType','NDims','BinaryData', 'BinaryDataByteOrderMSB','CompressedData','CompressedDataSize', 'TransformMatrix','Offset','CenterOfRotation', 'AnatomicalOrientation', 'ElementSpacing', 'DimSize', 'ElementType', 'ElementDataFile', 'Comment','SeriesDescription','AcquisitionDate','AcquisitionTime','StudyDate','StudyTime'] for tag in tags: if tag in meta_dict.keys(): header += '%s = %s\n'%(tag,meta_dict[tag]) f = open(filename,'w') f.write(header) f.close() return filename
def _remove_comments_and_spaces_from_src_line(line: str) -> str: """ >>> _remove_comments_and_spaces_from_src_line('a = 42 # this is a comment') 'a=42' >>> _remove_comments_and_spaces_from_src_line('m = MyClass[Parent](a=Child1())') 'm=MyClass[Parent](a=Child1())' """ return line.split('#')[0].replace(' ', '')
def filter_blacklist(requests): """ If the session contains an article in the blacklist, drop the session. Currently, only the Main Page is in the black list """ black_list = set(['Q5296',]) for r in requests: if r['id'] in black_list: return False return True
def render_content(tab, search_from, **kwargs): """ Tab display callback. If the user clicked this tab, show it, otherwise hide """ outputs = [] for i in ["dataset", "frequencies", "chart", "concordance"]: if tab == i: outputs.append({"display": "block"}) else: outputs.append({"display": "none"}) return outputs
def snakify(from_camel): """ Examples -------- >>> snakify("heyThere") -> "hey_there" """ import re return re.sub('([A-Z]{1})', r'_\1', from_camel).lower()
def update_occurrence_array(occurrence_array: list, floor_number: int) -> list: """ Updates a given floor in the occurrence array. :param list occurrence_array: Array of dictionaries mapping floor number and people on floor. :param int floor_number: The floor to be updated. :return: The updated occurrence array. :rtype: list """ for floor in occurrence_array: if floor["floor_number"] == floor_number: floor["occurrences"] = floor["occurrences"] - 1 if floor["occurrences"] == 0: occurrence_array.remove(floor) return occurrence_array
def calc_increase(totals): """ Return a list of values representing the change in value from i-1 and i. """ changes = [] for i, s in enumerate(totals): if i == 0: changes.append(totals[i]) else: changes.append(s - totals[i-1]) return changes
def assoc(keyvals, key, val) : """Searches the list of keyval pairs for a matching key. If found, associates the value with the key. Otherwise, appends the key/val pair to the list. Returns the updated keyval list.""" ret = [ (k, val) if k == key else (k,v) for k,v in keyvals] if not any([k == key for k,v in keyvals]) : ret.append((key,val)) return ret
def wrap_python_args_with_string(args): """Wrap argument values with string Args: args: list like ["--foo", "3", "--bar", False] Returns: list of string: like ["--foo", "'3'", "--bar", "'False'"] """ result = [] for value in args: if not value.startswith("--"): result.append("'{}'".format(value)) else: result.append(value) return result
def sort_array_012(array): """Sort an array of 0s, 1s and 2s.""" # Dictionary of numbers encountered data = {0: 0, 1: 0, 2: 0} output = '' for x in array: data[x] = data[x] + 1 for key, value in data.items(): output += f'{key},' * value return output.split(',')[:-1]
def prod(iter, *, start=1, cast=int): """This version of product made to cast numpy types to python types so we don't have to worry about overflows. """ m = start for i in iter: m *= cast(i) return m
def schwartzian(rec): """Provides a schwartzian transform for the given record, used for sorting """ flds = rec.split() return (flds[1], float(flds[2]), rec)
def calc_impedance(density_soil, vs_soil, density_rock, vs_rock): """ Calculates the impedance contrast between the soil and rock Ref: Eq 7.23 from Kramer (1996) :param density_soil: Soil mass density :param g_soil: Soil shear modulus :param density_rock: Rock mass density :param g_rock: Rock shear modulus :return: """ impedance = density_soil * vs_soil / (density_rock * vs_rock) return impedance
def add_suffix_to_file_name(file_name, suffix=None): """Adds the specified suffix, if any, either to the end of the specified file_name; or, if the file_name has an "extension" starting with a dot ('.'), then just in front of the dot. """ result = file_name if suffix: ext_index = str(file_name).rfind('.') if ext_index > -1: file_name = file_name[:ext_index] + suffix + file_name[ext_index:] else: file_name += suffix return file_name
def unwrap_lines(lines, index): """Combine the two lines at lines[index] and lines[index + 1]. The actual lines extracted from the PDF sometimes contain long center and subcon names that have wrapped onto the following line. In most cases (generally on cover pages), that's not an error. However, my test code that builds the list of expected lines can't predict how and where the PDF layout algorithm will wrap a long name, so it always comes as somewhat of a surprise. It's easier to unwrap the actual lines than it is to figure out where to wrap the expected lines, and that's what this code does. """ return lines[:index] + [lines[index + 1] + ' ' + lines[index]] + lines[index + 2:]
def format_coord(axes, xdata, ydata): """ A C{None}-safe version of {Axes.format_coord()}. """ if xdata is None or ydata is None: return '' return axes.format_coord(xdata, ydata)
def capture(pattern): """ generate a capturing pattern :param pattern: an `re` pattern :type pattern: str :rtype: str """ return r'({:s})'.format(pattern)
def create_provenance_record(ancestor_files): """Create a provenance record.""" record = { 'caption': "Match temperature anomaly in target model to CMIP ensemble", 'domains': ['global'], 'authors': [ 'kalverla_peter', 'alidoost_sarah', 'rol_evert', ], 'ancestors': ancestor_files, } return record
def sqrt(n): """ Calculate the floored square root of a number Args: number(int): Number to find the floored squared root Returns: int: Floored Square Root """ # square root of 0 is 0 and 1 is 1 so return the same if n == 0 or n == 1: return n # square root of a number is: a value that can be multiplied by itself to give the given number # As sqrt(n) will be between [2, n/2] so do a simple binary search to find the solution start = 1 end = n/2 ans = 2 while start <= end: m = (start + end) // 2 if m * m == n: return m elif m * m < n: # save last m for which (m*m) < n because in cases like 27 which are not perfect squares we need # the lower bound which for 27 will be 5 ans = m # sqrt(n) is probably greater than m so move to the right side start = m + 1 else: # m * m > n # sqrt(n) is probably is smaller so move to the left side end = m - 1 return ans
def reorder_id(x, y, ids_original, ids_new): """Reorder id after shuffle""" x_ok = []; y_ok = [] for id_ok in ids_original: position_new=0 for new_id in ids_new: if id_ok == new_id: x_ok.append(x[position_new]) y_ok.append(y[position_new]) break position_new+=1 return x_ok, y_ok
def new_line_handler(tag, post_html): """ Replacing a tag with a tag + closing tag Example: <br> => <br></br> """ start_tag = "<{0}>".format(tag) end_tag = "</{0}>".format(tag) return post_html.replace(start_tag, start_tag + end_tag)
def rev_comp(seq): """reverse complement a string""" relation = {'A':'T', 'T':'A', 'C':'G', 'G':'C', 'N':'N'} return ''.join(relation[s] for s in seq[::-1])
def norm(list_of_nums): """ Normalizes input `list_of_nums` (`list` of `float`s or `int`s) """ try: norm_list_of_nums = list_of_nums / sum(list_of_nums) except: # occurs if divide by zero norm_list_of_nums = list_of_nums return norm_list_of_nums
def get_seed(seed_id): """ This function provides the random seed. :param seed_id: int the seed_id is the 'seeds' vector index :return: """ seeds = [1859168769, 1598189534, 1822174485, 1871883252, 694388766, 188312339, 773370613, 2125204119, #0,1,2,3,4,5 2041095833, 1384311643, 1000004583, 358485174, 1695858027, 762772169, 437720306, 939612284, 1998078925, 981631283, 1024155645, 1147024708, #19 558746720, 1349341884, 678622600, 1319566104, 538474442, 722594620, 1700738670, 1995749838, 1936856304, 346983590, 565528207, 513791680, 1996632795, 2081634991, 1769370802, 349544396, 1996610406, 1973272912, 1972392646, 605846893, 934100682, 222735214, 2101442385, 2009044369, 1895218768, 701857417, 89865291, 144443207, 720236707, 822780843, 898723423, 1644999263, 985046914, 1859531344, 1024155645, 764283187, 778794064, 683102175, 1334983095, 1072664641, 999157082, 1277478588, 960703545, 186872697, 425414105] return seeds[seed_id]
def get_liq_color(liq_dist): """ Get some colors for out Liquidation distance :param liq_dist: :return: """ if liq_dist > 0.5: return " text-success" elif 0.25 <= liq_dist <= 0.50: return " text-warning" elif 0 < liq_dist < 0.25: return " text-danger" else: return " text-body"
def checkImport(name): """ A function to check if the given module exists by importing it. """ try: import imp imp.find_module(name) return True except ImportError as error: return False
def make_list(n): """ Returns a list of n zeros, for the given argument n. """ zeros = [] for _ in range(n): zeros.append(0) # FWIW, the append method uses mutation return zeros
def gen_rg_pu_id(unit): """https://www.biostars.org/p/50349/""" if unit['run_id'] and unit['flowcell_id'] and unit['lane_id']: return "{}_{}.{}".format(unit['run_id'], unit['flowcell_id'], unit['lane_id']) else: return "PU-" + unit['rg_id']
def lazy_begin(*bodys): """Racket-like begin: run bodys in sequence, return the last return value. Lazy; each body must be a thunk (0-argument function), to delay its evaluation until begin() runs. f = lambda x: lazy_begin(lambda: print("hi"), lambda: 42*x) print(f(1)) # 42 """ l = len(bodys) if not l: return None if l == 1: b = bodys[0] return b() *rest, last = bodys for body in rest: body() return last()
def get_list_of_subsets(subset_task): """ Get the subsets to process for this analysis Parameters: ----------- subset_task: string string which specifies which subsets to use Results: -------- list of subset tasks """ # prefix for data and images if subset_task == 'all': subset_list = ['train', 'valid', 'test'] elif subset_task == 'train': subset_list = ['train'] elif subset_task == 'valid': subset_list = ['valid'] elif subset_task == 'test': subset_list = ['test'] else: raise ValueError('task value does not match to the expected value', subset_task) return subset_list
def float_converter(value): """To deal with Courtney CTD codes""" return float(value.split(":")[-1])
def reply_quote(s: str, prefix: str = "> ") -> str: """ .. versionadded:: 0.2.0 Quote__ a text following the *de facto* standard for replying to an e-mail; that is, prefix each line of the text with ``"> "`` (or a custom prefix), and if a line already starts with the prefix, omit any trailing whitespace from the newly-added prefix (so ``"> already quoted"`` becomes ``">> already quoted"``). If the resulting string does not end with a newline, one is added. The empty string is treated as a single line. __ https://en.wikipedia.org/wiki/Usenet_quoting """ s2 = "" for ln in (s or "\n").splitlines(True): if ln.startswith(prefix): s2 += prefix.rstrip() + ln else: s2 += prefix + ln if not s2.endswith(("\n", "\r")): s2 += "\n" return s2
def flatten(x): """General-purpose list-of-lists flattening. :type x: list of lists of something :param x: list of lists to flatten :rtype: list of that something :return: flattened list """ return [item for sublist in x for item in sublist]
def fact(n : int) -> int: """Retourne la factorielle de n. """ acc : int # accumulateur acc = 1 i : int # compteur i = 2 while i <= True: acc = acc * i i = i + 1 return acc
def flatten(value, prefix=""): """ >>> flatten({'a': {'b': 1, 'c': [2, 3]}}) {'.a.b': 1, '.a.c.0': 2, '.a.c.1': 3} We want to do something like that to ensure that we handled all props that occurred in the given spec. """ def merge_via(xs, prefix): d = {} for k, v in xs: d.update(flatten(v, f"{prefix}.{k}")) return d if isinstance(value, dict): return merge_via(value.items(), prefix) if isinstance(value, list): return merge_via(enumerate(value), prefix) return {prefix: value}
def round_dict_values(input_dict, digits=4): """ Helper function for printing dicts with float values """ return {key: round(val, digits) for key, val in input_dict.items()}
def equals(obj1, obj2, *, deep=False) -> bool: """ Checks whether two input objects are the same and returns the result in Boolean. Parameters: obj1(object): Objects to compare for equality. obj2(object): Objects to compare for equality. deep(bool): Specifies the scope of the comparison. The default value is false, and if true, compares two objects for equality, and if false, compares the values of two objects for equality. Returns: bool: The comparison value of two objects. """ if not deep: return True if obj1 == obj2 else False else: return True if obj1 is obj2 else False
def _splitRecordAndRemoveComments(line, delimiter=None): """ Method to split a record (relap5 input line) removing the comments if present @ In, line, str, the line to be splitted @ In, delimiter, str, optional, the delimiter to split by (default None -> white spaces) @ Out, splitted, list, the list containing the splitted line (without comments) """ splitted = [] for component in line.split(delimiter): stripped = component.strip() if stripped.startswith("*"): break splitted.append(stripped) return splitted
def get_maxrate(ratelimits, size): """ Returns number of requests allowed per second for given size. """ last_func = None if size: size = int(size) for ratesize, rate, func in ratelimits: if size < ratesize: break last_func = func if last_func: return last_func(size) return None
def wordp(thing): """ WORDP thing WORD? thing outputs TRUE if the input is a word, FALSE otherwise. """ return type(thing) is str
def _lane_detail_to_ss(fcid, ldetail): """Convert information about a lane into Illumina samplesheet output. """ return [fcid, ldetail["lane"], ldetail["name"], ldetail["genome_build"], ldetail["bc_index"], ldetail["description"], "N", "", "", ldetail["project_name"]]
def safe_index(lst, e): """Gets the index of e in l, providing an index of len(l) if not found""" try: return lst.index(e) except: return len(lst)
def hamilton(graph, start_at, verbose=False): """ Find and return a Hamiltonian path through a graph Thanks to Dmitry Sergeev via https://stackoverflow.com/questions/47982604/hamiltonian-path-using-python for this function, as I was too lazy to write it myself. """ size = len(graph) # if None we are -unvisiting- comming back and pop v to_visit = [None, start_at] path = [] while(to_visit): v = to_visit.pop() if v : if verbose: print("Visiting {0}".format(v)) print(" Path so far: {0}".format(path)) path.append(v) if len(path) == size: break for x in set(graph[v])-set(path): to_visit.append(None) # out to_visit.append(x) # in else: # if None we are comming back and pop v path.pop() return path
def _get_highest(board): """Return highest tile on the board, the board is a list of list Since the board unordered, you have to go through every element. """ return max(val for row in board for val in row)
def _htmlescape(string): """ Convert problematic characters in string to use HTML entities. Handles angle brackets, double quotes and ampersand. """ for char, rep in [('&', 'amp'), ('<', 'lt'), ('>', 'gt'), ('"', 'quot')]: string = string.replace(char, '&%s;' % rep) return string
def parsing(data): """Parses recieved data to readable form. Null('\0') is delimiter Returns list of data.""" data = data.replace(b'\377',b'') data = data.decode('UTF-8') li = data.split('\0') return li
def solution(A): """ """ # initialise array to record the sums of the elements in the array sum = [0] * len(A) sum[0] = A[0] # populate sums for i in range(1, len(A)): sum[i] = A[i] + sum[i - 1] # get a list of solutions for valid values of N solutions = [abs(sum[-1] - 2 * sum[i]) for i in range(0, len(A) - 1)] # return smallest value found return min(solutions)
def check_org_relevancy(cert, ssl_orgs): """ Check to see if the certificate is relevant to our organization. """ if "subject_organization_name" in cert: for org in cert["subject_organization_name"]: if org in ssl_orgs: return True
def get_input_streams(stream: dict) -> list: """ Generate input stream list :param stream: :return: """ input_stream_ids = stream.get("stream_ids", []) stream_name = stream.get("stream_name", "") input_streams = [] for id in input_stream_ids: input_streams.append({"name": stream_name, "identifier": id["identifier"]}) return input_streams
def intersect(nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: List[int] """ result = [] for i in range(len(nums1)): if nums1[i] in nums2: result.append(nums1[i]) return result
def _compare_term(minterm, term): """ Return True if a binary term is satisfied by the given term. Used for recognizing prime implicants. """ for i, x in enumerate(term): if x not in (3, minterm[i]): return False return True
def juncture_isom(juncture1, juncture2): """Takes a juncture and checks if the cell values are all equal""" B1, P1, N1, F1 = juncture1 B2, P2, N2, F2 = juncture2 return ((B1[1] == B2[1]) and (P1[1] == P2[1]) and (N1[1] == N2[1]) and (F1[1] == F2[1]))
def sort_dict_by_value(m_dict): """Sort the dict by value""" list_tuple = [(x, m_dict[x]) for x in m_dict] list_tuple.sort(key = lambda x : -x[1]) return list_tuple
def hello(name='person', lastname='exposito'): """ Function that return 'Hello World'. name: string, lastname: string, return: string, """ return f'Hello, {name} {lastname}!'
def edge_to_mesh(edge): """ This will find the mesh that corresponds to the edge """ mesh = None if edge.find('.e[') > -1: split_selected = edge.split('.e[') if len(split_selected) > 1: mesh = split_selected[0] return mesh
def _log1_p(log_p: float): """ Computes log(1 - p) given log(p). """ from math import exp, log1p return log1p(-exp(log_p))
def area2(a,b,c): """ return 2 * area of triangle abc """ return (a[0]-c[0])*(b[1]-c[1]) - (a[1]-c[1])*(b[0]-c[0])
def linspace(start, end, number_of_points): """ Generate a list of floats from start to end containing number_of_points elements. clone of NumPy function with same name. :param start: starting point of list. :param end: ending point of list. :param number_of_points: number of points in returned list. """ if start >= end: raise ValueError( 'The starting value must be less than the ending value.') if number_of_points < 2: raise ValueError('The space must contain at least two points.') interval = (end - start) / (number_of_points - 1) return [start + interval * i for i in range(number_of_points)]
def plural(num): """Determine plurality given an integer""" if num != 1: return 's' else: return ''
def sanitize(vec3): """ Swaps axes so that the Mocap coordinates fit Mujoco's coordinate system. """ if len(vec3) != 3: return vec3 return [round(vec3[2], 3), round(vec3[0], 3), round(vec3[1], 3)]
def is_function_symbol(objdump_line): """Returns true if it's a function, returns false otherwise""" if not ".text" in objdump_line: return False return True
def slice_list(l, n): """Yield successive n-sized chunks from l.""" # for i in xrange(0, len(l), n): # yield l[i:i + n] return [l[i:i + n] for i in range(0, len(l), n)]
def _remove_repeated(inds): """Removes repeated objects from sequences Returns a set of the unique objects and a tuple of all that have been removed. >>> from sympy.tensor.index_methods import _remove_repeated >>> l1 = [1, 2, 3, 2] >>> _remove_repeated(l1) (set([1, 3]), (2,)) """ sum_index = {} for i in inds: if i in sum_index: sum_index[i] += 1 else: sum_index[i] = 0 inds = [x for x in inds if not sum_index[x]] return set(inds), tuple([ i for i in sum_index if sum_index[i] ])
def detectFallingSeq(points_list): """Find falling temperatures sequences in given list and stores beginnings and ends of them in list. Always with format [seq1 start index, seq1 end index, seq2 start index, seq2 end index, ...] :param points_list: list of pipe temperatures :return: list of indexes """ falling = False index_list = [] for i in range(2, (len(points_list) - 1)): actual = points_list[i]['value'] prev = points_list[i - 1]['value'] prev_prev = points_list[i - 2]['value'] if float(actual) < float(prev) and float(actual) < float(prev_prev) and (not falling): if (float(prev_prev) - float(actual)) >= 0.2: # Calibration to not detect falling air temperature index_list.append(i - 2) falling = True elif float(actual) > float(prev) and float(actual) > float(prev_prev) and falling: index_list.append(i) falling = False return index_list