content
stringlengths
42
6.51k
def toJadenCase(string): """ Convert strings to how they would be written by Jaden Smith. The strings are actual quotes from Jaden Smith, but they are not capitalized in the same way he originally typed them. Example: Not Jaden-Cased: "How can mirrors be real if our eyes aren't real" Jaden-Cased: "How Can Mirrors Be Real If Our Eyes Aren't Real" :param string: :return: """ list_string = string.split() for i, el in enumerate(list_string): list_string[i] = el.capitalize() new_string = ' '.join(list_string) return new_string
def strMakeComma(categories): """ Make comma seperate string i.e: a, b, c """ result = "" for catg in categories: result += catg["name"] + ", " if len(result) > 0: result = result[:len(result) - 2] return result
def difference(actual, expected): """ Returns strings describing the differences between actual and expected sets. Example:: >>> difference({1, 2, 3}, {3, 4, 5}) ('; added {1, 2}', '; removed {4, 5}') >>> difference({1}, {1}) ('', '') :param set actual: the actual set :param set expected: the expected set """ added = actual - expected if added: added = f'; added {added}' else: added = '' removed = expected - actual if removed: removed = f'; removed {removed}' else: removed = '' return added, removed
def compile_target_uri(url: str, query_string: bytes) -> str: """Append GET query string to the page path, to get full URI.""" if query_string: return f"{url}?{query_string.decode('utf-8')}" else: return url
def apply_weather_correction( enduse, fuel_y, cooling_factor_y, heating_factor_y, enduse_space_heating, enduse_space_cooling ): """Change fuel demand for heat and cooling service depending on changes in HDD and CDD within a region (e.g. climate change induced). Change fuel consumption based on climate change induced temperature differences Arguments ---------- enduse : str Enduse fuel_y : array Yearly fuel per fueltype cooling_factor_y : array Distribution of fuel within year to days (yd) heating_factor_y : array Distribution of fuel within year to days (yd) enduse_space_heating : list Enduses defined as space heating enduse_space_cooling : list Enduses defined as space cooling Return ------ fuel_y : array Changed yearly fuel per fueltype Note ---- - `cooling_factor_y` and `heating_factor_y` are based on the sum over the year. Therefore it is assumed that fuel correlates directly with HDD or CDD. """ if enduse in enduse_space_heating: fuel_y = fuel_y * heating_factor_y elif enduse in enduse_space_cooling: fuel_y = fuel_y * cooling_factor_y return fuel_y
def get_title(title_raw): """ Extracts title from raw string """ return title_raw.replace('\xa0', ' ').split('\n')[0].split('## ')[1]
def wordgen(iters, base_cases, rule, return_all=False): """generate arbitrary recursive words Args: iters (int): number of iterations to run on top of base cases base_cases (list of strings): strings which your rule can refer to rule (method): A function that takes in previous strings and returns a new string return_all (bool): return all of the strings generated for this call rule's call signature is rule(words:list of strings) -> string. it gets passed previous words, including base cases. returns: word """ words = base_cases n_base_case = len(base_cases) for _ in range(n_base_case, iters): words.append(rule(words)) if return_all: return words else: return words[iters-1]
def hmap_hash(str): """hash(str) -> int Apply the "well-known" headermap hash function. """ return sum((ord(c.lower()) * 13 for c in str), 0)
def fmt_dft(val): """Generate default argument description This secondary utility function is supporting formatting of command line argument help string """ return "" if val is None else " (default: {0})".format(val)
def list2pairlist(input_list: list, start=None) -> list: """ Example: input_list = [1,2,3,4,5], start=None -> [(1, 2), (2, 3), (3, 4), (4, 5)] input_list = [1,2,3,4,5], start=10 -> [(10, 1), (1, 2), (2, 3), (3, 4), (4, 5)] """ if start is not None: return [(start, input_list[0])] + list(zip(input_list[:-1], input_list[1:])) else: return list(zip(input_list[:-1], input_list[1:]))
def random_hex_code(number_of_digits): """ Creates a random string of hex characters. Parameters ---------- number_of_digits : int Returns ------- str """ import random digits = [] for i_digit in range(number_of_digits): i = random.randrange(16) digits.append("0123456789abcdef"[i]) return "".join(digits)
def get_tests(test_trie): """Gets all tests in this test trie. It detects if an entry is a test by looking for the 'expected' and 'actual' keys in the dictionary. The keys of the dictionary are tuples of the keys. A test trie like "foo": { "bar": { "baz": { "actual": "PASS", "expected": "PASS", } } } Would give you { ('foo', 'bar', 'baz'): { "actual": "PASS", "expected": "PASS", } } NOTE: If you are getting an error with a stack trace ending in this function, file a bug with crbug.com/new and cc martiniss@. """ if not isinstance(test_trie, dict): raise ValueError("expected %s to be a dict" % test_trie) tests = {} for k, v in test_trie.items(): if 'expected' in v and 'actual' in v: tests[(k,)] = v else: for key, val in get_tests(v).items(): tests[(k,) + key] = val return tests
def has_keyword(list_post, fields, keywords): """Return list Search list childs for a dict containing a specific keyword. """ results = [] for field in fields: if field in list_post: for keyword in keywords: if keyword.upper() in list_post[field].upper(): results.append(field) return results
def gtype( n ): """ Return the a string with the data type of a value, for Graph data """ t = type(n).__name__ return str(t) if t != 'Literal' else 'Literal, {}'.format(n.language)
def _get_log_formatter(verbosity_level): """ Get a log formatter string based on the supplied numeric verbosity level. :param int verbosity_level: the verbosity level :return: the log formatter string :rtype: str """ formatter = "%(levelname)s: %(message)s" if verbosity_level >= 3: formatter = "%(levelname)s: %(name)s: %(message)s" return formatter
def cmd_valid(cmd): """Checks to see if a given string command to be sent is valid in structure. Used in talk() prior to sending a command to the Arduino. Parameters ---------- cmd : str The command string to be sent. Command is structured as "<mode, motorID, arg_m1, arg_m2, arg_m3>", where mode is one of [RUN, STOP, RESUME, PAUSE, SET_SPEED, SET_ACCEL], and motorID is [1, 1, 1] (can be combo of numbers i.e. 100 or 101 or 001 (binary indicator), and arg_m* is any floating number. print_cols : bool, optional A flag used to print the columns to the console (default is False) Returns ------- bool A boolean indicating whether the command is valid (True) or not (False). """ cmds = ["RUN", "STOP", "RESUME", "PAUSE", "SET_SPEED", "SET_ACCEL"] inds = ["000", "100", "010", "001", "110", "101", "011", "111"] valid = False if "," in cmd and cmd[0] == '<' and cmd[-1]=='>': testcmd = cmd[1:].split(",")[0] ind = cmd[1:].split(",")[1] if testcmd in cmds and ind in inds: valid = True return valid return valid
def assign_relative_positions(abs_start, abs_end, overall_start): """Return relative positions given the absolute interval positions. Bases the relative positions from an overall starting position. Args: abs_start (int): global start of the interval, 1-based abs_end (int): global end of the interval, 1-based overall_start (int): absolute start of overall group of intervals Returns: tuple of int: relative start and end positions """ assert abs_start <= abs_end, 'Interval must be positive' assert overall_start <= abs_start, "Interval must overlap 'overall'" rel_start = abs_start - overall_start rel_end = abs_end - overall_start return rel_start, rel_end
def solution(M, A): """ 3 steps - 1. count the value of distinct in current window 2. check for duplicates 3. count distinct method- 0,0 tail ------ head for tail - 0 -------head 0,1,2,3...length :param M: :param A: :return: """ in_current_slice = [False] * (M + 1) total_slices = 0 head = 0 # for each tail... for tail in range(0, len(A)): print() print("For this tail.."+str(tail)) # start with each head... # check if not duplicate while head < len(A) and (not in_current_slice[A[head]]): print("For this head.." + str(head)) # mark item at head as visited in_current_slice[A[head]] = True # find total slices total_slices += (head - tail) + 1 head += 1 total_slices = 1000000000 if total_slices > 1000000000 else total_slices print("total up to here "+str(total_slices)) # one iteration is finished, now mark tail pointer location as not visited in_current_slice[A[tail]] = False return total_slices
def getEndAddress(fileSize, startAddress): """ :param fileSize: size of the FreeRTOS image used to add OTA descriptor in bytes :param startAddress: start address in decimal integer :return: end address in decimal integer """ endAddress = startAddress # initialize it as start address endAddress += fileSize # include the file size endAddress += 24 # include size of the OTA descriptor, currently we have 24 bytes return endAddress
def safe_get_value(maybe_dict, key: str): """ Get the value for `key` if `maybe_dict` is a `dict` and has that key. If `key` isn't there return `None`. Otherwise, `maybe_dict` isn't a `dict`, so return `maybe_dict` as is. """ if isinstance(maybe_dict, dict): return maybe_dict.get(key, None) return maybe_dict
def sub_dir_algo(d): """ build out the algorithm portion of the directory structure. :param dict d: A dictionary holding BIDS terms for path-building """ return "_".join([ '-'.join(['tgt', d['tgt'], ]), '-'.join(['algo', d['algo'], ]), '-'.join(['shuf', d['shuf'], ]), ])
def remove_special_characters(value): """ Remove special characters from argument :param value - a string containing special characters to remove :returns a string with special characters removed """ # If not a string then just return as is if not isinstance(value, str): return value # \, ', "" chars_to_remove = {92, 39, 34} new_value = "" # Check if each character in the given string is a special character for char in value: # If not then keep it if ord(char) not in chars_to_remove: new_value += char return new_value
def mean_squared_error(x1, x2): """Calculates the mean squared error between x1 and x2 [description] Arguments: x1 {list-like} -- the calculated values x2 {list-like} -- the actual values Returns: [type] -- [description] Raises: RuntimeError -- [description] """ if len(x1) != len(x2): raise RuntimeError("Length of two iterables is not the same") sum = 0. for i in range(len(x1)): sum += (x1[i] - x2[i])**2 return sum/float(len(x1))
def _uid2unixperms(perms, has_owner): """ Convert the uidperms and the owner flag to full unix bits """ res = 0 if has_owner: res |= (perms & 0x07) << 6 res |= (perms & 0x05) << 3 elif perms & 0x02: res |= (perms & 0x07) << 6 res |= (perms & 0x07) << 3 else: res |= (perms & 0x07) << 6 res |= (perms & 0x05) << 3 res |= 0x05 return res
def check_present(wanted, item_list): """ check if item is present in the list """ for item in item_list: if item.get('description') == wanted: return True return False
def projection_type_validator(x): """ Property: Projection.ProjectionType """ valid_types = ["KEYS_ONLY", "INCLUDE", "ALL"] if x not in valid_types: raise ValueError("ProjectionType must be one of: %s" % ", ".join(valid_types)) return x
def group_keys_by_attributes(adict, names, tol='3f'): """ Make group keys by shared values of attributes. Parameters ---------- adict : dic Attribute dictionary. name : str Attributes of interest. tol : float Float tolerance. Returns ------- dic Group dictionary. """ groups = {} for key, item in adict.items(): values = [] for name in names: if name in item: value = item[name] if type(value) == float: value = '{0:.{1}}'.format(value, tol) else: value = str(value) else: value = '-' values.append(value) vkey = '_'.join(values) groups.setdefault(vkey, []).append(key) return groups
def get_recursively(in_dict, search_pattern): """ Takes a dict with nested lists and dicts, and searches all dicts for a key of the field provided. """ fields_found = [] for key, value in in_dict.items(): if key == search_pattern: fields_found.append(value) elif isinstance(value, dict): results = get_recursively(value, search_pattern) for result in results: fields_found.append(result) return(fields_found)
def is_symmetrical(num: int) -> bool: """Determine if num is symmetrical.""" num_str = str(num) return num_str[::-1] == num_str
def get_models_weight(models_info): """Parses the information about model ids and weights in the `models` key of the fusion dictionary. The contents of this key can be either list of the model IDs or a list of dictionaries with one entry per model. """ model_ids = [] weights = [] try: model_info = models_info[0] if isinstance(model_info, dict): try: model_ids = [model["id"] for model in models_info] except KeyError: raise ValueError("The fusion information does not contain the" " model ids.") try: weights = [model["weight"] for model in models_info] except KeyError: weights = None else: model_ids = models_info weights = None return model_ids, weights except KeyError: raise ValueError("Failed to find the models in the fusion info.")
def is_product_bookable( product_code: str, availability: bool, durability: int, ) -> bool: # noqa E125 """Checks if a product is available for booking """ # Quick and dirty check if availability and durability > 0: return True else: return False
def page_start(weekday, day, month): """ Print the initialisation of the page """ lines = list() lines.append("<html>") lines.append("<head>") date = weekday.capitalize() + " " + str(day) + " " + str(month) lines.append("<title>Dagens mat - {}</title>".format(date)) lines.append('<link href="styles.css" rel="stylesheet" type="text/css">') lines.append('<style type="text/css"></style>') lines.append('<script src="js.js"></script>') lines.append('<meta name="viewport" content="width=device-width, initial-scale=1">') lines.append('<meta name="color-scheme" content="dark light">') lines.append('<link rel="icon" href="favicon.svg" type="image/svg+xml">') lines.append("</head>") lines.append("<body>") lines.append('<p class="warning"> Information is stale</p>') lines.append('<div id="content">') # page formatting lines.append("") return lines
def dec2hex(n, uni=1): """Convert decimal number to hex string with 4 digits, and more digits if the number is larger. >>> dec2hex(12) '000C' >>> dec2hex(100) '0064' >>> dec2hex(65535) 'FFFF' >>> dec2hex(100000) '186A0' """ hexadec = "%X" % n if uni == 1: while len(hexadec) <= 3: hexadec = '0' + str(hexadec) return hexadec
def is_out_of_bounds(board, row, col): """checks if the indexes are within the boundary of the board""" return not (0 <= row < len(board) and 0 <= col < len(board[0]))
def animals(chickens: int, cows: int, pigs: int) -> int: """Return the total number of legs on your farm.""" return sum([(chickens * 2), (cows * 4), (pigs * 4), ])
def _get_request_args(args): """ Build a tuple of the maximum age an event can be plus the maximum amount of records to return in the SQL query. If no argument is provided, or the value is uncastable to an int the respective default value or 360 and 1000 will be returned. """ try: maxage = int(args.get('maxage', 360)) except ValueError: maxage = 360 try: maxcount = int(args.get('maxcount', 1000)) except ValueError: maxcount = 1000 return maxage, maxcount
def build_cflags_y(cflags_list): """ Build cflags-y additions from the @cflags_list. Note: the input sources should have their file extensions. """ return '\n'.join(['cflags-y += {0}'.format(cflag) for cflag in cflags_list])
def Cluster(sequence, partition_point): """Return a tuple (left, right) where partition_point is part of right.""" return (sequence[:partition_point], sequence[partition_point:])
def get_offer_type_enum(offer_type): """ """ if offer_type == "bogo": return 0 elif offer_type == "informational": return 1 elif offer_type == "discount": return 2 else: return 3
def distance(x0, y0, x1, y1): """distance between points""" dx = x1 - x0 dy = y1 - y0 dist = ((dx ** 2) + (dy ** 2)) ** 0.5 return dist
def check_history(model, history): """Check if model was trained with different history to avoid key errors.""" if not model.get('~'*history): history = len([c for c in model if c.startswith('~') and c.endswith('~')][0]) print('#'* 57) print("# WARNING: the model was trained with history length:{0} #".format(history)) print("# Falling back to model history length. #") print('#', ' '*53, '#') print('#'*22, 'GENERATING!', '#'*22) return history
def parse_str(s: str): """ Parse entry of info file Parameters ---------- s : str Value Returns ------- obj Corresponding python type """ if s.isnumeric(): return int(s) elif set(s) - set('-.0123456789E') == set(): # Try is a workaround for the version string try: return float(s) except ValueError: return s elif set(s) - set('-.0123456789E,') == set(): return list(map(float, s.split(','))) elif s == 'TRUE': return True elif s == 'FALSE': return False else: return s
def ultimate_answer(question): """Provides an answer to the ultimate question. Returns '42' if the question is 'What is the meaning of Life, The Universe, Everything?' otherwise returns 'That is not much of a question' args: question (str): The question to be answered. returns: str """ if question == "What is the meaning of Life, The Universe, Everything?": answer = "42" else: answer = "That is not much of a question" return answer
def max_integer(my_list=[]): """ finds the largest integer of a list """ if len(my_list) == 0: return (None) my_list.sort() return (my_list[-1])
def clean_onnx_name(name: str) -> str: """Modifies a onnx name that is potentially invalid in dace to make it valid""" return "ONNX_" + name.replace(".", "DOT").replace(":", "COLON").replace( "/", "SLASH").replace("-", "DASH")
def pool_output_length(input_length, pool_size, stride, pad, ignore_border): """ Compute the output length of a pooling operator along a single dimension. Parameters ---------- input_length : integer The length of the input in the pooling dimension pool_size : integer The length of the pooling region stride : integer The stride between successive pooling regions pad : integer The number of elements to be added to the input on each side. ignore_border: bool If ``True``, partial pooling regions will be ignored. Must be ``True`` if ``pad != 0``. Returns ------- output_length * None if either input is None. * Computed length of the pooling operator otherwise. Notes ----- When ``ignore_border == True``, this is given by the number of full pooling regions that fit in the padded input length, divided by the stride (rounding down). If ``ignore_border == False``, a single partial pooling region is appended if at least one input element would be left uncovered otherwise. """ if input_length is None or pool_size is None: return None if ignore_border: output_length = input_length + 2 * pad - pool_size + 1 output_length = (output_length + stride - 1) // stride # output length calculation taken from: # https://github.com/Theano/Theano/blob/master/theano/tensor/signal/downsample.py else: assert pad == 0 if stride >= pool_size: output_length = (input_length + stride - 1) // stride else: output_length = max( 0, (input_length - pool_size + stride - 1) // stride) + 1 return output_length
def is_standard_key(key): """ Function to determine whether the supplied key is one of the common/standard keys.\n :param key: key to check :return: True if standard key otherwise False """ if key.find("concept") != -1 or key.find("lifecycle") != -1 or key.find("org") != -1 or key.find( "time") != -1 or key.find("semantic") != -1: return True else: return False
def docstring_to_tooltip(docstring): """ Returns tooltip friendly version of the docstring :param docstring: a docstring :return: the docstring content """ docstring = docstring or '' if not docstring.strip().splitlines(): return '' return docstring.strip().splitlines()[0]
def int_to_binary(d, length=8): """ Binarize an integer d to a list of 0 and 1. Length of list is fixed by `length` """ d_bin = '{0:b}'.format(d) d_bin = (length - len(d_bin)) * '0' + d_bin # Fill in with 0 return [int(i) for i in d_bin]
def diff_dict(old, new): """ >>> diff_dict({'del': '0', 'change': '0', 'stay': '0'}, {'change': '1', 'stay': '0', 'add': '0'}) {'added': ['add'], 'removed': ['del'], 'changed': ['change']} """ all_keys = set(old) | set(new) diff = {'added': [], 'removed': [], 'changed': []} for k in all_keys: lv = old.get(k) rv = new.get(k) if not lv: diff['added'].append(k) elif not rv: diff['removed'].append(k) elif lv != rv: diff['changed'].append(k) return diff
def rollout_rewards_combinator(rollout_rewards, new_rewards): """ Combine rewards used in deploy_workers in rl_oracle.py. """ new_rollout_rewards = [] for i, j in zip(rollout_rewards, new_rewards): new_rollout_rewards.append(i + j) return new_rollout_rewards
def match(first_list, second_list, attribute_name): """Compares two lists and returns true if in both there is at least one element which has the same value for the attribute 'attribute_name' """ for i in first_list: for j in second_list: if i[attribute_name] == j[attribute_name]: return True return False
def create_initial_state(dihedrals, grid_spacing, elements, init_coords, dihedral_ranges=None, energy_decrease_thresh=None, energy_upper_limit=None): """Create the initial input dictionary for torsiondrive API Parameters ---------- dihedrals : List of tuples A list of the dihedrals to scan over. grid_spacing : List of int The grid seperation for each dihedral angle elements : List of strings Symbols for all elements in the molecule init_coords : List of (N, 3) or (N*3) arrays The initial coordinates in bohr dihedral_ranges: (Optional) List of [low, high] pairs consistent with launch.py, e.g. [[-120, 120], [-90, 150]] energy_decrease_thresh: (Optional) Float Threshold of an energy decrease to triggle activate new grid point. Default is 1e-5 energy_upper_limit: (Optional) Float Upper limit of energy relative to current global minimum to spawn new optimization tasks. Returns ------- dict A representation of the torsiondrive state as JSON Examples -------- dihedrals = [[0,1,2,3], [1,2,3,4]] grid_spacing = [30, 30] elements = ["H", "C", "C", "O", "H"] init_coords = [[0.1, 0.2, 0.1], [1.1, 1.2, 1.1], [2.4, 2.2, 2.4], [3.1, 3.2, 3.1], [4.1, 3.8, 4.2]] dihedral_ranges = [[-120, 120], [-90, 150]] energy_decrease_thresh = 0.00001 energy_upper_limit = 0.05 Notes ----- The extra_constraints feature is implemented in the server. See tests/test_stack_api.py for example. """ initial_state = { 'dihedrals': dihedrals, 'grid_spacing': grid_spacing, 'elements': elements, 'init_coords': init_coords, 'grid_status': {}, } if dihedral_ranges is not None: initial_state['dihedral_ranges'] = dihedral_ranges if energy_decrease_thresh is not None: initial_state['energy_decrease_thresh'] = energy_decrease_thresh if energy_upper_limit is not None: initial_state['energy_upper_limit'] = energy_upper_limit return initial_state
def generate_traefik_path_labels(url_path, segment=None, priority=2, redirect=True): """Generates a traefik path url with necessary redirects :url_path: path that should be used for the site :segment: Optional traefik segment when using multiple rules :priority: Priority of frontend rule :redirect: Redirect to path with trailing slash :returns: list of labels for traefik """ label_list = [] # check segment segment = f'.{segment}' if segment is not None else '' # fill list label_list.append(f'traefik{segment}.frontend.priority={priority}') if redirect: label_list.append( f'traefik{segment}.frontend.redirect.regex=^(.*)/{url_path}$$') label_list.append( f'traefik{segment}.frontend.redirect.replacement=$$1/{url_path}/') label_list.append( f'traefik{segment}.frontend.rule=PathPrefix:/{url_path};' f'ReplacePathRegex:^/{url_path}/(.*) /$$1') else: label_list.append( f'traefik{segment}.frontend.rule=PathPrefix:/{url_path}') return label_list
def feature_selection(all_features): """ Description: Function defining which features to use Input: all_features -> boolean telling us if we use all the features or only the important ones Return: A list of the features we keep """ if all_features: features = ['Age', 'HoursPerWeek', 'TotalHours', 'APM', 'SelectByHotkeys', 'AssignToHotkeys','UniqueHotkeys', 'MinimapAttacks', 'MinimapRightClicks', 'NumberOfPACs','GapBetweenPACs', 'ActionLatency', 'ActionsInPAC', 'TotalMapExplored', 'WorkersMade', 'UniqueUnitsMade', 'ComplexUnitsMade','ComplexAbilitiesUsed'] else: features = ['APM', 'SelectByHotkeys', 'AssignToHotkeys', 'ActionLatency', 'GapBetweenPACs'] return features
def parse_cooler_uri(s): """ Parse a Cooler URI string e.g. /path/to/mycoolers.cool::/path/to/cooler """ parts = s.split("::") if len(parts) == 1: file_path, group_path = parts[0], "/" elif len(parts) == 2: file_path, group_path = parts if not group_path.startswith("/"): group_path = "/" + group_path else: raise ValueError("Invalid Cooler URI string") return file_path, group_path
def all_neighbors(x,y,arr): """Returns all neighbors including diagonals""" neighbors = [] for i in [-1,0,1]: for j in [-1,0,1]: neighbors.append((x+i,y+j)) neighbors = [i for i in neighbors if i != (x,y)] return neighbors
def _dict_has_value(dct): """helper to check if the dict contains at least one valid value""" for val in dct.values(): if isinstance(val, str): if val.strip() != '': return True elif isinstance(val, list): if val: return True elif type(val) in (int, float, bool): return True elif isinstance(val, dict): return _dict_has_value(val) return False
def decode(chromosome): """ Takes each individual from the population and decodes their value. """ first_value = chromosome & 0xff second_value = (chromosome & 0xFF00) >> 8 third_value = (chromosome & 0xFF0000) >> 16 fourth_value = (chromosome & 0xFF000000) >> 24 decoded_value = first_value + second_value + third_value + fourth_value return decoded_value
def good_request(status: str): """ Check if request from NYT API was good """ return ('OK' == status)
def filter_file(single_file): """ Method used to filter out unwanted files """ if(single_file.endswith(".txt") or single_file.endswith(".py") or single_file.endswith(".java") or single_file.endswith(".s")): return single_file
def parse_text(data: list): """Remove newlines, HTML characters, and join lines that do not include headers """ data = [i.strip() for i in data] # Strip data = list(filter(None, data)) # Remove empty lines # Skip blank files if not data: return data # Add first header if none if '<B>' not in data[0]: data[0] = '<B>HEADER:</B> ' + data[0] # Join lines within header i = 1 while i < len(data): if '<B>' not in data[i]: data[i - 1:i + 1] = [' '.join(data[i - 1:i + 1])] else: i += 1 data = [item.replace('<B>', '').replace('</B>', '') for item in data] # Remove html tags return data
def diff_pf_potential(phi): """ Derivative of the phase field potential. """ return phi**3-phi
def _resolve_repository_template( template, abi = None, arch = None, system = None, tool = None, triple = None, vendor = None, version = None): """Render values into a repository template string Args: template (str): The template to use for rendering abi (str, optional): The host ABI arch (str, optional): The host CPU architecture system (str, optional): The host system name tool (str, optional): The tool to expect in the particular repository. Eg. `cargo`, `rustc`, `stdlib`. triple (str, optional): The host triple vendor (str, optional): The host vendor name version (str, optional): The Rust version used in the toolchain. Returns: string: The resolved template string based on the given parameters """ if abi: template = template.replace("{abi}", abi) if arch: template = template.replace("{arch}", arch) if system: template = template.replace("{system}", system) if tool: template = template.replace("{tool}", tool) if triple: template = template.replace("{triple}", triple) if vendor: template = template.replace("{vendor}", vendor) if version: template = template.replace("{version}", version) return template
def hex2rgb(hexstring, digits=2): """Converts a hexstring color to a rgb tuple. Example: #ff0000 -> (1.0, 0.0, 0.0) digits is an integer number telling how many characters should be interpreted for each component in the hexstring. """ if isinstance(hexstring, (tuple, list)): return hexstring top = float(int(digits * 'f', 16)) r = int(hexstring[1:digits+1], 16) g = int(hexstring[digits+1:digits*2+1], 16) b = int(hexstring[digits*2+1:digits*3+1], 16) return r / top, g / top, b / top
def MakeLong(high, low): """Pack high into the high word of a long and low into the low word""" # we need to AND each value with 0xFFFF to account for numbers # greater then normal WORD (short) size return ((high & 0xFFFF) << 16) | (low & 0xFFFF)
def getPointRange(iFace, dims): """Return the correct point range for face iFace on a block with dimensions given in dims""" il = dims[0] jl = dims[1] kl = dims[2] if iFace == 0: return [[1, il], [1, jl], [1, 1]] elif iFace == 1: return [[1, il], [1, jl], [kl, kl]] elif iFace == 2: return [[1, 1], [1, jl], [1, kl]] elif iFace == 3: return [[il, il], [1, jl], [1, kl]] elif iFace == 4: return [[1, il], [1, 1], [1, kl]] elif iFace == 5: return [[1, il], [jl, jl], [1, kl]]
def process_hierarchy(field, data): """Process dictionary hierarchy.""" field_arr = field.split(".") data_set = data for field in field_arr: data_set = data_set[field] return str(data_set)
def test_limit_points(sequence, max_number_of_lp): """ Return the number (color coded) of limit points in a sequence. Points within a distance epsilon are indistinguishable. """ if len(sequence) == 1: return 0 # undefined epsilon = 1e-10 try: for i in range(2, max_number_of_lp+2): if abs(sequence[-1]-sequence[-i]) < epsilon: return i-1 return 0 # undefined except (OverflowError, ValueError): return 0
def AND(A, B): """Returns events that are in A AND B.""" return A.intersection(B)
def murnaghan(V, E0, B0, B1, V0): """ From PRB 28,5480 (1983) """ return E0 + B0 * V / B1 * (((V0/V)**B1)/(B1-1)+1) - V0 * B0 / (B1-1)
def hex_to_rgb(hex): """ Convert hex color code to RGB """ code = hex.lstrip("#") return [int(code[i : i + 2], 16) for i in (0, 2, 4)]
def prunecomments(blocks): """Remove comments.""" i = 0 while i < len(blocks): b = blocks[i] if b[b'type'] == b'paragraph' and ( b[b'lines'][0].startswith(b'.. ') or b[b'lines'] == [b'..'] ): del blocks[i] if i < len(blocks) and blocks[i][b'type'] == b'margin': del blocks[i] else: i += 1 return blocks
def rc_to_xy(row, col, rows): """ Convert from (row, col) coordinates (eg: numpy array) to (x, y) coordinates (bottom left = 0,0) (x, y) convention * (0,0) in bottom left * x +ve to the right * y +ve up (row,col) convention: * (0,0) in top left * row +ve down * col +ve to the right Args: row (int): row coordinate to be converted col (int): col coordinate to be converted rows (int): Total number of rows Returns: tuple: (x, y) """ x = col y = rows - row - 1 return x, y
def lsb(x, n): """Return the n least significant bits of x. >>> lsb(13, 3) 5 """ return x & ((2 ** n) - 1)
def get_individual_positions(individuals): """Return a dictionary with individual positions Args: individuals(list): A list with vcf individuals in correct order Returns: ind_pos(dict): Map from ind_id -> index position """ ind_pos = {} if individuals: for i, ind in enumerate(individuals): ind_pos[ind] = i return ind_pos
def yp_processed_reviews(yelp_username): """ Raw form of reviews that contains ony status and reviews. File Type: CSV """ return '../data/processed/{}.csv'.format(yelp_username)
def isclassattr(a, cls): """ Test if an attribute is a class attribute. """ for c in cls.__mro__: if a in c.__dict__: return True return False
def calcular_costo_envio(kilometros): """ num -> float opera dos numeros para dar como resultado el costo de envio :param kilometros: se ingresan la cantidad de kilometros recorridos :return: el costo del envio >>> calcular_costo_envio(1) 115.0 >>> calcular_costo_envio(0) 0.0 """ if (kilometros < 0): return 'El numero de kilometros debe ser mayor a cero.' return float(kilometros * 115)
def italicize(s): """Given a string return the same string italicized (in wikitext).""" return "''{}''".format(s)
def double(_printer, ast): """Prints a double value.""" return f'{ast["val"]}.0' if isinstance(ast["val"], int) else f'{ast["val"]}'
def candidateKey(candidate): """Generates a comparison key for a candidate. Candidates are sorted by the number of dimensions (the highest, the better), then by average execution time of the biggest dimension (the lower the better)""" if candidate is None: return (float('inf'), float('inf')) numDimensions = len(candidate.metrics[0]) executionTime = candidate.metrics[0][2**(numDimensions-1)].mean() return (1/numDimensions, executionTime)
def _num_lines(label: str) -> int: """Return number of lines of text in label.""" return label.count("\n") + 1
def non_deleting_interleaving(o): """ no empty tuple element (ie. utilize commas maximally) PRO TIP: When running, listen to 'Charlemagne Palestine - Strumming Music' """ return all([len(x) > 0 for x in o])
def _mkx(i, steps, n): """ Generate list according to pattern of g0 and b0. """ x = [] for step in steps: x.extend(list(range(i, step + n, n))) i = step + (n - 1) return x
def is_empirical(var_type): """ Checks whether the variable type for the variable of interest is to be taken as a constant value or as numerical values. """ return var_type == "empirical"
def counting_sort_in_place(a): """ in-place counting sort http://p-nand-q.com/python/algorithms/sorting/countingsort.html """ counter = [0] * (max(a) + 1) for i in a: counter[i] += 1 pos = 0 for i, count in enumerate(counter): for _ in range(count): a[pos] = i pos += 1 return a
def int_or_str(text): """Helper function for argument parsing.""" try: return int(text) except ValueError: return text
def surface_zeta_format_to_texture_format(fmt, swizzled, is_float): """Convert nv2a zeta format to the equivalent Texture format.""" if fmt == 0x1: # Z16 if is_float: return 0x2D if swizzled else 0x31 return 0x2C if swizzled else 0x30 if fmt == 0x2: # Z24S8 if is_float: return 0x2B if swizzled else 0x2F return 0x2A if swizzled else 0x2E raise Exception( "Unknown zeta fmt %d (0x%X) %s %s" % ( fmt, fmt, "float" if is_float else "fixed", "swizzled" if swizzled else "unswizzled", ) )
def merge_dict_sum(dict1, dict2): """ Merge two dictionaries and add values of common keys. Values of the input dicts can be any addable objects, like numeric, str, list. """ dict3 = {**dict1, **dict2} for key, value in dict3.items(): if key in dict1 and key in dict2: dict3[key] = value + dict1[key] return dict3
def translate(text, conversion_dict, before=None): """ Fix wrong words """ if not text: return text before = before or str tmp = before(text) for key, value in conversion_dict.items(): tmp = tmp.replace(key, value) return tmp
def strip_ascii(content_data): """ Strips out non-printable ASCII chars from strings, leaves CR/LF/Tab. Args: content_data: b"\x01He\x05\xFFllo" Returns: stripped_message: "Hello" """ stripped_message = str() if type(content_data) == bytes: for entry in content_data: if (int(entry) == 9 or int(entry) == 10 or int(entry) == 13) or (32 <= int(entry) <= 126): stripped_message += chr(int(entry)) elif type(content_data) == str: for entry in content_data: if (ord(entry) == 9 or ord(entry) == 10 or ord(entry) == 13) or (32 <= ord(entry) <= 126): stripped_message += entry return stripped_message.replace("\x00", "")
def lcmt_check(grade_v, grade_i, grade_j): """ A check used in lcmt table generation """ return grade_v == (grade_j - grade_i)
def container_code_path(spec): """ Returns the path inside the docker container that a spec (for an app or lib) says it wants to live at """ return spec['mount']
def skip_waiting(scopeURL: str) -> dict: """ Parameters ---------- scopeURL: str """ return {"method": "ServiceWorker.skipWaiting", "params": {"scopeURL": scopeURL}}
def a_second_has_elapsed(current_time: float, start_time: float) -> bool: """ Given two timestamps (unix epochs), a starting time and a current time, checks if the current time is at least a second later than the starting time """ return current_time - start_time >= 1
def gen_all_holds(hand): """ Generate all possible choices of dice from hand to hold. hand: full yahtzee hand Returns a set of tuples, where each tuple is dice to hold """ if (len(hand) == 0): return set([()]) holds = set([()]) for die in hand: for element in holds.copy(): new_list = list(element) new_list.append(die) holds.add(tuple(new_list)) return holds
def decode_domain_def(domains, merge=True, return_string=False): """Return a tuple of tuples of strings, preserving letter numbering (e.g. 10B).""" if not domains: return None, None if domains[-1] == ",": domains = domains[:-1] x = domains if return_string: domain_fragments = [[r.strip() for r in ro.split(":")] for ro in x.split(",")] else: domain_fragments = [[int(r.strip()) for r in ro.split(":")] for ro in x.split(",")] domain_merged = [domain_fragments[0][0], domain_fragments[-1][-1]] if merge: return domain_merged else: return domain_fragments
def match_cond(target, cond_key, cond_value, force=True, opposite=False): """ params: - target: the source data want to check. - cond_key: the attr key of condition. - cond_value: the value of condition. if the cond_value is a list, any item matched will make output matched. - opposite: reverse check result. - force: must have the value or not. """ def _dotted_get(key, obj): if not isinstance(obj, dict): return None elif '.' not in key: return obj.get(key) else: key_pairs = key.split('.', 1) obj = obj.get(key_pairs[0]) return _dotted_get(key_pairs[1], obj) def _dotted_in(key, obj): if not isinstance(obj, dict): return False elif '.' not in key: return key in obj else: key_pairs = key.split('.', 1) obj = obj.get(key_pairs[0]) return _dotted_in(key_pairs[1], obj) if cond_value == '' and not force: return _dotted_in(cond_key, target) != opposite elif cond_value is None and not force: # if cond_value is None will reverse the opposite, # then for the macthed opposite must reverse again. so... # also supported if the target value really is None. return _dotted_in(cond_key, target) == opposite elif isinstance(cond_value, bool) and not force: return _dotted_in(cond_key, target) != opposite elif not _dotted_in(cond_key, target): return False matched = False target_value = _dotted_get(cond_key, target) if isinstance(cond_value, list): for c_val in cond_value: matched = match_cond(target, cond_key, c_val, force=True) if matched: break elif isinstance(cond_value, bool): target_bool = isinstance(target_value, bool) matched = cond_value == target_value and target_bool else: if isinstance(target_value, list): matched = cond_value in target_value else: matched = cond_value == target_value return matched != opposite
def detect_anagrams(word, candidates): """ Return all correct anagrams of a given word from a list of words. Anagrams are case insensitive, and differ from the original word. """ anagrams = [] for candidate in candidates: c = candidate.lower() w = word.lower() if sorted(c) == sorted(w) and c != w: # we used case insensitive comparison, but the original # candidate is appended to the anagram list anagrams.append(candidate) return anagrams