content
stringlengths
42
6.51k
def detect_date(token: str): """ Attempts to convert string to date if found mask_test = r'(Jan(?:uary)?|Feb(?:ruary)?|Mar(?:ch)?|Apr(?:il)?|May|Jun(?:e)?|Jul(?:y)?|Aug(?:ust)?|Sep(?:tember)?|Oct(?:ober)?|Nov(?:ember)?|Dec(?:ember)?)\s+(\d{1,2})\s+(\d{4})' """ from re import search from dateutil.parser import parse from dateutil.parser._parser import ParserError token = token.lower() # Feb 2010 mask1 = r"((jan)|(feb)|(mar)|(apr)|(may)|(jun)|(jul)|(aug)|(sep)|(oct)|(nov)|(dec))\s([1-9]|([12][0-9])|(3[04]))" mask4 = r"((january)|(february)|(march)|(april)|(may)|(june)|(july)|(august)|(september)|(october)|(november)|(december))\s([1-9]|([12][0-9])|(3[04]))" date1 = search(mask1, token) # 12-09-1991 mask2 = r'(?:(?:31(\/|-|\.)(?:0?[13578]|1[02]|(?:january|march|may|july|august|october|december)))\1|(?:(?:29|30)(\/|-|\.)(?:0?[1,3-9]|1[0-2]|(?:january|march|april|may|january|july|august|september|october|november|december))\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})$|^(?:29(\/|-|\.)(?:0?2|(?:february))\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:0?[1-9]|1\d|2[0-8])(\/|-|\.)(?:(?:0?[1-9]|(?:january|february|march|april|may|june|july|august|september))|(?:1[0-2]|(?:october|november|december)))\4(?:(?:1[6-9]|[2-9]\d)?\d{2})$' date2 = search(mask2, token) # 09/2020, 09-2020, 09.2020 dates mask3 = r'[0-9]{2}(-|.|/)[0-9]{4}' date3 = search(mask3, token) date4 = search(mask4, token) if date1 or date2 or date3 or date4: try: # Case with 1999 2003 is faulty -> gives mask as 99 2003 if len(token.split(' ')[0]) == len(token.split(' ')[1]) == 4: token = token.split(' ')[0] date = parse(token).date() return date except Exception as e: print("Date Parse Error: {}".format(e)) return None
def compute_total_ue_for_bs(_cell_associate, _bs_count): """Computes the number of UEs associated with a BS object for UE. Args: _cell_associate: (list) that contains tuple (ue_object, bs_associated)! _bs_count: (list) that contains tuple of BS objects and the number of UEs they are associated to! Returns: (list of) ints that correspond to the count of total number of UEs associated with a BS. """ other_ue_count_bs = [] # List of the total number of UEs associated with a BS for each UE! for x in _cell_associate: for y in _bs_count: if x[1] == y[0]: other_ue_count_bs.append(y[1]) return other_ue_count_bs
def longest_common_prefix(str1, str2): """ Returns the length of the longest common prefix of two provided strings """ i = 0 while i < min(len(str1), len(str2)): if str1[i] != str2[i]: break i += 1 return i
def getFilename(f): """Get the filename from an open file handle or filename string.""" if isinstance(f, str): return f return f.name
def load_vocab(vocab): """ Transforms a vocabulary to the dictionary format required for the candidate generation. :param vocab: a list containing the vocabulary :return: vocab_dict """ # TRANSFORM VOCABULARY TO DICTIONARY # initialize vocab word length keys and character set length keys vocab_dict = {} min_len = len(min(vocab, key=len)) max_len = len(max(vocab, key=len)) item_lens = range(min_len, max_len+1) for item in item_lens: vocab_dict[item] = {} for i in range(1, max_len+1): vocab_dict[item][i] = set() # fill vocab according to word length and character set length for word in vocab: vocab_dict[len(word)][len(set(word))].add(word) return vocab_dict
def build(scoreGraph, orig_sentences): """ Builds the content summary based on the graph :param orig_sentences: (list) list of original sentences :param scoreGraph: (list) 2 dimensional list-graph of scores :returns: Aggregate score(dictionary) of each sentence in `sentences` """ aggregateScore = dict() sen = 0 for scores in scoreGraph: aggregate = 0 for i in scores: aggregate += i aggregateScore[orig_sentences[sen]] = aggregate sen += 1 return aggregateScore
def _format_media_type(endpoint, version, suffix): """ Formats a value for a cosmos Content-Type or Accept header key. :param endpoint: a cosmos endpoint, of the form 'x/y', for example 'package/repo/add', 'service/start', or 'package/error' :type endpoint: str :param version: The version of the request :type version: str :param suffix: The string that will be appended to endpoint type, most commonly 'request' or 'response' :type suffix: str :return: a formatted value for a Content-Type or Accept header key :rtype: str """ prefix = endpoint.replace('/', '.') separator = '-' if suffix else '' return ('application/vnd.dcos.{}{}{}' '+json;charset=utf-8;version={}').format(prefix, separator, suffix, version)
def sign2w(x): """ Decode signed 2-byte integer from unsigned int """ if x >= 32768: x ^= 65535 x += 1 x *=-1 return x
def get_best_model(errors_list, model_list): """ Based on list of errors and list of models, return the model with the minimum error Returns: model object """ # Find the index of the smallest ROEM import numpy as np idx = np.argmin(errors_list) print("Index of smallest error:", idx) # Find ith element of ROEMS print("Smallest error: ", errors_list[idx]) return model_list[idx]
def trimhttp(url): """ Strip 'http://' or 'https://' prefix to url """ if url[:7] == 'http://': return url[7:] elif url[:8] == 'https://': return url[8:] return url
def func_xy_ab_args_pq_kwargs(x, y, a=2, b=3, *args, p="p", q="q", **kwargs): """func. Parameters ---------- x, y: float a, b: int args: tuple p, q: str, optional kwargs: dict Returns ------- x, y: float a, b: int args: tuple p, q: str kwargs: dict """ return x, y, a, b, args, p, q, kwargs
def get_opcode(instruction_bytes): """ Returns the 6-bit MIPS opcode from a 4 byte instruction. """ op = (instruction_bytes & 0xFC000000) >> (3 * 8 + 2) return op
def summarize_consensus(consensus): """ Return 'high', 'medium' or 'low' as a rough indicator of consensus. """ cons = int(100 * consensus) if cons >= 70: return "high" elif cons >= 30: return "medium" else: return "low"
def check_guess(guess, answer): """ :param guess: an alphabet, the guess made by player :param answer: a word, the correct answer :return: bool, if the guess is in the answer or not """ for i in range(len(answer)): ch = answer[i] if ch == guess: return True
def parse_2hc(segment): """ Parser for 2hc periodic output""" second_hit = {} data = segment.split() second_hit["fill_perc"] = float(data[1]) return second_hit
def get_reduction_level(indsize, optlevel, slicesize, chunksize): """Compute the reduction level based on indsize and optlevel.""" rlevels = [ [8, 8, 8, 8, 4, 4, 4, 2, 2, 1], # 8-bit indices (ultralight) [4, 4, 4, 4, 2, 2, 2, 1, 1, 1], # 16-bit indices (light) [2, 2, 2, 2, 1, 1, 1, 1, 1, 1], # 32-bit indices (medium) [1, 1, 1, 1, 1, 1, 1, 1, 1, 1], # 64-bit indices (full) ] isizes = {1: 0, 2: 1, 4: 2, 8: 3} rlevel = rlevels[isizes[indsize]][optlevel] # The next cases should only happen in tests if rlevel >= slicesize: rlevel = 1 if slicesize <= chunksize * rlevel: rlevel = 1 if indsize == 8: # Ensure that, for full indexes we will never perform a reduction. # This is required because of implementation assumptions. assert rlevel == 1 return rlevel
def check_auth(username, password): """This function is called to check if a username / password combination is valid. """ return username == 'xlr_test' and password == 'admin'
def merge_as_sets(*args): """Create an order set (represented as a list) of the objects in the sequences passed as arguments.""" s = {} for x in args: for y in x: s[y] = True return sorted(s)
def whitespace_tokenize(text): """Runs basic whitespace cleaning and splitting on a piece of text.""" text = text.strip() if not text: return [] tokens = text.split() return tokens
def get_average(data): """Returns the average value from given data points.""" return sum(data) / len(data)
def no_response_error(api, response): """format error message for empty response""" return "calling: %s: no response %s" % (api, repr(response))
def is_valid_boolstr(val): """Check if the provided string is a valid bool string or not.""" val = str(val).lower() return val in ('true', 'false', 'yes', 'no', 'y', 'n', '1', '0')
def himmelblau(individual): """The Himmelblau's function is multimodal with 4 defined minimums in :math:`[-6, 6]^2`. .. list-table:: :widths: 10 50 :stub-columns: 1 * - Type - minimization * - Range - :math:`x_i \in [-6, 6]` * - Global optima - :math:`\mathbf{x}_1 = (3.0, 2.0)`, :math:`f(\mathbf{x}_1) = 0`\n :math:`\mathbf{x}_2 = (-2.805118, 3.131312)`, :math:`f(\mathbf{x}_2) = 0`\n :math:`\mathbf{x}_3 = (-3.779310, -3.283186)`, :math:`f(\mathbf{x}_3) = 0`\n :math:`\mathbf{x}_4 = (3.584428, -1.848126)`, :math:`f(\mathbf{x}_4) = 0`\n * - Function - :math:`f(x_1, x_2) = (x_1^2 + x_2 - 11)^2 + (x_1 + x_2^2 -7)^2` .. plot:: code/benchmarks/himmelblau.py :width: 67 % """ return (individual[0] * individual[0] + individual[1] - 11)**2 + \ (individual[0] + individual[1] * individual[1] - 7)**2,
def _extend_pads(pads, rank): """Extends a padding list to match the necessary rank. Args: pads ([int] or None): The explicitly-provided padding list. rank (int): The rank of the operation. Returns: None: If pads is None [int]: The extended padding list. """ if pads is None: return pads pads = list(pads) if len(pads) < rank: pads.extend([0] * (rank - len(pads))) if len(pads) < (2 * rank): pads.extend(pads[len(pads) - rank:rank]) return pads
def calc(region, metric, ms): """ """ if metric in region: value = region[metric] return round((value / ms) * 100) else: return 0
def _list_f2s(float_list): """Converts a list of floats to strings.""" return ["{:0.2f}".format(x) for x in float_list]
def title(text): """Turns text into a title""" return str(text).replace("_", " ").title()
def recursive_longest_palindromic_subsequence(input_string): """ Parameters ---------- input_string : str String with palindromic subsequence Returns ------- int length of the longest palindromic subsequence >>> recursive_longest_palindromic_subsequence("abdbca") 5 >>> recursive_longest_palindromic_subsequence("cddpd") 3 >>> recursive_longest_palindromic_subsequence("pqr") 1 """ def helper(start, end): # if start == end: return 1 if start > end: return 0 if input_string[start] == input_string[end]: return 2 + helper(start + 1, end - 1) return max(helper(start + 1, end), helper(start, end - 1)) return helper(0, len(input_string) - 1)
def lossless_compression(text: str, token_separator=" ") -> str: """Here we count how many times the same token was repeated and write it and it's count e.g text ABC ABC ABC EE A S X X SD will be compressed to: ABC 3 EE 1 A 1 S 1 XX 2 SD 1. For small resolutions this compression doesn't give us much. But as we increase resolution it works better and better, and we still have very detailed description Args: text (str): text to be compressed token_separator (str, optional): _description_. Defaults to " ". Returns: str: compressed text """ compressed = [] tokenized = text.split(token_separator) previous = tokenized[0] counter = 1 for token in tokenized[1:]: if token != previous and counter > 0: compressed.append(previous) compressed.append(str(counter)) previous = token counter = 1 else: counter += 1 # Last token won't be added in the loop compressed.append(previous) compressed.append(str(counter)) return " ".join(compressed)
def _appendListElement(list_data, data) -> list: """ Function Description : _appendListElement : append new squence element and return into sequence accept list_data as list that would be append with new data. And the data is arg to hold the new data EXAMPLE ARGS : (list_data = [], data = 2) EXAMPLE PROSSIBLE RESULT : [2] """ list_data.append(data) return list_data
def unsigned_int(value): """Convert from signed to unsigned int (Channel Access does not support unsigend int)""" if type(value) == int and value < 0: value = value+0x100000000 return value
def dec2hex(x): """ Convert decimal number to hexadecimal string. For instance: 26 -> '1a' """ return hex(x)[2:]
def differentiate(coefficients): """ Calculates the derivative of a polynomial and returns the corresponding coefficients. """ new_cos = [] for deg, prev_co in enumerate(coefficients[1:]): new_cos.append((deg+1) * prev_co) return new_cos
def to_multipart_form(data, boundary): """Create a multipart form like produced by HTML forms from a dict.""" form_lines = [] for k, v in data.items(): form_lines.append('--' + boundary) # Handle special case for imageFile. if k == 'imageFile': form_lines.append('Content-Disposition: form-data; ' + 'name="%s"; filename="cover.jpg"' % k) form_lines.append('Content-Type: image/jpeg') form_lines.append('') form_lines.append('') else: form_lines.append('Content-Disposition: form-data; name="%s"' % k) form_lines.append('') # Lowercase bool values to follow JSON standards. form_lines.append(str(v) if not isinstance(v, bool) else str(v).lower()) form_lines.append('--' + boundary + '--') joined_form = '\n'.join(form_lines) return joined_form
def get_output_detections_json_file_path(input_file_path, suffix="--detections"): """Get the appropriate detections JSON output path for a given image input. Effectively appends "--detections" to the original image file and places it within the same directory. Parameters ----------- input_file_path: str Path to input image. suffix: str Suffix appended to the file. Default: "--detections" Returns ------- str Full path for detections JSON output. """ input_file_path = input_file_path.replace('--original.', '.') input_file_paths = input_file_path.split('.') input_file_paths[-2] = input_file_paths[-2]+suffix input_file_paths[-1] = 'json' return '.'.join(input_file_paths)
def _stripItalic(s): """Returns the string s, with italics removed.""" return s.replace('\x1d', '')
def stringify_time(time) -> str: """ returns time in appropriate way for agenda """ hours = str(int(time)) if len(hours) == 1: hours = '0' + hours minutes = '30' if time % 1 != 0 else '00' return hours + minutes + '00'
def voltage_to_direction(voltage: float) -> str: """ Converts an anolog voltage to a direction Arguments: - voltage: Voltage float value form the MCP3008. values are between 0 and 3.3V Returns: - Direction coresponding to an input voltage """ if voltage < 0.20625 or voltage > 3.09375: return "N" elif 0.20625 <= voltage < 0.61875: return "NE" elif 0.61875 <= voltage < 1.03125: return "E" elif 1.03125 <= voltage < 1.44375: return "SE" elif 1.44375 <= voltage < 1.85625: return "S" elif 1.85625 <= voltage < 2.26875: return "SW" elif 2.26875 <= voltage < 2.68125: return "W" else: return "NW"
def oxe_set_headers(token, method=None): """Builder for requests headers depending on request method Args: token (STR): Authentication token method (None, optional): GET (not mandatory), PUT, POST, DELETE Returns: JSON: headers """ # basic method GET headers = { 'Authorization': 'Bearer ' + token, 'accept': 'application/json' } # addition for POST & PUT if method in ('POST', 'PUT'): headers.update({'Content-Type': 'application/json'}) # addition for DELETE elif method == 'DELETE': headers.update({'Content-Type': 'text/plain'}) return headers
def _common_dir(dirs): """ dirs: List[String] """ if not dirs: return "" if len(dirs) == 1: return dirs[0] split_dirs = [dir.split("/") for dir in dirs] shortest = min(split_dirs) longest = max(split_dirs) for i, piece in enumerate(shortest): # if the next dir does not match, we've found our common parent if piece != longest[i]: return "/".join(shortest[:i]) return "/".join(shortest)
def build_txt_strand_from_chains(model): """ Concatenates chains in given model and builds a single strand from them :param model: Model aggregate of chains :return: RNA strand text string """ txt = '' for _, chain in model.items(): txt += ''.join(chain) return txt
def justify_right(css: str) -> str: """Justify to the Right all CSS properties on the argument css string.""" max_indent, right_justified_css = 1, "" for css_line in css.splitlines(): c_1 = len(css_line.split(":")) == 2 and css_line.strip().endswith(";") c_2 = "{" not in css_line and "}" not in css_line and len(css_line) c_4 = not css_line.lstrip().lower().startswith("@import ") if c_1 and c_2 and c_4: lenght = len(css_line.split(":")[0].rstrip()) + 1 max_indent = lenght if lenght > max_indent else max_indent for line_of_css in css.splitlines(): c_1 = "{" not in line_of_css and "}" not in line_of_css c_2 = max_indent > 1 and len(line_of_css.split(":")) == 2 c_3 = line_of_css.strip().endswith(";") and len(line_of_css) c_4 = "@import " not in line_of_css if c_1 and c_2 and c_3 and c_4: propert_len = len(line_of_css.split(":")[0].rstrip()) + 1 xtra_spaces = " " * (max_indent + 1 - propert_len) xtra_spaces = ":" + xtra_spaces justified_line_of_css = "" justified_line_of_css = line_of_css.split(":")[0].rstrip() justified_line_of_css += xtra_spaces justified_line_of_css += line_of_css.split(":")[1].lstrip() right_justified_css += justified_line_of_css + "\n" else: right_justified_css += line_of_css + "\n" return right_justified_css if max_indent > 1 else css
def search(state, path): """Get value in `state` at the specified path, returning {} if the key is absent""" if path.strip("/") == '': return state for p in path.strip("/").split("/"): if p not in state: return {} state = state[p] return state
def _plugin_replace_role(name, contents, plugins): """ The first plugin that handles this role is used. """ for p in plugins: role_hook = p.get_role_hook(name) if role_hook: return role_hook(contents) # If no plugin handling this role is found, return its original form return ':{0}:`{1}`'.format(name, contents)
def __is_variable(data: str) -> bool: """ Returns true if predicate is a variable. Note: requires to start all variables with a capital letter. """ return data[0].isupper()
def isiterable(obj): """ Returns True if obj is Iterable (list, str, tuple, set, dict, etc'), and False otherwise. \ This function does not consume iterators/generators. :param obj: the object to be tested for iterability :type obj: Any :return: True if obj is Iterable, False otherwise. :rtype: bool """ try: _ = iter(obj) except TypeError: return False else: return True
def morris_traversal(root): """ Morris(InOrder) travaersal is a tree traversal algorithm that does not employ the use of recursion or a stack. In this traversal, links are created as successors and nodes are printed using these links. Finally, the changes are reverted back to restore the original tree. root = Node(4) temp = root temp.left = Node(2) temp.right = Node(8) temp = temp.left temp.left = Node(1) temp.right = Node(5) """ inorder_traversal = [] # set current to root of binary tree current = root while current is not None: if current.left is None: inorder_traversal.append(current.data) current = current.right else: # find the previous (prev) of curr previous = current.left while previous.right is not None and previous.right != current: previous = previous.right # make curr as right child of its prev if previous.right is None: previous.right = current current = current.left # firx the right child of prev else: previous.right = None inorder_traversal.append(current.data) current = current.right return inorder_traversal
def settings_index(val: float, settings: list) -> int: """Return index into settings that has nearest value to val. Args: val: settings: Returns: """ idx = 0 for idx, setting in enumerate(settings): if val <= setting: if idx > 0: # Not first entry. delta_prev = abs(val - settings[idx - 1]) delta_cur = abs(val - setting) if delta_prev < delta_cur: # Value closer to previous entry. idx -= 1 # Setting found. break return idx
def folders_to_path(folders): """ Convert list of folders to a path. :param folders: List of folders, None denotes a root folder e.g. [None, 'NAS', 'Music', 'By Folder', 'folder1'] :returns: path string e.g. /NAS/Music/By Folder/folder1 """ if not folders: return '/' if folders[0] is None: folders[0] = '' return '/'.join(folders) or '/'
def vol_format(x): """ Formats stock volume number to millions of shares. Params: x (numeric, like int or float)): the number to be formatted Example: vol_format(10000000) vol_format(3390000) """ return "{:.1f}M".format(x/1000000)
def convert_variable_name(oldname: str) -> str: """Convert Variable Name. Converts a variable name to be a valid C macro name. """ return oldname.strip().upper().replace(" ", "_")
def readFileLines(fname): """Read the lines of 'fname', returning them as a list.""" with open(fname, "r") as fp: return fp.readlines()
def task_wrapper(task): """Task wrapper for multithread_func Args: task[0]: function to be wrapped. task[1]: function args. Returns: Return value of wrapped function call. """ func = task[0] params = task[1] return func(*params)
def make_link(text: str, link: str) -> str: """ Creates a markdown link :param text: the text to display :param link: the link target :return: the formatted link """ return '[%s](%s)' % (text, link)
def make_extension_name(extension_basename: str, package_name: str) -> str: """Make a full Arrowbic extension name. Args: extension_basename: Extension basename. package_name: Package name. Returns: Extension fullname. """ extension_name = f"arrowbic.{package_name}.{extension_basename}" return extension_name
def version_int_to_string(version_integer: int) -> str: """Convert a version integer to a readable string. Args: version_integer (int): The version integer, as retrieved from the device. Returns: str: The version translated to a readable string. """ if not version_integer: return "" appendixes = ["N", "E", "A", "B", "R", "S"] version_bytes = version_integer.to_bytes(4, "big") version_appendix = ( appendixes[version_bytes[3]] if 0 <= version_bytes[3] < len(appendixes) else "" ) return f"{version_bytes[0]:x}.{version_bytes[1]:x}.{version_bytes[2]}.{version_appendix}"
def get_scientific_name_from_row(r): """ r: a dataframe that's really a row in one of our taxonomy tables """ if 'canonicalName' in r and len(r['canonicalName']) > 0: scientific_name = r['canonicalName'] else: scientific_name = r['scientificName'] return scientific_name
def parity(x,N,sign_ptr,args): """ works for all system sizes N. """ out = 0 sps = args[0] for i in range(N): j = (N-1) - i out += ( x%sps ) * (sps**j) x //= sps # return out
def cmp_dicts(d1, d2): """Recursively compares two dictionaries""" # First test the keys for k1 in d1.keys(): if k1 not in d2: return False for k2 in d2.keys(): if k2 not in d1: return False # Now we need to test the contents recursively. We store the results of # each recursive comparison in a list and assert that they all must be True # at the end comps = [] for k1, v1 in d1.items(): v2 = d2[k1] if isinstance(v1, dict) and isinstance(v2, dict): comps.append(cmp_dicts(v1, v2)) else: if v1 != v2: return False return all(comps)
def _interpolation_max_weighted_deg(n, tau, s): """Return the maximal weighted degree allowed for an interpolation polynomial over `n` points, correcting `tau` errors and with multiplicity `s` EXAMPLES:: sage: from sage.coding.guruswami_sudan.interpolation import _interpolation_max_weighted_deg sage: _interpolation_max_weighted_deg(10, 3, 5) 35 """ return (n-tau) * s
def n_eff(dlnsdlnm): """ Return the power spectral slope at the scale of the halo radius, Parameters ---------- dlnsdlnm : array The derivative of log sigma with log M Returns ------- n_eff : float Notes ----- Uses eq. 42 in Lukic et. al 2007. """ n_eff = -3.0 * (2.0 * dlnsdlnm + 1.0) return n_eff
def get_attributes(label_data): """Reads all attributes of label. Args: label_data (dict): List of label attributes Returns: list: List of all attributes """ attributes = [] if label_data['attributes'] is not None: for attribute_name in label_data['attributes']: if len(label_data['attributes'][attribute_name]) > 0: for attribute in label_data['attributes'][attribute_name]: attributes.append(attribute['name']) return attributes
def _import_object(source): """helper to import object from module; accept format `path.to.object`""" modname, modattr = source.rsplit(".",1) mod = __import__(modname, fromlist=[modattr], level=0) return getattr(mod, modattr)
def sum_pows(a: int, b: int, c: int, d: int) -> int: """ >>> sum_pows(9, 29, 7, 27) 4710194409608608369201743232 """ return a**b + c**d
def hist_dict(array): """ Return a histogram of any items as a dict. The keys of the returned dict are elements of 'array' and the values are the counts of each element in 'array'. """ hist = {} for i in array: if i in hist: hist[i] += 1 else: hist[i] = 1 return hist
def map_tcp_flags(bitmap): """ Maps text names of tcp flags to values in bitmap :param bitmap: array[8] :return: dictionary with keynames as names of the flags """ result = {} result["FIN"] = bitmap[7] result["SYN"] = bitmap[6] result["RST"] = bitmap[5] result["PSH"] = bitmap[4] result["ACK"] = bitmap[3] result["URG"] = bitmap[2] result["ECE"] = bitmap[1] result["CRW"] = bitmap[0] return result
def _is_substitution(content, start, end): """This is to support non-ARM-style direct parameter string substitution as a simplification of the concat function. We may wish to remove this if we want to adhere more strictly to ARM. :param str content: The contents of an expression from the template. :param int start: The start index of the expression. :param int end: The end index of the expression. """ return not (content[start - 1] == '"' and content[end + 1] == '"')
def createMyWords(language, validletters='abcdefghijklmnopqrstuvwxyz', additionals=''): """Return a list of guessable words. Ideally, these words originate from an included dictionary file called de-en.dict. """ mywords = set() # guessable words if language == 'en': languagepick = 2 else: languagepick = 0 try: myfile = open("de-en.dict") for line in myfile: # EN = 2, DE = 0 mywordsplit = line.partition(':: ')[languagepick] myword = mywordsplit.partition(' ')[0] if len(myword) < 5: # filter out certain words pass elif not (myword.lower()).isalpha(): pass else: for letter in myword.lower(): if (letter not in validletters) and ( letter not in additionals): break else: mywords.add(myword) myfile.close() except: # fallback list of words if dict file isn't found if language == 'en': # EN list mywords = {"cherry", "summer", "winter", "programming", "hydrogen", "Saturday", "unicorn", "magic", "artichoke", "juice", "hacker", "python", "Neverland", "baking", "sherlock", "troll", "batman", "japan", "pastries", "Cairo", "Vienna", "raindrop", "waves", "diving", "Malta", "cupcake", "ukulele"} else: # DE list mywords = {"Ferien", "Grashuepfer", "programmieren", "Polizei", "Zielgerade", "Kronkorken", "Kuchen", "rumlungern", "kichern", "Salzwasser", "Schwimmflossen", "Motorradhelm", "feiern", "Fehlbesetzung", "Regisseurin", "Zuckerwatte", "pieksen", "Nebelmaschine", "Lampenschirm", "Redewendung"} finally: return mywords
def get_delete_query(table_name: str) -> str: """Build a SQL query to delete a RDF triple from a PostgreSQL table. Argument: Name of the SQL table from which the triple will be deleted. Returns: A prepared SQL query that can be executed with a tuple (subject, predicate, object). """ return f"DELETE FROM {table_name} WHERE subject = %s AND predicate = %s AND object = %s"
def month_converter(month): """Convert month name string to number.""" months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] return str(months.index(month) + 1).rjust(2, '0')
def split_string(phrase: str, split_param: str): """ Split the 'phrase' string in different strings taking 'split_param' as split's parameter :param phrase: string to be splitted :param split_param: split's parameter :return: a list of strings """ return phrase.split(split_param)
def isinslice(index, Slice): """ Determine whether index is part of a slice. """ start, stop, stride = Slice.indices(index + 1) if (index - start) % stride != 0: return False if stride < 0: return (start >= index > stop) else: return (start <= index < stop)
def gamma_PML(x, gamma, PML_start, PML_thk): """ Polynomial stretching profile for a perfectly matched layer. Parameters: x : physical coordinate gamma : average value of the profile PML_start : where the PML starts PML_thk : thickness of the PML Returns: the value of the profile function at x """ return 1 + 3*(gamma - 1)*((abs(x - PML_start))/PML_thk)**2
def parseIntList(string): """Parses a comma-separated string of ints into a list""" splitarray = string.split(",") int_list = [] for elem in splitarray: int_list.append(int(elem)) return int_list
def get_target_metrics(dataset: str, tolerance: float = 0.0): """Get performance of pretrained model as gold standard.""" if dataset == 'eth': # target_ade, target_fde = 0.64, 1.11 # paper target_ade, target_fde = 0.732, 1.223 # pretrained target_col = 1.33 elif dataset == 'hotel': # target_ade, target_fde = 0.49, 0.85 # paper target_ade, target_fde = 0.410, 0.671 # pretrained target_col = 3.56 elif dataset == 'univ': # target_ade, target_fde = 0.44, 0.79 # paper target_ade, target_fde = 0.489, 0.911 # pretrained target_col = 9.22 elif dataset == 'zara1': target_ade, target_fde = 0.335, 0.524 # paper ~= pretrained target_col = 2.14 elif dataset == 'zara2': target_ade, target_fde = 0.304, 0.481 # paper ~= pretrained target_col = 6.87 else: raise NotImplementedError return target_ade+tolerance, target_fde+tolerance, target_col
def docker_compose_files(pytestconfig): """Get the docker-compose.yml absolute path. Override this fixture in your tests if you need a custom location. """ return ["docker-compose.yml"]
def cloudtrail_event_parser(event): """Extract list of new S3 bucket attributes. These attributes are extracted from the AWS CloudTrail resource creation event. Args: event: a CloudTrail event Returns: s3_bucket_name: name of the created S3 bucket resource_date: date+time the S3 bucket was created role_arn: IAM role ARN of entity creating the S3 bucket Raises: none """ s3_bucket_name = event.get("detail").get("requestParameters").get("bucketName", "") resource_date = event.get("detail").get("eventTime", "") # Verify assumed IAM role ARN assumed to create the new S3 bucket if event.get("detail").get("userIdentity").get("type") == "AssumedRole": role_arn = ( event.get("detail") .get("userIdentity") .get("sessionContext") .get("sessionIssuer") .get("arn", "") ) else: role_arn = "" return s3_bucket_name, resource_date, role_arn
def filter_out_agg_logs(logs): """Remove aggregate interactions from the list in computing data point metrics""" filtered = [] for log in logs: if "agg" not in log: filtered.append(log) return filtered
def filter_dict_by_key_set(dict_to_filter, key_set): """Takes a dictionary and returns a copy with only the keys that exist in the given set""" return {key: dict_to_filter[key] for key in dict_to_filter.keys() if key in key_set}
def flax_while_loop(cond_fun, body_fun, init_val): # pragma: no cover """ for debugging purposes, use this instead of jax.lax.while_loop """ val = init_val while cond_fun(val): val = body_fun(val) return val
def _dict_extends(d1, d2): """ Helper function to create a new dictionary with the contents of the two given dictionaries. Does not modify either dictionary, and the values are copied shallowly. If there are repeates, the second dictionary wins ties. The function is written to ensure Skulpt compatibility. Args: d1 (dict): The first dictionary d2 (dict): The second dictionary """ d3 = {} for key, value in d1.items(): d3[key] = value for key, value in d2.items(): d3[key] = value return d3
def file_name(path: str) -> str: """From path of a file, find the name of that file""" # Scroll back path string until he find / or \ for i in range(len(path)-1, 0, -1): if path[i] == "/" or path[i] == "\\": return path[i+1:] else: return path
def get_direction_time(direction, travelling_mode): """Get the duration of the journey Arguments: - direction : (list) information about the journey - travelling_mode: (str) conveyance Returns: - time : (str) duration of the journey """ time = None if travelling_mode == 'driving': time = \ direction[0]['legs'][0]['duration_in_traffic']['text'] else: time = \ direction[0]['legs'][0]['duration']['text'] return time
def count_total_parameters(variables): """ Args: variables (list): tf.trainable_variables() Returns: parameters_dict (dict): key => variable name value => the number of parameters total_parameters (float): total parameters of the model """ total_parameters = 0 parameters_dict = {} for variable in variables: shape = variable.get_shape() variable_parameters = 1 for dim in shape: variable_parameters *= dim.value total_parameters += variable_parameters parameters_dict[variable.name] = variable_parameters return parameters_dict, total_parameters
def utterance_from_line(line): """Converts a line of text, read from an input file, into a list of words. Start-of-sentence and end-of-sentece tokens (``<s>`` and ``</s>``) will be inserted at the beginning and the end of the list, if they're missing. If the line is empty, returns an empty list (instead of an empty sentence ``['<s>', '</s>']``). :type line: str or bytes :param line: a line of text (read from an input file) :rtype: list of strs :returns: list of words / tokens """ if isinstance(line, bytes): line = line.decode('utf-8') line = line.rstrip() if not line: # empty line return [] result = line.split() if result[0] != '<s>': result.insert(0, '<s>') if result[-1] != '</s>': result.append('</s>') return result
def _expand_xyfp(x, y): """ Undo _redux_xyfp() transform """ a = 420.0 return -x*a, y*a
def grab_file_extension(file_name): """ grabs the chunk of text after the final period. """ return file_name.rsplit('.', 1)[1]
def apply_set_and_clear(val: int, set_flag: int, clear_flag: int): """ :param val: an input value of the flag(s) :param set_flag: a mask of bits to set to 1 :param clear_flag: a mask of bits to set to 0 :note: set has higher priority :return: new value of the flag """ return (val & ~clear_flag) | set_flag
def _strip_comments(definition_lines): """Not as straightforward as usual, because comments can be escaped by backslash, and backslash can escape space.""" out_lines = [] for line in definition_lines: pos = 0 while True: x = line.find("#", pos) if x <= 0: if x == 0: line = "" break is_escaped = False if line[x - 1] == "\\": # see how many there are y = x - 2 while y >= pos and line[y] == "\\": y -= 1 is_escaped = (x - y) % 2 == 0 if is_escaped: pos = x + 1 else: line = line[:x] break out_lines.append(line) return out_lines
def f(x, a, r): """ The equation ax^(a-1) - (a-1)x^a - r = 0 To be used as argument in solver """ return a*x**(a-1) - (a-1)*x**a - r
def adjust_parameter_threshold(param, stab, targ_stab = 0.5, rate = 0.03): """ """ param_update = param + (stab - targ_stab)*rate param_diff= param - param_update return param_update, param_diff
def decode(parsed_string): """ INPUT: A List of List parsed from encoded string OUTPUT: A String of Decoded line """ decoded = "" for item in parsed_string: try: decoded += item[0] * item[1] except IndexError: pass return decoded
def prettyElapsed(seconds): """ Return a pretty string representing the elapsed time in hours, minutes, seconds """ def shiftTo(seconds, shiftToSeconds, shiftToLabel): """ Return a pretty string, shifting seconds to the specified unit of measure """ prettyStr = '%i%s' % ((seconds / shiftToSeconds), shiftToLabel) mod = seconds % shiftToSeconds if mod != 0: prettyStr += ' %s' % prettyElapsed(mod) return prettyStr seconds = int(seconds) if seconds < 60: return '%is' % seconds elif seconds < 60 * 60: return shiftTo(seconds, 60, 'm') else: return shiftTo(seconds, 60 * 60, 'h')
def file_type_matches(file_types): """wildcard file name matches for the file types to include""" return ["/*.%s" % file_type for file_type in file_types]
def checkExistence_file(database_filename): """Function that check if the db file can be opened""" try: with open(database_filename) as file: read_data = file.read() except Exception as e: raise Exception("Could not opened the file '" + database_filename + "'") return True
def top_accepted(answers, top=5): """Top accepted answers by score""" return list( filter( lambda x: x["is_accepted"], sorted(answers, key=lambda x: x["score"], reverse=True), ) )[:top]
def modelfor(model, table): """ Returns True if the given `model` object is for the expected `table`. >>> from pyfarm.master.config import config >>> from pyfarm.models.agent import Agent >>> modelfor(Agent("foo", "10.56.0.0", "255.0.0.0"), config.get("table_agent")) True """ try: return model.__tablename__ == table except AttributeError: return False
def build_bmv2_config(bmv2_json_path): """ Builds the device config for BMv2 """ with open(bmv2_json_path) as f: return f.read()
def normalize_newlines(text: str) -> str: """Normalize text to follow Unix newline pattern""" return text.replace("\r\n", "\n").replace("\r", "\n")
def get_midpoint(origin, destination): """ Return the midpoint between two points on cartesian plane. :param origin: (x, y) :param destination: (x, y) :return: (x, y) """ x_dist = destination[0] + origin[0] y_dist = destination[1] + origin[1] return x_dist / 2.0, y_dist / 2.0