content
stringlengths
42
6.51k
def _line_is_hyphens(line): """Returns whether the line is entirely hyphens (and not blank).""" return line and not line.strip('-')
def get_filename(abs_path): """Returns the basename of the given absolute path.""" return abs_path.rsplit("/", 1)[-1].rsplit("\\", 1)[-1]
def format_orbit_notes(text: str) -> str: """Given orbit notes returns them as HTML""" template = '<div class="orbit-notes"><p>{}</p></div>' html_text = text.replace("\n", "</p><p>") return template.format(html_text)
def strip_id_from_matrix(mat): """ Remove the ID (1st row element) form a matrix :param mat: a 2D list :rtype: a 2D list with the 1st row elelemnt (ID) removed """ new_mat = [] for i in range(0, len(mat)): new_mat.append(mat[i][1:]) return new_mat
def get_status_code_value(status_code): """function to return appropriate status code value from the dictionary""" status_code_dict = { "100": "Continue", "101": "Switching Protocols", "200": "OK", "201": "Created", "202": "Accepted", "203": "Non-authoritative Information", "204": "No Content", "205": "Reset Content", "206": "Partial Content", "300": "Multiple Choices", "301": "Moved Permanently", "302": "Found", "303": "See Other", "304": "Not Modified", "305": "Use Proxy", "306": "Unused", "307": "Temporary Redirect", "400": "Bad Request", "401": "Unauthorized", "402": "Payment Required", "403": "Forbidden", "404": "Not Found", "405": "Method Not Allowed", "406": "Not Acceptable", "407": "Proxy Authentication Required", "408": "Request Timeout", "409": "Conflict", "410": "Gone", "411": "Length Required", "412": "Precondition Failed", "413": "Request Entity Too Large", "414": "Request-url Too Long", "415": "Unsupported Media Type", "416": "Requested Range Not Satisfiable", "417": "Expectation Failed", "500": "Internal Server Error", "501": "Not Implemented", "502": "Bad Gateway", "503": "Service Unavailable", "504": "Gateway Timeout", "505": "HTTP Version Not Supported" } return status_code_dict[status_code]
def bench5(x): """A benchmark function for test purposes. f(x) = float(x[0]) ** 2 + x[1] ** 2 where x is a string. It has a single minima with f(x) = 0 at x[0] = "0" and x[1] = "0" This benchmark is used for checking support of mixed spaces. """ return float(x[0]) ** 2 + x[1] ** 2
def split_url(url): """ Split the given URL ``base#anchor`` into ``(base, anchor)``, or ``(base, None)`` if no anchor is present. In case there are two or more ``#`` characters, return only the first two tokens: ``a#b#c => (a, b)``. :param string url: the url :rtype: list of str """ if url is None: return (None, None) array = url.split("#") if len(array) == 1: array.append(None) return tuple(array[0:2])
def int_to_string(integer, keyspace_chars): """ Turn a positive integer into a string. """ if not integer > 0: raise ValueError('integer must be > 0') output = "" while integer > 0: integer, digit = divmod(integer, len(keyspace_chars)) output += keyspace_chars[digit] return output[::-1]
def runlength2(blk, p0, p1, bsf): """ p0 is the source position, p1 is the dest position Return the length of run of common chars """ if blk[p0:p0+bsf+1] != blk[p1:p1+bsf+1]: return 0 for i in range(bsf + 1, len(blk) - p1): if blk[p0:p0+i] != blk[p1:p1+i]: return i - 1 return len(blk) - p1 - 1
def get_binary_representation(n, num_digits): """ Helper function to get a binary representation of items to add to a subset, which combinations() uses to construct and append another item to the powerset. Parameters: n and num_digits are non-negative ints Returns: a num_digits str that is a binary representation of n """ result = '' while n > 0: result = str(n%2) + result n = n//2 if len(result) > num_digits: raise ValueError('not enough digits') for i in range(num_digits - len(result)): result = '0' + result return result
def origin(current, start, end, cum_extents, screen, moving): """Determine new origin for screen view if necessary. The part of the DataFrame displayed on screen is conceptually a box which has the same dimensions as the screen and hovers over the contents of the DataFrame. The origin of the relative coordinate system of the box is calculated here. >>> origin(0, 0, 0, [0, 4, 8, 12], 7, True) 0 >>> origin(4, 0, 2, [0, 4, 8, 12], 7, True) 5 >>> origin(5, 1, 1, [0, 4, 8, 12], 7, False) 4 :param current: current origin of a given axis :type current: int :param start: leftmost column index or topmost row index selected :type start: int :param end: rightmost column index or bottommost row index selected :type end: int :param cum_extents: cumulative sum of column widths or row heights :type cum_extents: numpy.ndarray :param screen: total extent of a given axis :type screen: int :param moving: flag if current action is advancing :type: bool :returns: new origin :rtype: int """ # Convert indices to coordinates of boundaries start = cum_extents[start] end = cum_extents[end+1] if end > current + screen and moving: return end - screen elif start < current and not moving: return start else: return current
def _amplify_qm(text): """ check for added emphasis resulting from question marks (2 or 3+) """ qm_count = text.count("?") qm_amplifier = 0 if qm_count > 1: if qm_count <= 3: # (empirically derived mean sentiment intensity rating increase for # question marks) qm_amplifier = qm_count * 0.18 else: qm_amplifier = 0.96 return qm_amplifier
def VOLTStoHEX(volts): """ DAC: 1000.0 volts full scale (FFFF). (for setting DAC output) VOLTStoHEX(1000.0) => 'FFFF' VOLTStoHEX( 900.0) => 'E665' """ return hex(int(volts * 65.535))[2:].upper()
def pad_pokemon_id(pokemon_id: int) -> str: """Pads a pokemon's id with 0's. Examples: 1 -> 001 23 -> 023 144 -> 144 Args: pokemon_id: The pokemon's id Returns: A string with padded 0's in front. """ return f"{pokemon_id:03}"
def get_commit_merge_message( head_commit_id: str, user_commit_id: str, user_input: str ) -> str: """Shortens the commit ids and adds them to a commit message; if user used a branch name, the latter will appear next to the id. Example: `Merged 123456 (HEAD) with 654321 (<branch_name>)`. """ shortened_head_id = head_commit_id[:6] is_id = user_input == user_commit_id merged_with = ( user_commit_id[:6] if is_id else f"{user_commit_id[:6]} ({user_input})" ) commit_message = f"Merged {shortened_head_id} (HEAD) with {merged_with}." return commit_message
def isnumeric(value): """ "0.2355" would return True. A little auxiliary function for command line parsing. """ return str(value).replace(".", "").replace("-", "").isdigit()
def _decode_node(s): """Map string `s` to node-like integer.""" if s == 'F': return -1 elif s == 'T': return 1 else: return int(s)
def to_tuple(expression): """ Convert nested list to nested tuple """ my_tup=tuple() for elem in expression: if type(elem)!=list: my_tup=my_tup+tuple([elem]) else: my_tup=my_tup+tuple([to_tuple(elem)]) return (my_tup)
def get_dependencies(key, mapping, recurse=True): """ Get the full set of dependencies required by an extension :param key: extension base name or skin as 'skin/BASENAME' :param mapping: mapping of repositories to their dependencies :param recurse: Whether to recursively process dependencies :return: set of dependencies """ resolved = set() def resolve_deps(ext): resolved.add(ext) deps = set() if ext in mapping: for dep in mapping[ext]: deps.add(dep) if recurse and dep not in resolved: deps = deps.union(resolve_deps(dep)) return deps return resolve_deps(key)
def matSub(mat1, mat2): """Return matrix - matrix.""" dim = len(mat1) return tuple( tuple( mat1[i][j] - mat2[i][j] for j in range(dim) ) for i in range(dim) )
def generate_nodes_binary_status(nodes_status, number_cascades): """ Parameters ---------- nodes_status: list The status for each node (if number_cascades = 3): [(1, 1),(2, 3),...,(n, 0)] number_cascades: int The number of competitive cascades Returns --------- node_status_binary_mode: list [(1, 0, 0), (0, 0, 1),...,(0, 0, 0)] """ nodes_status_binary_mode = [] for instance in nodes_status: one_node = [] for cascade in range(1, number_cascades + 1): if instance[1] == cascade: one_node.append(1) else: one_node.append(0) nodes_status_binary_mode.append(one_node) return nodes_status_binary_mode
def to_matrix(graph): """Function for convert graph to matrix This function is getting the json-data and return list of lists like: [ [0, 1, 1], [0, 0, 1], [0, 1, 0], ]. """ graph_names = [node["name"] for node in graph["nodes"]] numb_of_nodes = len(graph_names) matrix = [[0] * numb_of_nodes for i in range(0, numb_of_nodes)] for edge in graph["edges"]: first_node = graph_names.index(edge["firstNode"]) second_node = graph_names.index(edge["secondNode"]) matrix[first_node][second_node] = 1 return matrix
def bubble(sortlist): """checks for adjacent values and swaps them on the spot""" for i in range(0,len(sortlist)): for j in range(0,len(sortlist)-1): if sortlist[j] > sortlist[j+1]: sortlist[j],sortlist[j+1] = sortlist[j+1],sortlist[j] return sortlist
def findIsolatedNodes (graph): """ Returns a list of isolated nodes. """ isolated = [] for node in graph: if not graph[node]: isolated += node return isolated
def full_name(app): """Builds App full_name, prepending the App with the name of the parent App. :param app: App as returned by queries.get_apps() :type app: dict :return: full name of the app :rtype: string """ name = app['name'] if app.get('parentApp'): parent_app = app['parentApp']['name'] name = f"{parent_app}/{name}" return name
def _deal_with_update(template: str) -> str: """ For the patch of UPDATE statement, avoid redundant commas in update set :param template: Template :return: Results after treatment """ up_template = template.upper() index_update = up_template.find("UPDATE") index_where = up_template.find("WHERE") if index_update != -1 and index_where != -1: index_where -= 1 while index_where > 0: char = up_template[index_where] if char == ' ': index_where -= 1 continue if char == ',': template = template[:index_where] + template[index_where + 1:] break return template
def check_blank_row(person_row: list): """ This function takes a name row and sees if theres enough information to determine if the row has no information in it.\n @param personRow the row to be determined whether or not its blank.\n @return True if the row is blank and can be removed, False otherwise. """ count_confirms = 1 count_blanks = 1 for i in person_row[:4]: # and every one. any false will 0 the entire thing count_confirms *= i[2] count_blanks *= (i[0] == '') return count_confirms and count_blanks
def retrieve_task_id(context): """Helper to retrieve the `Task` identifier from the message `body`. This helper supports Protocol Version 1 and 2. The Protocol is well detailed in the official documentation: http://docs.celeryproject.org/en/latest/internals/protocol.html """ headers = context.get('headers') body = context.get('body') if headers: # Protocol Version 2 (default from Celery 4.0) return headers.get('id') else: # Protocol Version 1 return body.get('id')
def flatten_voting_method(method): """Flatten a voting method data structure. The incoming ``method`` data structure is as follows. At the time of writing, all elections have an identical structure. In practice. the None values could be different scalars. :: { "instructions": { "voting-id": { "en_US": None, }, }, "excuse-required": None, "start": None, "end": None, "primary": None, "type": None, } This function flattens the US English voting ID instructions to become a top level item like all of the others. Args: method (dict): A nested voting method data structure. Returns: dict: A flat voting method data structure. """ flat_method = {k: v for k, v in method.items() if k != "instructions"} flat_method["instructions"] = method["instructions"]["voting-id"]["en_US"] return flat_method
def drop_non_lower(X): """ :param X: a data matrix: a list wrapping a list of strings, with each sublist being a sentence. :return: >>> drop_non_lower([['Catullus'], ['C.', 'VALERIVS', 'CATVLLVS'],['1','2', '2b', '3' ],['I.', 'ad', 'Cornelium'],['Cui', 'dono', 'lepidum', 'novum', 'libellum', 'arida', 'modo', 'pumice', 'expolitum', '?']]) [['Catullus'], [], ['2b'], ['ad', 'Cornelium'], ['Cui', 'dono', 'lepidum', 'novum', 'libellum', 'arida', 'modo', 'pumice', 'expolitum']] """ return [[word for word in sentence if word.upper() != word] for sentence in X]
def union_dicts(dicts: list) -> dict: """ :param dicts: :return: """ merged = {} for dic in dicts: try: for key in dic.keys(): merged[key] = dic[key] except Exception: raise TypeError("Dicts are as input required.") return merged
def time_formatter(seconds: float) -> str: """ humanize time """ minutes, seconds = divmod(int(seconds), 60) hours, minutes = divmod(minutes, 60) days, hours = divmod(hours, 24) tmp = ((str(days) + "d, ") if days else "") + \ ((str(hours) + "h, ") if hours else "") + \ ((str(minutes) + "m, ") if minutes else "") + \ ((str(seconds) + "s, ") if seconds else "") return tmp[:-2]
def concatenate(token_1, token_2): """ :param token_1: :param token_2: :return: """ if not token_2 or len(token_2) == 0: return token_1 return '%s%s%s' % (token_1, ' ' if len(token_1) > 0 else '', token_2)
def valFallingSlopes(Frames): """Computes values of FALLING slopes.Returns a list of all values of FALLING slopes in the signal.""" previous, slopes = Frames[0], [] for i in range(len(Frames)): if Frames[i] < previous: slopes.append(previous - Frames[i]) previous = Frames[i] return slopes
def get_city_from_team(cityteam): """Returns a city and teamname from teamname in lower case. It should return the contents of class wide-matchup from the NHL schedule For historical reasons: This function used to return a city from a team name, citydict1 had entries like: "Washington" : "Washington Capitals", This function is not named well anymore, but it works ;) Something like, get_city_team_from_team? Confusing in any case.. """ citydict1 = { "ducks": "Anaheim Ducks", "coyotes": "Arizona Coyotes", "bruins": "Boston Bruins", "buffalo": "Buffalo Sabres", "hurricanes": "Carolina Hurricanes", "bluejackets": "Columbus Blue Jackets", "flames": "Calgary Flames", "blackhawks": "Chicago Blackhawks", "avalanche": "Colorado Avalanche", "stars": "Dallas Stars", "redwings": "Detroit Red Wings", "oilers": "Edmonton Oilers", "panthers": "Florida Panthers", "kings": "Los Angeles Kings", "wild": "Minnesota Wild", "canadiens": "Montreal Canadiens", "devils": "New Jersey Devils", "predators": "Nashville Predators", "islanders": "New York Islanders", "rangers": "New York Rangers", "senators": "Ottawa Senators", "flyers": "Philadelphia Flyers", "penguins": "Pittsburgh Penguins", "sharks": "San Jose Sharks", "blues": "St Louis Blues", "lightning": "Tampa Bay Lightning", "leafs": "Toronto Maple Leafs", "canucks": "Vancouver Canucks", "goldenknights": "Vegas Golden Knights", "jets": "Winnipeg Jets", "capitals": "Washington Capitals", "kraken": "Seattle Kraken", } # Flip because I'm lazy citydict1flip = {value: key for key, value in citydict1.items()} try: return citydict1flip[cityteam] except KeyError: return ""
def colorize(string, color, bold=False, highlight=False): """ Colorize a string. This function was originally written by John Schulman. """ color2num = dict( gray=30, red=31, green=32, yellow=33, blue=34, magenta=35, cyan=36, white=37, crimson=38 ) attr = [] num = color2num[color] if highlight: num += 10 attr.append(str(num)) if bold: attr.append('1') return '\x1b[%sm%s\x1b[0m' % (';'.join(attr), string)
def serialise(entry): """Serialise an entry.""" if not entry: return None ret = entry._asdict() ret['type'] = entry.__class__.__name__ if ret['type'] == 'Transaction': if entry.tags: ret['narration'] += ' ' + ' '.join(['#' + t for t in entry.tags]) if entry.links: ret['narration'] += ' ' + ' '.join(['^' + l for l in entry.links]) del ret['links'] del ret['tags'] ret['postings'] = [serialise(pos) for pos in entry.postings] return ret
def parse_cookie(cookie): """ Parse cookie string and return a dictionary where key is a name of the cookie and value is cookie value. """ return cookie and dict([pair.split('=', 1) for pair in cookie.split('; ')]) or {}
def simplify(num, denom): """Given a numerator and denominator for a fraction, reduce it to lowest terms""" while num % 2 == 0 and denom % 2 == 0: num = num >> 1 denom = denom >> 1 factor = 3 while factor <= num: while num % factor == 0 and denom % factor == 0: num = int(round(num / factor)) denom = int(round(denom / factor)) factor += 2 return [num, denom]
def _iterate_over_nested_obj(obj, key): """It iterates over the nested dict object. It iterates over two types of data * list * dict for the rest data type it returns the value Args: obj (any type): object to process key (str, int): key to find in object """ if isinstance(obj, dict): if obj.get(key): return obj[key] elif isinstance(obj, list): for item in obj: value = _iterate_over_nested_obj(item, key) if value: return value return None else: return None
def dictFromList(data_list): """Returns a dict given a list. - Dict created from a list where list contains alternating key, value pairs. - ex: [key1, value1, key2, value2] returns: {key1:value1, key2:value2} """ data_dict = {} for i in range(0,len(data_list)-1,2): #If there is already a value for the given key if data_list[i] in data_dict: #Add the rest of data to the value string data_dict[data_list[i]] = data_dict[data_list[i]] + ' ' + \ data_list[i+1] else: #Otherwise add value to given key data_dict[data_list[i]] = data_list[i+1] return data_dict
def function_04(parameter_01, parameter_02, parameter_03): """ Function description. Parameters ---------- parameter_01 : type Description. parameter_02 : type Description. parameter_03 : type Description. Returns ------- return_01 Description. """ return_01 = parameter_01 + parameter_02 + parameter_03 return return_01
def _get_class_category_href(c_name: str) -> str: """Return a href for linking to the specified class category.""" return 'class_category_' + c_name.replace('.', '_').replace(' ', '_')
def get_potential(q): """Return potential energy on scaled oscillator displacement grid q.""" return q ** 2 / 2
def dfs(grid, row, col): """ :type grid: List[List[str]] :type row : int :type col : int :rtype : int """ # Checking for Out of Bounds if (row < 0 or col < 0 or row > len(grid)-1 or col > len(grid[row])-1 or grid[row][col] == '0'): return 0 # Assigning the traversed the element to a '0' grid[row][col] = '0' # Recursive DFS calls to traverse through the neighbors # Below the element dfs(grid, row+1, col) # Above the element dfs(grid, row-1, col) # To the right of the element dfs(grid, row, col+1) # To the left of the element dfs(grid, row, col-1) # Returning 1 after successful traversing from all the neighbors return 1
def _match_field(line, field): """ Return the remaining part of the line in case of matching field, otherwise it returns None. """ if line is None or len(line) < 2: return None if line[0] == '*' and line[1] == ':': # Match (star). return line[2:] escaped = False while line: if not escaped and line[0] == '\\': line = line[1:] escaped = True if not line: return None if not escaped and line[0] == ':' and not field: # match return line[1:] escaped = False if not field: return None elif field[0] == line[0]: line = line[1:] field = field[1:] else: return None return None
def ShouldCheckFile(file_name): """Returns True if the given file is a type we want to check.""" if len(file_name) < 2: return False return file_name.endswith(".cc") or file_name.endswith(".h")
def binary_search_recursive(array, elem, offset=0): """ Binary search algorithm. Complexity of algorithm is log(n). :param array: should be sorted list of elements :param elem: element to find in array :param offset: default is 0, used for recursive call :return: index of element in array if it's in array, otherwise -1 """ ind = len(array) % 2 if elem == array[ind]: return ind + offset elif elem > array[ind]: return binary_search_recursive(array[ind + 1:], elem, offset + ind + 1) else: return binary_search_recursive(array[:ind - 1], elem, offset)
def hello(name="World"): """ python3 all.py hello > Hello World python3 all.py hello --name Yazid > Hello Yazid """ return "Hello %s" % name
def script_run_DB2Falcon(config, preads4falcon_fn, preads_db): """Run in pread_dir. """ params = dict(config) params.update(locals()) script = """\ # Given preads.db, # write preads4falcon.fasta (implicitly) in CWD. time DB2Falcon -U {preads_db} [ -f preads4falcon.fasta ] || exit 1 """.format(**params) return script
def _from_file(filename): """Open a file and read its first line. :param filename: the name of the file to be read :returns: string -- the first line of filename, stripped of the final '\n' :raises: IOError """ with open(filename) as f: value = f.readline().rstrip('\n') return value
def quicksort(arr, pivi=0): """Return a sorted 2D numerical array smallest -> largest.""" if len(arr) < 2: return arr else: piv = arr[pivi] lower = [v for v in arr[1:] if v <= piv] higher = [v for v in arr[1:] if v > piv] return quicksort(lower) + [piv] + quicksort(higher)
def agent_alive_id_list(agent_list, agent_type): """Return a list of agents that are alive from an API list of agents :param agent_list: API response for list_agents() """ return [agent['id'] for agent in agent_list if agent['agent_type'] == agent_type and agent['alive'] is True]
def merge(A, p, q, r): """Assumes A to be an array of numbers, p, q, and r are indices of the array A such that that p <= q < r. The process also assumes that the subarrays A[p, q] and A[q+1, r] are sorted.""" n1 = q-p+1 n2 = r-q L, R = [], [] for i in range(n1): L.append(A[p+i]) for j in range(n2): R.append(A[q+j+1]) L.append(1000) R.append(1000) i = 0 j = 0 for k in range(p, r+1): if L[i] <= R[j]: A[k] = L[i] i += 1 else: A[k] = R[j] j += 1 return A
def ignore_urls(searchurls, ignoreurls): """Removes URLs that are common to both lists, given a list of URLs and another list of URLs to ignore. Args: searchurls (list): initial list of URLs to remove from. ignoreurls (list): a list of URLs to remove from searchurls. Returns: list: a list containing URLs that were not found in ignoreurls. """ # finds the common elements between the two lists and gets rid of them finalurls = list(set(searchurls) ^ set(ignoreurls)) return finalurls
def whitespace_tokenize(text): """ Desc: runs basic whitespace cleaning and splitting on a piece of text """ text = text.strip() if not text: return [] tokens = text.split() return tokens
def merge_result(docker_list: dict, result_dict: dict = {}, max_entries_per_docker: int = 5) -> dict: """Returns a python dict of the merge result :type docker_list: ``dict`` :param docker_list: dictionary representation for the docker image used by integration or script :type result_dict: ``dict`` :param result_dict: dictionary representation for the docker image and the integration/scripts belongs to it merge the current result to it :type max_entries_per_docker: ``int`` :param max_entries_per_docker: max number of integration or script to show per docker image entry :return: dict as {'docker_image':['integration/scripts', 'integration/scripts',...]} :rtype: dict """ result = result_dict or {} for integration_script, docker_image in docker_list.items(): if integration_script in ['CommonServerUserPowerShell', 'CommonServerUserPython']: continue if docker_image in result: if len(result[docker_image]) < max_entries_per_docker: result[docker_image].append(integration_script) else: result[docker_image] = [integration_script] return result
def __to_camel(method_name: str) -> str: """ Function converts to camel case specific method name. First version of naming: <get|set>_your_action -> getYourAction Second version of naming: _<get|set> -> get :param method_name: As is :return: str """ tmp = method_name[:] if tmp.startswith('_'): tmp = tmp[-(len(tmp) - 1):] return "".join( w.lower() if i == 0 else w.title() for i, w in enumerate(tmp.split('_')) )
def getOrElseUpdate(dictionary, key, opr): """If given key is already in the dictionary, returns associated value. Otherwise compute the value with opr, update the dictionary and return it. None dictionary are ignored. >>> d = dict() >>> getOrElseUpdate(d, 1, lambda _: _ + 1) 2 >>> print(d) {1: 2} @type dictionary: dictionary of A => B @param dictionary: the dictionary @type key: A @param key: the key @type opr: function of A => B @param opr: the function to compute new value from keys @rtype: B @return: the value associated with the key """ if dictionary is None: return opr(key) else: if key not in dictionary: dictionary[key] = opr(key) return dictionary[key]
def penn_to_wordnet(tag): """ Convert a Penn Treebank PoS tag to WordNet PoS tag. """ if tag in ['NN', 'NNS', 'NNP', 'NNPS']: return 'n' #wordnet.NOUN elif tag in ['VB', 'VBD', 'VBG', 'VBN', 'VBP', 'VBZ']: return 'v' #wordnet.VERB elif tag in ['RB', 'RBR', 'RBS']: return 'r' #wordnet.ADV elif tag in ['JJ', 'JJR', 'JJS']: return 'a' #wordnet.ADJ return None
def get_fixed_length_string(string: str, length=20) -> str: """ Add spacing to the end of the string so it's a fixed length. """ if len(string) > length: return f"{string[: length - 3]}..." spacing = "".join(" " for _ in range(length - len(string))) return f"{string}{spacing}"
def binary_search(a_list, item): """ >>> test_list = [0, 1, 2, 8, 13, 17, 19, 32, 42] >>> print(binary_search(test_list, 3)) False >>> print(binary_search(test_list, 13)) True """ if len(a_list) == 0: return False midpoint = len(a_list) // 2 if a_list[midpoint] == item: return True if item < a_list[midpoint]: return binary_search(a_list[:midpoint], item) else: return binary_search(a_list[midpoint + 1 :], item)
def ver_tuple_to_str(req_ver): """Converts a requirement version tuple into a version string.""" return ".".join(str(x) for x in req_ver)
def get_repository_name(url): """ This function returns the name of the repository for splitting the url of the repository. :Arguments: 1. url (str) = url of the repository as stated by the user in the xml file :Returns: string = name of the repository """ li_temp_1 = url.rsplit('/', 1) return li_temp_1[1][:-4] if \ li_temp_1[1].endswith(".git") else li_temp_1[1]
def decimal_to_hex(number): """ This function calculates the hex of the given decimal number :param number: decimal number in string or integer format :return : string of the equivalent hex number Algo: 1. Divide the decimal number by 16. Treat the division as an integer division. 2. Write down the remainder (in hexadecimal). 3. Divide the result again by 16. Treat the division as an integer division. 4. Repeat step 2 and 3 until result is 0. 5. The hex value is the digit sequence of the remainders from the last to first. """ if isinstance(number, str): number = int(number) hexadec = [] hex_equivalents = {10: "A", 11: "B", 12: "C", 13: "D", 14: "E", 15: "F"} while number >= 1: remainder = number % 16 if remainder < 10: hexadec.append(remainder) elif remainder >= 10: hexadec.append(hex_equivalents[remainder]) number = number // 16 return "".join(map(str, hexadec[::-1]))
def scheduler(epoch): """ Learning rate scheduler """ lr = 0.0001 if epoch > 25: lr = 0.00001 elif epoch > 60: lr = 0.000001 print('Using learning rate', lr) return lr
def transform_pesq_range(pesq_score): """transform PESQ metric range from [-0.5 ~ 4.5] to [0 ~ 1] Args: pesq_score (float): pesq score Returns: pesq_score: transformed pesq score """ return (pesq_score + 0.5) / 5
def isglob(path): """ Checks if *path* is a glob pattern. Returns #True if it is, #False if not. """ return '*' in path or '?' in path
def split_decimal(flt): """ split decimal params: flt : <float> float to convert returns: <tuple> ( whole number, decimal part) """ whole, dec = str(flt).split('.') # dec = int(dec) # if dec >= 5: # return int(whole) + 1, dec return [int(whole), int(dec)]
def hk_sp_errors(bits: list) -> bytes: """ First bit should be on the left, bitfield is read from left to right """ error_bits = 0 bits.reverse() for i in range(len(bits)): error_bits |= bits[i] << i return error_bits.to_bytes(2, byteorder='big')
def _mapfuns(d1, d2): """ Given two dicts, d1 (k1 -> v1) and d2 (k2 -> v2), returns a dict which has the mapping (k1 -> k2) such that _name(k1) == _name(k2). """ def _name(fn): """ Strips the line number at the end if any. Eg. 'foo.py:23' -> 'foo.py', 'foo:bar.py' -> 'foo:bar.py' etc. """ parts = fn.rsplit(':', 1) try: int(parts[1]) return parts[0] except Exception: return fn m1 = [(_name(f), f) for f in d1] m2 = dict([(_name(f), f) for f in d2]) return dict([(v, m2[k]) for k, v in m1 if k in m2])
def good_fft_number(goal): """pick a number >= goal that has only factors of 2,3,5. FFT will be much faster if I use such a number""" assert goal < 1e5 choices = [2**a * 3**b * 5**c for a in range(17) for b in range(11) for c in range(8)] return min(x for x in choices if x >= goal)
def evaluate_status2led(elm): """ adapter between color rendered by `led.css` and statuses returned by `guestoo` color-space: ['red', 'orange', 'yellow', 'green', 'blue'] status-space: ['INVITED', 'OPEN', 'DECLINED', 'CONFIRMED', 'APPEARED'] """ guest_status = elm['events'][0]['status'] if guest_status == 'CONFIRMED': status = 'led led-green' else: status = 'led led-yellow' return status
def get_leader(tokens, token_index, size): """ Create a tuple out of the tokens that precede the token at the given index. If the leader would extend beyond the begging of tokens None will be used. :param tokens: the tokens to create the leader from :param token_indiex: the index of the token ot get the leader of :param size: the number of tokens to include in the leader :return: the leader to the token at the given index """ leader = [] for offset in range(size): leader_index = (token_index - 1) - offset leader.append(tokens[leader_index] if leader_index >= 0 else None) return tuple(leader)
def extract_vars(l): """ Extracts variables from lines, looking for lines containing an equals, and splitting into key=value. """ data = {} for s in l.splitlines(): if '=' in s: name, value = s.split('=') data[name] = value return data
def ifan03to02(state) -> dict: """Convert incoming from iFan03.""" return {'switches': [ {'outlet': 0, 'switch': state['light']}, {'outlet': 1, 'switch': state['fan']}, {'outlet': 2, 'switch': 'on' if state['speed'] == 2 else 'off'}, {'outlet': 3, 'switch': 'on' if state['speed'] == 3 else 'off'}, ]}
def convert_bytes(num): """ this function will convert bytes to MB.... GB... etc """ for x in ['bytes', 'KB', 'MB', 'GB', 'TB', 'XB']: if num < 1024.0: return "%3.1f %s" % (num, x) num /= 1024.0
def replace_multiple(text, dic): """replace multiple text fragments in a string""" for i, j in dic.items(): text = text.replace(i, j) return text
def generate_scenarios(key, test_cases): """ This function generates the test case scenarios according to key given to it, e.g. key=ADD, key=update etc. :param key: for which operation generate the test scenario :type key: str :param test_cases :type test_cases: list :return: scenarios :rtype: list """ scenarios = [] for scenario in test_cases[key]: test_name = scenario["name"] scenario.pop("name") tup = (test_name, dict(scenario)) scenarios.append(tup) return scenarios
def _parameters_link(args, parameters): """Build arguments based on the arguments and parameters provided.""" args_ = {} for index, arg in enumerate(args): args_.setdefault(arg, []).append(index) args_ = {key: iter(value) for key, value in args_.items()} return [next(args_.get(p, iter([p]))) for p in parameters]
def filterString(text): """ Replace/Remove invalid file characters text : The text to search in Returns: A filtered version of the given string """ # Remove invalid chars text = text.strip() text = text.replace(':', ';') text = text.replace('?', '') text = text.replace('"', "'") return text;
def add_suffix(signals, suffix): """Add `suffix` to every element of `signals`.""" return [s + suffix for s in signals]
def temp_depression(ua_per_ft2, balance_point, outdoor_temp, doors_open): """Function returns the number of degrees F cooler that the bedrooms are relative to the main space, assuming no heating system heat is directly provided to bedrooms. Bedrooms are assumed to be adjacent to the main space that is heated directly by a heating system. This function can be used for other rooms that are adjacent to the main space and not directly heated. See https://github.com/alanmitchell/heat-pump-study/blob/master/general/bedroom_temp_depression.ipynb for derivation of the formula. 'ua_per_ft2': is the heat loss coefficient per square foot of floor area for the building. It is measured as Btu/hour/deg-F/ft2 'balance_point': is the balance point temperature (deg F) for the building; an outdoor temperature above which no heat needs to be supplied to the building. 'outdoor_temp': the outdoor temperature, deg F. 'doors_open': True if the doors between the main space and the bedroom are open, False if they are closed. """ r_to_bedroom = 0.424 if doors_open else 1.42 temp_delta = balance_point - outdoor_temp temp_depress = temp_delta * r_to_bedroom / (r_to_bedroom + 1.0/ua_per_ft2) return temp_depress
def _B_at_h(h1, h2): """Evaluates B auxiliary variable at given h coefficients. Parameters ---------- h1: float The first of the h coefficients. h2: float The second of the h coefficients. Returns ------- B: float Auxiliary variable. Notes ----- This is equation (56) from the original report. """ B = (27 * h2) / (4 * (1 + h1) ** 3) return B
def parse_repository_tag(repo_path): """Splits image identification into base image path, tag/digest and it's separator. Example: >>> parse_repository_tag('user/repo@sha256:digest') ('user/repo', 'sha256:digest', '@') >>> parse_repository_tag('user/repo:v1') ('user/repo', 'v1', ':') """ tag_separator = ":" digest_separator = "@" if digest_separator in repo_path: repo, tag = repo_path.rsplit(digest_separator, 1) return repo, tag, digest_separator repo, tag = repo_path, "" if tag_separator in repo_path: repo, tag = repo_path.rsplit(tag_separator, 1) if "/" in tag: repo, tag = repo_path, "" return repo, tag, tag_separator
def align(n, a): """Align @n to @a bytes. Examples: align(4, 4) = 4 align(3, 4) = 4 align(0, 4) = 0 align(5, 4) = 8 Args: n (numbers.Integral): Virtual address to align a (numbers.Integral): Alignment Returns: New, aligned address, or @n if already @a-byte aligned. """ return (n + (a - 1)) & ~(a - 1)
def circle_area(radius: float) -> float: """ >>> circle_area(10) 314.1592653589793 >>> circle_area(0) 0.0 """ import math return math.pi * radius * radius
def is_number(s): """ checks if passed in variable is a float """ try: float(s) return True except: pass return False
def remove_intro(l): """ Remove the marker that indicates this is a change to introductory text. """ return l.replace('[text]', '')
def page_not_found(e): """Return a custom 404 error.""" return 'Sorry, nothing at this URL. (' + str(e) + ')', 404
def _is_caching_needed(m): """Check if image should be cached or not :param m: the meta-data dictionary of an image :return: False if it's not ok to cache or already cached True if is good to cache or previous caching failed """ # Check main status and format if m['status'] != 'active' or m['disk_format'] == 'raw': return False # Check the caching properties p = m.get('properties', {}) if p.get('cache_raw', '') == 'True': cache_raw_status = p.get('cache_raw_status', '') if cache_raw_status != 'Cached': return True # we retry the conversion if the image is in Error return False return False
def GetAccelIndex(label): """ Returns the mnemonic index of the label and the label stripped of the ampersand mnemonic (e.g. 'lab&el' ==> will result in 3 and labelOnly = label). :param `label`: a string containining an ampersand. """ indexAccel = 0 while True: indexAccel = label.find("&", indexAccel) if indexAccel == -1: return indexAccel, label if label[indexAccel:indexAccel+2] == "&&": label = label[0:indexAccel] + label[indexAccel+1:] indexAccel += 1 else: break labelOnly = label[0:indexAccel] + label[indexAccel+1:] return indexAccel, labelOnly
def format_filesize(value): """ Return a human readable filesize for a given byte count """ if not value: return "" for x in ['bytes', 'KB', 'MB', 'GB', 'TB', 'PB']: if value < 1024.0: return "%3.1f %s" % (value, x) value /= 1024.0 return value
def _compare_across(collections, key): """Return whether all the collections return equal values when called with `key`.""" if len(collections) < 2: return True c0 = key(collections[0]) return all(c0 == key(c) for c in collections[1:])
def isValid(s): """ :type s: str :rtype: bool """ ## given a string of just parentheses ## go through the string ## keep track if something is the correct closing parentheses ## O(N) where n is length of the string ## {[]} stack = [] par_mapping = {"}" : "{", "]" : "[", ")" : "("} #maybe add in count of |? for p in s: if p in par_mapping: if len(stack) == 0: return False most_recent = stack.pop() if par_mapping[p] != most_recent: return False else: stack.append(p) if len(stack) != 0: return False return True
def isalpha(obj): """ Test if the argument is a string representing a number. :param obj: Object :type obj: any :rtype: boolean For example: >>> import pmisc >>> pmisc.isalpha('1.5') True >>> pmisc.isalpha('1E-20') True >>> pmisc.isalpha('1EA-20') False """ # pylint: disable=W0702 try: float(obj) return isinstance(obj, str) except: return False
def pid_controller(proportional_value, integral_value, derivative_value): """Docstring here (what does the function do)""" return derivative_value + (proportional_value + integral_value)
def decode(line): """Make treatment of stdout Python 2/3 compatible""" if isinstance(line, bytes): return line.decode('utf-8') return line
def add_layer(a_binary, C, ori_tile, gg_tile): """ add layer for building complexity fractiles """ for i in range(C-1): extend_tile = () for tt in a_binary: if tt == 0: # G(gold exist) extend_tile += gg_tile elif tt == 1: # L(gold not exist) extend_tile += ori_tile a_binary = extend_tile return a_binary
def latex_name(model_name): """ Replaces model names with latex-friendly names. E.g. "avg_br" becomes "$E_{avg}|D_{br}$". Args: model_name (str): original name of the model Returns: latex_name (str): latex-friendly translation of the model name """ if model_name == "enc_dec": return "$seq2seq$" elif "enc_dec_" in model_name: return "$seq2seq_{{{}}}$".format(model_name[len("enc_dec_"):]) elif "_" not in model_name: return model_name i = model_name.index("_") return "$E_{{{}}}|D_{{{}}}$".format(model_name[:i], model_name[i+1:])