content
stringlengths
42
6.51k
def binary_search(n,arr,ele): """ Function to perform iterative binary search params: n : Size of input array arr : input array ele : element to be searched in array returns: index : index of element if found else -1. """ left = 0 right = n-1 while left<=right: mid = left + int((right-left)/2) if arr[mid] == ele: return mid elif ele > arr[mid]: left = mid+1 else: right = mid-1 return -1
def mnormalize(matrix): """Scale a matrix according to the value in the center.""" width = len(matrix[0]) height = len(matrix) factor = 1.0 / matrix[int(height / 2)][int(width / 2)] if 1.0 == factor: return matrix for i in range(height): for j in range(width): matrix[i][j] *= factor return matrix
def PickHistoryName(args): """Returns the results history name to use to look up a history ID. The history ID corresponds to a history name. If the user provides their own history name, we use that to look up the history ID; If not, but the user provides an app-package name, we use the app-package name with ' (gcloud)' appended as the history name. Otherwise, we punt and let the Testing service determine the appropriate history ID to publish to. Args: args: an argparse namespace. All the arguments that were provided to the command invocation (i.e. group and command arguments combined). Returns: Either a string containing a history name derived from user-supplied data, or None if we lack the required information. """ if args.results_history_name: return args.results_history_name if args.app_package: return args.app_package + ' (gcloud)' return None
def main(args=None): """Console script for chutie.""" # click.echo("See the 'screenshots' command.") return 0
def linear_search(a, v): """Linear search algorithm. If v exist in a, returns index. Returns None if not found.""" for index, e in enumerate(a): if e == v: return index return None
def rgb_to_brightness(r, g, b, grayscale=False): """ Calc a brightness factor according to rgb color """ if grayscale: return 0.2126*r + 0.7152*g + 0.0722*b else: return 0.267*r + 0.642*g + 0.091*b
def parse_name(text): """Split an arbitrary (maybe empty) word from the beginning of a string.""" lth = 0 while text[lth] not in ' ,*%();': lth += 1 return text[:lth], text[lth:]
def poly5(x, a5, a4, a3, a2, a1, a0, export=False): """Polynom 5th degree for fitting. :param x: parameter :param a5: coeff :param a4: coeff :param a3: coeff :param a2: coeff :param a1: coeff :param a0: coeff :param export: enable text output of function :returns: function -- polynomial 5th degree """ if export == 'Mathematica': return f'((((({a5}*{x} + {a4})*{x} + {a3})*{x} + {a2})*{x} + {a1})*{x} + {a0})' else: return (((((a5*x + a4)*x + a3)*x + a2)*x + a1)*x + a0)
def make_fully_qualified_url(url): """ Ensure url is qualified """ if url.startswith("//"): return "https:" + url if url.startswith("/"): return "https://en.wikipedia.org" + url assert url.startswith("http"), "Bad URL (relative to unknown location): " + url return url
def xml_escape(s): """Escape XML meta characters '<' and '&'.""" answer = s.replace("<", "&lt;") answer = answer.replace("&", "&amp;") return answer
def quadraticProbe(hk, size, i): """Default quadratic probe using c1=1/2 and c2=1/2.""" return int(hk + 0.5 + i*i*0.5) % size
def summation(n, term): """Sum the first n terms of a sequence. >>> summation(5, double) 30 >>> summation(5, square) 55 >>> summation(5, cube) 225 """ total = 0 k = 1 while k <= n: total = total + term(k) # <-- FIX THIS LINE! k += 1 return total
def func_xy_kwargs(x, y, **kwargs): """func. Parameters ---------- x, y: float kwargs: dict Returns ------- x, y: float kwargs: dict """ return x, y, None, None, None, None, None, kwargs
def find_substring(s, indicator, terminator): """ Given a string, returns the substring strictly between the indicator and terminator strings, if they exist. Otherwise returns None. It is possible that an empty string is returned if the indicator and terminator are adjacent. """ i = s.find(indicator) if i == -1: return None j = s.find(terminator, i + len(indicator)) if j == -1: return None return s[i + len(indicator) : j]
def distance_point_segment(ps1, ps2, external_p): """Returns the distance between segment and point. Don't ask why.""" x3, y3 = external_p x1, y1 = ps1 x2, y2 = ps2 px = x2-x1 py = y2-y1 norm = px*px + py*py u = ((x3 - x1) * px + (y3 - y1) * py) / float(norm) if u > 1: u = 1 elif u < 0: u = 0 x = x1 + u * px y = y1 + u * py dx = x - x3 dy = y - y3 dist = (dx*dx + dy*dy)**.5 return dist
def similarity( M_c, X_L_list, X_D_list, given_row_id, target_row_id, target_column=None): """Returns the similarity of the given row to the target row, averaged over all the column indexes given by col_idxs. Similarity is defined as the proportion of times that two cells are in the same view and category. """ score = 0.0 # Set col_idxs: defaults to all columns. if target_column: if type(target_column) == str: col_idxs = [M_c['name_to_idx'][target_column]] elif type(target_column) == list: col_idxs = target_column else: col_idxs = [target_column] else: col_idxs = M_c['idx_to_name'].keys() col_idxs = [int(col_idx) for col_idx in col_idxs] ## Iterate over all latent states. for X_L, X_D in zip(X_L_list, X_D_list): for col_idx in col_idxs: view_idx = X_L['column_partition']['assignments'][col_idx] if X_D[view_idx][given_row_id] == X_D[view_idx][target_row_id]: score += 1.0 return score / (len(X_L_list)*len(col_idxs))
def remove_keys(dct, keys=[]): """Remove keys from a dict.""" return {key: val for key, val in dct.items() if key not in keys}
def generate_model_masks( depth, mask = None, masked_layer_indices = None): """Creates empty masks for this model, or initializes with existing mask. Args: depth: Number of layers in the model. mask: Existing model mask for layers in this model, if not given, all module masks are initialized to None. masked_layer_indices: The layer indices of layers in model to be masked, or all if None. Returns: A model mask, with None where no mask is given for a model layer, or that specific layer is indicated as not to be masked by the masked_layer_indices parameter. """ if depth <= 0: raise ValueError(f'Invalid model depth: {depth}') if mask is None: mask = {f'MaskedModule_{i}': None for i in range(depth)} # Have to explicitly check for None to differentiate from empty array. if masked_layer_indices is not None: # Check none of the indices are outside of model's layer bounds. if any(i < 0 or i >= depth for i in masked_layer_indices): raise ValueError( f'Invalid indices for given depth ({depth}): {masked_layer_indices}') mask = { f'MaskedModule_{i}': mask[f'MaskedModule_{i}'] for i in masked_layer_indices } return mask
def wage_feature_eng(wage): """ Feature engineering by making the quantitative type data in WAGE column into categorical data """ if wage <= 50000: return "VERY LOW" elif wage in range(50000,75000): return "LOW" elif wage in range(75000,100000): return "AVERAGE" elif wage in range(100000,150000): return "HIGH" elif wage >= 150000: return "VERY HIGH"
def event_type(play_description): """ Returns the event type (ex: a SHOT or a GOAL...etc) given the event description :param play_description: description of play :return: event """ events = {'GOAL SCORED': 'GOAL', 'SHOT ON GOAL': 'SHOT', 'SHOT MISSED': 'MISS', 'SHOT BLOCKED': 'BLOCK', 'PENALTY': 'PENL', 'FACEOFF': 'FAC', 'HIT': 'HIT', 'TAKEAWAY': 'TAKE', 'GIVEAWAY': 'GIVE'} event = [events[e] for e in events.keys() if e in play_description] return event[0] if event else None
def convert_neg_indices(indices, ndim): """converts negative values in tuple/list indices""" def canonicalizer(ax): return ax + ndim if ax < 0 else ax indices = tuple([canonicalizer(axis) for axis in indices]) return indices
def min_n_discretes_acyclic_graph(n_global_discretes): """The minimal system size RootSolution/Unfold can handle with acyclic_graphs. Args: n_global_discretes: Number of global discretes Returns: The minimum number of discretes needed. """ term_width = 2 # 2-body building_blocks first_limit = n_global_discretes + 2 * ((term_width - 1) + 7) if term_width % 2 == 0: first_limit += 1 second_limit = 7 + 2 * n_global_discretes + 2 * (term_width - 1) if (term_width + n_global_discretes) % 2 == 0: # Both are odd or both are even. second_limit += 1 return max(first_limit, second_limit)
def determine_nohit_score(cons, invert): """ Determine the value in the matrix assigned to nohit given SeqFindr options :param cons: whether the Seqfindr run is using mapping consensus data or not :param invert: whether the Seqfindr run is inverting (missing hits to be shown as black bars. :type cons: None of boolean :type cons: boolean :returns: the value defined as no hit in the results matrix """ if cons is None: nohit = 0.5 else: nohit = 1.0 if invert: nohit = nohit*-1.0 return nohit
def similar_mers(desiredcomplementset, revcomplementset): """2013-12-04 14:21 WEV This should return a list of Nmer sequences which match up DesiredCompliment <- should be sequences which are oriented the way That the parts are oriented RevCompliment <- This is the revComplement - We are looking at binding spot """ # First chance to use set functions! return desiredcomplementset.intersection(revcomplementset)
def key_(arg): """ get an argument's destiation key """ _, kwargs = arg return kwargs['dest']
def normalize_spaces(s): """ Replaces all sequences of whitespace characters with a single space """ if not s: return '' return ' '.join(s.split())
def row_sum_odd_numbers(n): """function takes in number and returns sum of numbers in that row.""" calculate_index = sum([num for num in range(1, n)]) odd_numbers = [] m = 1 while len(odd_numbers) != calculate_index + n: odd_numbers.append(m) m += 2 numbers = [] for i in range(calculate_index, calculate_index + n): numbers.append(odd_numbers[i]) return sum(numbers)
def _right_child(node): """ Args: node: index of a binary tree node Returns: index of node's right child """ return 2 * node + 2
def fibonacci(k: int) -> int: """Finds fibonacci number in index k. Parameters ---------- k : Index of fibonacci. Returns ------- int Fibonacci number in position k. >>> fibonacci(0) 0 >>> fibonacci(2) 1 >>> fibonacci(5) 5 >>> fibonacci(15) 610 >>> fibonacci('a') Traceback (most recent call last): TypeError: k must be an integer. >>> fibonacci(-5) Traceback (most recent call last): ValueError: k integer must be greater or equal to zero. """ if not isinstance(k, int): raise TypeError("k must be an integer.") if k < 0: raise ValueError("k integer must be greater or equal to zero.") if k == 0: return 0 elif k == 1: return 1 else: return fibonacci(k - 1) + fibonacci(k - 2)
def dasherize(word): """Replace underscores with dashes in the string. Example:: >>> dasherize("foo_bar") "foo-bar" Args: word (str): input word Returns: input word with underscores replaced by dashes """ return word.replace('_', '-')
def is_id(argument: str): """Check if argument is #. Parameters ---------- argument: str text to parse Returns ---------- str the bare id """ status = True for x in argument: try: _ = int(x) except: status = False return False return True
def aggregate_str_content(array_of_elements): """ Takes an array of DOM elements with text and merges their text content """ u = "" for h in array_of_elements: u+=h.text return u
def has_extension(file_path: str, *args: str) -> bool: """ Checks to see if the given file path ends with any of the specified file extensions. If a file extension does not begin with a '.' it will be added automatically :param file_path: The path on which the extensions will be tested for a match :param args: One or more extensions to test for a match with the file_path argument :return: Whether or not the file_path argument ended with one or more of the specified extensions """ def add_dot(extension): return ( extension if extension.startswith('.') else '.{}'.format(extension) ) return any([ file_path.endswith(add_dot(extension)) for extension in args ])
def get_text(score): """Returns a textual representation of the likelihood that a domain is parked, based on the score. """ if score == 0: return 'Unlikely' elif score <= 0.3: return 'Possibly' elif score <= 0.6: return 'Fairly likely' elif score <= 0.85: return 'Quite likely' else: return 'Highly likely'
def merge_rings(rings): """ Merge rings at the endpoints. """ endpoints = {} for ring in rings: if len(ring.refs) < 2: continue left = ring.refs[0] right = ring.refs[-1] orig_ring = None if left in endpoints: orig_ring = endpoints.pop(left) if left == orig_ring.refs[-1]: orig_ring.refs = orig_ring.refs + ring.refs[1:] orig_ring.coords = orig_ring.coords + ring.coords[1:] else: orig_ring.refs = orig_ring.refs[::-1] + ring.refs[1:] orig_ring.coords = orig_ring.coords[::-1] + ring.coords[1:] orig_ring.ways.extend(ring.ways) orig_ring.tags.update(ring.tags) if right in endpoints and endpoints[right] is not orig_ring: # close gap ring = endpoints.pop(right) if right == ring.refs[0]: orig_ring.refs = orig_ring.refs + ring.refs[1:] orig_ring.coords = orig_ring.coords + ring.coords[1:] else: orig_ring.refs = orig_ring.refs[:-1] + ring.refs[::-1] orig_ring.coords = orig_ring.coords[:-1] + ring.coords[::-1] orig_ring.ways.extend(ring.ways) orig_ring.tags.update(ring.tags) right = orig_ring.refs[-1] endpoints[right] = orig_ring else: endpoints[right] = orig_ring elif right in endpoints: orig_ring = endpoints.pop(right) if right == orig_ring.refs[0]: orig_ring.refs = ring.refs[:-1] + orig_ring.refs orig_ring.coords = ring.coords[:-1] + orig_ring.coords else: orig_ring.refs = orig_ring.refs[:-1] + ring.refs[::-1] orig_ring.coords = orig_ring.coords[:-1] + ring.coords[::-1] orig_ring.ways.extend(ring.ways) orig_ring.tags.update(ring.tags) endpoints[left] = orig_ring else: endpoints[left] = ring endpoints[right] = ring return list(set(endpoints.values()))
def IsUnderAlphabet(s, alphabet): """ ################################################################# Judge the string is within the scope of the alphabet or not. :param s: The string. :param alphabet: alphabet. Return True or the error character. ################################################################# """ for e in s: if e not in alphabet: return e return True
def parse_lanes(lane_expr): """ Break up a 'lane expression' into a list of lane numbers A 'lane expression' is a string consisting of: - a single integer (e.g. 1), or - a list of comma-separated integers (e.g. 1,2,3), or - a range (e.g. 1-4), or - a combination of lists and ranges (e.g. 1,3,5-8). Arguments: lane_expr (str): a lane expression Returns: List: list of integers representing lane numbers. """ # Extract lane numbers fields = lane_expr.split(',') lanes = [] for field in fields: # Check for ranges i.e. 1-3 try: i = field.index('-') l1 = int(field[:i]) l2 = int(field[i+1:]) for i in range(l1,l2+1): lanes.append(i) except ValueError: # Not a range lanes.append(int(field)) # Sort into order lanes.sort() return lanes
def sweep_div_toggle_style(mode_val): """toggle the layout for sweep""" if mode_val == 'single': return {'display': 'none'} else: return { 'display': 'flex', 'flex-direction': 'column', 'alignItems': 'center' }
def parse_layers_string(layers_string): """Convert a layer size string (e.g., `128_64_32`) to a list of integers.""" if not layers_string: return () num_hidden = layers_string.split('_') num_hidden = [int(num) for num in num_hidden] return num_hidden
def get_dict_values(dicts, keys, return_dict=False): """Get values from `dicts` specified by `keys`. When `return_dict` is True, return values are in dictionary format. Parameters ---------- dicts : dict keys : list return_dict : bool Returns ------- dict or list Examples -------- >>> get_dict_values({"a":1,"b":2,"c":3}, ["b"]) [2] >>> get_dict_values({"a":1,"b":2,"c":3}, ["b", "d"], True) {'b': 2} """ new_dicts = dict((key, dicts[key]) for key in keys if key in list(dicts.keys())) if return_dict is False: return list(new_dicts.values()) return new_dicts
def cxSet(ind1, ind2): """ Apply a crossover operation on input sets. The first child is the intersection of the two sets, the second child is the difference of the two sets. Parameters ---------- ind1: Set Parent 1. ind2: Set Parent 1 Returns ------- :tuple :[0]: Set Child 1. :[1]: Set Child 2. """ temp = set(ind1) # Used in order to keep type ind1 &= ind2 # Intersection (inplace) ind2 ^= temp # Symmetric Difference (inplace) return ind1, ind2
def clean_unsheltered(battlefield: str) -> str: """ Clean letters outside the shelter :param battlefield: :return: """ result = '' temp = battlefield.split('[') for char in temp: if char.count(']') == 0: c = ''.join(k for k in char if not k.isalpha()) result += c elif len(char) == char.count('#'): result += char else: sharp = char.count('#') char = char[0:char.index(']') + 1] result += '[' + char + ('#' * sharp) return result
def _worst_size(str_len): """ Given a string length, what's the worst size that we should grow to """ if str_len == 0: return 0 elif str_len == 1: return 2 elif str_len % 255 in (0, 1): return (str_len / 255) * 2 + str_len + (str_len % 255) else: return ((str_len / 255) + 1) * 2 + str_len
def get_human_number(num): """Get Human Readable Format of the number.""" if num < 1000: return num magnitude = 0 while abs(num) >= 1000: magnitude += 1 num /= 1000.0 # add more suffixes if you need them return '%.2f%s' % (num, ['', 'K', 'M', 'G', 'T', 'P'][magnitude])
def _check_data(list_data: list) -> list: """ Checking test data format. :param list_data: :return: """ if isinstance(list_data, list) is False: raise TypeError("The data format is not `list`.") if len(list_data) == 0: raise ValueError("The data format cannot be `[]`.") if isinstance(list_data[0], dict): test_data = [] for data in list_data: line = [] for d in data.values(): line.append(d) test_data.append(line) return test_data else: return list_data
def space_pad(instring, minlength): """ Pad a string with spaces until it's the minimum length. :param instring: String to pad. :type instring: str :param minlength: Pad while len(instring) < minlength. :type minlength: int """ while len(instring) < minlength: instring += " " return instring
def check_args(args: list) -> bool: """ The arguments passed to crapgrep.py """ if len(args) < 2 or args[0] == '--help': return False return True
def parse_range_specification(spec): """Parses a range specification used as arguments for some options in ``qplot``. Range specifications contain two numbers separated by a colon (``:``). Either of the numbers may be replaced by an underscore (``_``) or an empty string meaning 'automatic'.""" return [ None if value == "_" or value == "" else float(value) for value in spec.split(":", 1) ]
def group_consecutives(vals, step=1): """Return list of consecutive lists of numbers from vals (number list).""" len_limit = 32 run = [] result = [run] expect = None for v in vals: if (v == expect) or (expect is None): run.append(v) else: run = [v] result.append(run) expect = v + step return result
def resource_type_from_id(context, resource_id): """Get resource type by ID Returns a string representation of the Amazon resource type, if known. Returns None on failure. :param context: context under which the method is called :param resource_id: resource_id to evaluate """ known_types = { 'i': 'instance', 'r': 'reservation', 'vol': 'volume', 'snap': 'snapshot', 'ami': 'image', 'aki': 'image', 'ari': 'image' } type_marker = resource_id.split('-')[0] return known_types.get(type_marker)
def snitch_contained_at_end(metadata, three_class=False): """Return 1 if snitch is contained at the end.""" ever_contained = False res = None for _, movements in metadata['movements'].items(): contain_start = None for movement in movements: if movement[0] == '_contain' and movement[1] == 'Spl_0': # Should not be containing anything already assert contain_start is None contain_start = True ever_contained = True elif contain_start is not None and movement[0] == '_pick_place': assert movement[2] > contain_start contain_start = None # Means this object never "uncontained" the snitch if contain_start is not None: res = 'At end' break if res is None: if ever_contained: res = 'In between' else: res = 'Never' if three_class: return res else: return 'Contained' if res == 'At end' else 'Open'
def __isIntType__(obj): """ Returns true if the obj is an integer """ return isinstance(obj, int)
def find_prev_month(year, month): """Find CENTURY's representation of the month previous to year, month.""" if month == 1: prev_month = 12 year = year - 1 else: prev_month = month - 1 prev_date = year + float('%.2f' % (prev_month / 12.)) return prev_date
def splitIndent(text): """ Return tuple (ind, t) where ind is a string of the indentation characters (normally spaces) and t is text without the indentation. """ pl = len(text) textOnly = text.lstrip() return (text[:pl-len(textOnly)], textOnly)
def _seconds_and_microseconds(timestamp): """ Split a floating point timestamp into an integer number of seconds since the epoch, and an integer number of microseconds (having rounded to the nearest microsecond). If `_seconds_and_microseconds(x) = (y, z)` then the following holds (up to the error introduced by floating point operations): * `x = y + z / 1_000_000.` * `0 <= z < 1_000_000.` """ if isinstance(timestamp, int): return (timestamp, 0) else: timestamp_us = int(round(timestamp * 1e6)) return divmod(timestamp_us, 1000000)
def get_attr(obj, attr, default=None): """Recursive get object's attribute. May use dot notation. >>> class C(object): pass >>> a = C() >>> a.b = C() >>> a.b.c = 4 >>> get_attr(a, 'b.c') 4 >>> get_attr(a, 'b.c.y', None) >>> get_attr(a, 'b.c.y', 1) 1 """ if '.' not in attr: ret = getattr(obj, attr, default) else: L = attr.split('.') ret = get_attr(getattr(obj, L[0], default), '.'.join(L[1:]), default) if isinstance(ret, BaseException): raise ret return ret
def net_shortwave_radiation_daily(rs, albedo): """ :param rs: daily shortwave radiation [MJ m-2 day-1] :param albedo: reflection coefficient (0 <= albedo <= 1), which is 0.23 for the hypothetical grass reference crop [-] :return: daily net shortwave radiation reaching the earth [MJ m-2 day-1] """ return (1.0 - albedo) * rs
def factors_list(n): """Return a list containing all the numbers that divide `n` evenly, except for the number itself. Make sure the list is in ascending order. >>> factors_list(6) [1, 2, 3] >>> factors_list(8) [1, 2, 4] >>> factors_list(28) [1, 2, 4, 7, 14] """ all_factors = [] "*** YOUR CODE HERE ***" i = 1 while i <= n // 2: if n % i == 0: all_factors += [i] i += 1 return all_factors
def unordered_list(value): """ Recursively takes a self-nested list and returns an HTML unordered list -- WITHOUT opening and closing <ul> tags. The list is assumed to be in the proper format. For example, if ``var`` contains ``['States', [['Kansas', [['Lawrence', []], ['Topeka', []]]], ['Illinois', []]]]``, then ``{{ var|unordered_list }}`` would return:: <li>States <ul> <li>Kansas <ul> <li>Lawrence</li> <li>Topeka</li> </ul> </li> <li>Illinois</li> </ul> </li> """ def _helper(value, tabs): indent = '\t' * tabs if value[1]: return '%s<li>%s\n%s<ul>\n%s\n%s</ul>\n%s</li>' % (indent, value[0], indent, '\n'.join([_helper(v, tabs+1) for v in value[1]]), indent, indent) else: return '%s<li>%s</li>' % (indent, value[0]) return _helper(value, 1)
def get_default_span_name(method): """Default implementation for name_callback, returns HTTP {method_name}.""" return "HTTP {}".format(method).strip()
def unscale_data(data, min_val=0, max_val=255): """ Scale data ranging from -1 to 1 back to its original range. Args: data: min_val: max_val: Returns: """ unscaled_data = (data + 1) / 2 * (max_val - min_val) + min_val return unscaled_data
def important_words(words): """Filters a list of words to those are are valuable. Currently only makes sure that words are at least three characters. >>> w = ['hello', 'world', 'the', 'a', 'an'] >>> important_words(w) ['hello', 'world', 'the'] """ return [x for x in words if len(x) >= 3]
def load_spectrum_settings(settings_dict): """Set missing parameters to their defaults.""" settings = settings_dict.copy() if "feature" not in settings: settings["feature"] = "Stft" if "fft_sample_rate" not in settings: settings["fft_sample_rate"] = 44100 if "stft_window_length" not in settings: settings["stft_window_length"] = 1024 if "stft_hop_length" not in settings: settings["stft_hop_length"] = settings["stft_window_length"] // 2 if "frequency_bins" not in settings: settings["frequency_bins"] = 60 if settings["feature"] == "Cqt" and "cqt_min_frequency" not in settings: settings["cqt_min_frequency"] = "C1" if settings["feature"] == "Mfcc" and "mfc_coefficients" not in settings: settings["mfc_coefficients"] = 13 return settings
def gen_h_file(file_list): """ generate the c header file for audio tone """ h_file = '' h_file += '#ifndef __AUDIO_TONEURI_H__\r\n#define __AUDIO_TONEURI_H__\r\n\r\n' h_file += 'extern const char* tone_uri[];\r\n\r\n' h_file += 'typedef enum {\r\n' for line in [' TONE_TYPE_' + name.split(".")[0].upper() + ',\r\n' for name in file_list]: h_file += line h_file += ' TONE_TYPE_MAX,\r\n} tone_type_t;\r\n\r\nint get_tone_uri_num();\r\n\r\n#endif\r\n' return h_file
def all_lowercase(question): """ Lower case all of the string. """ return question.lower()
def squeeze(data: object) -> object: """ Overview: Squeeze data from tuple, list or dict to single object Example: >>> a = (4, ) >>> a = squeeze(a) >>> print(a) >>> 4 """ if isinstance(data, tuple) or isinstance(data, list): if len(data) == 1: return data[0] else: return tuple(data) elif isinstance(data, dict): if len(data) == 1: return list(data.values())[0] return data
def _get_subdir_list(dir_name): """ Get a list of subdirectories. """ subdir_list = [] if dir_name: dirlink = '' dir_items = dir_name.split('/') dir_items.pop() for dirname in dir_items: dirlink = dirlink + dirname + '/' subdir_list.append([dirname,dirlink]) return subdir_list
def get_digit_prefix(characters): """ Return the digit prefix from a list of characters. """ value = 0 while characters and characters[0].isdigit(): value = value * 10 + int(characters.pop(0)) return value
def uv60_to_xy(u60, v60): # CIE1960 to CIE1931 """ convert CIE1960 uv to CIE1931 xy coordinates :param u60: u value (CIE1960) :param v60: v value (CIE1960) :return: CIE1931 x, y """ denominator = (((6 * u60) / 2) - (12 * v60) + 6) if denominator == 0.0: x, y = 0.0, 0.0 else: x = ((18 * u60) / 4) / denominator y = (3 * v60) / denominator return x, y
def get_update_author_profile(d_included, base_url): """Parse a dict and returns, if present, the URL corresponding the profile :param d_included: a dict, as returned by res.json().get("included", {}) :type d_raw: dict :param base_url: site URL :type d_raw: str :return: URL with either company or member profile :rtype: str """ try: urn = d_included["actor"]["urn"] except KeyError: return "" except TypeError: return "None" else: urn_id = urn.split(":")[-1] if "company" in urn: return f"{base_url}/company/{urn_id}" elif "member" in urn: return f"{base_url}/in/{urn_id}"
def obtain_range(list_object): """ Return the range of the list """ min_value = min(list_object) max_value = max(list_object) return max_value - min_value
def create_return_value(status, message, log=None, error=None): """Convenience functiont that creates the start of the return_value dictionary, setting the "status" key to the value of 'status', the "message" key to the value of 'message' and the "log" key to the value of 'log'. If 'error' is passed, then this signifies an exception, which will be packed and returned. This returns a simple dictionary, which is ready to be packed into a json string """ if error: if isinstance(error, Exception): import traceback as _traceback status = -2 message = "%s: %s\nTraceback:\n%s" % ( str(error.__class__.__name__), " : ".join(error.args), "".join(_traceback.format_tb(error.__traceback__))) else: status = -1 message = str(error) return_value = {} return_value["status"] = status return_value["message"] = message if log: return_value["log"] = log return return_value
def bytesto(bytes, from_='b', to='m', bsize=1024): """convert bytes to megabytes, etc. sample code: print('mb= ' + str(bytesto(314575262000000, 'm'))) sample output: mb= 300002347.946 """ a = {'b': 0, 'k': 1, 'Ki': 1, 'm': 2, 'Mi': 2, 'g': 3, 'Gi': 3, 't': 4, 'Ti': 4, 'p': 5, 'Pi': 5, 'e': 6, 'Ei': 6} r = float(bytes) for i in range(a[from_], a[to]): r = r / bsize return r
def img(src, options=None): """takes a src, returns an img tag""" option_str = "" if options: option_list = [" "] for option in options: option_list.extend([option, '="', str(options[option]), '" ']) option_str = "".join(option_list) stub = [ '<img {}src="data:image/png;base64,{}" alt="icon" />'.format(option_str, src) ] return stub
def filter_medal_counts(medal_list, minimum_medal_count): """ This function will filter a <medal_list> of countries and their medal counts (e.g. <medal_counts>) by the number of medals that country won. If the total number of medals won by that country is greater than or equal to <minimum_medal_count>, then it will be included in the returned dictionary. Parameters: medal_list (list): A list of strings, where each string is of the form "<country>,<total number of medals>" minimum_medal_count (int): The minimum number medals that a country must have won in order to be included in the returned dictionary. Returns: dict: A dictionary where each key is a country name and each value is the integer number of medals won by the country. MAKE SURE that the values are integers by converting them using the int() function. As an example, if South Korea was included in this dictionary, its entry would be: {"South Korea" : 17} HINT: You will need to use the int() function to convert string representations of numbers into integers in order to compare two numbers. Also remember that the values of the returned dictionary should be integers as well. """ filtered_countries = {} for country in medal_list: country_data = country.split(",") name = country_data[0] total_medal_count = int(country_data[1]) if total_medal_count >= minimum_medal_count: filtered_countries[name] = total_medal_count return filtered_countries
def time_over(until, now): """ Checks if we are over the time we want to film until. Splits on every loop but it's not like it's a big performance drain. """ if until is None: return False until_hour, until_minutes = until.split(':') hour = int(until_hour) minutes = int(until_minutes) # If we want to watch something overnight, now will be greater before midnight if hour < 12 and now.hour > 12: return False if now.hour > hour or (now.hour == hour and now.minute >= minutes): return True
def verify(str,ref,match=0,start=0): """ return the index of the first character in string that is not also in reference. if "Match" is given, then return the result index of the first character in string that is in reference """ if start<0: start = 0 if start>=len(str): return -1 for i in range(start,len(str)): found = ref.find(str[i])==-1 if found ^ match: return i return -1
def parity(num: int) -> int: """Return the parity of a non-negative integer. For example, here are the parities of the first ten integers: >>> [parity(n) for n in range(10)] [0, 1, 1, 0, 1, 0, 0, 1, 1, 0] This function is undefined for negative integers: >>> parity(-1) Traceback (most recent call last): ... ValueError: expected num >= 0 """ if num < 0: raise ValueError("expected num >= 0") par = 0 while num: par ^= (num & 1) num >>= 1 return par
def func_fact(x): """ >>> func_fact(0) 0 >>> func_fact(1) 1 >>> func_fact(4) 24 >>> func_fact(10) 3628800 >>> func_fact(20) 2432902008176640000L """ if x == 0: return 0 elif x == 1: return 1 else: return x * func_fact(x-1)
def cmp(v1, v2): """ A helper function to compare the two values Parameters:\n v1: first value v2: second value """ if v1 < v2: return -1 elif v1 == v2: return 0 else: return 1
def unique_classes_from_lines(lines): """Return sorted list of unique classes that occur in all lines.""" # Build sorted list of unique classes. unique_classes = sorted( list({x.split(':')[0] for line in lines for x in line})) # pylint: disable=g-complex-comprehension return unique_classes
def _is_dtype(obj): """ True if object is `numpy.dtype`. """ return isinstance(obj, type) and ( obj.__module__ == 'numpy' or obj == complex)
def cmakeScopedDefine(projectName, name, value): """ Formats a CMake -D<projectName>_<name>=<value> argument. """ return '-D%s_%s=%s' % (projectName, name, value)
def get_http_path(http_request): """Given a HTTP request, return the resource path.""" return http_request.split('\n')[0].split(' ')[1]
def serialize_softlearning_class_and_config(cls_name, cls_config): """Returns the serialization of the class with the given config.""" return {'class_name': cls_name, 'config': cls_config}
def guess_content_type_from_body(body): """Guess the content-type based of the body. * "text/html" for str bodies starting with ``<!DOCTYPE html>`` or ``<html>``. * "text/plain" for other str bodies. * "application/json" for dict bodies. * "application/octet-stream" otherwise. """ if isinstance(body, str): if body.startswith(("<!DOCTYPE html>", "<!doctype html>", "<html>")): return "text/html" else: return "text/plain" elif isinstance(body, dict): return "application/json" else: return "application/octet-stream"
def add_missing_levels(ff, summ=True): """ Sum-up the internal abundances from leaf to root """ if sum([f.count(".") for f in ff]) < 1: return ff clades2leaves = {} for f in ff: fs = f.split(".") if len(fs) < 2: continue for l in range(1, len(fs)+1): n = ".".join(fs[:l]) if n in clades2leaves: clades2leaves[n].append(f) else: clades2leaves[n] = [f] ret = {} for k in clades2leaves: if summ: ret[k] = [sum([sum(ff[e]) for e in clades2leaves[k]])] else: lst = [] for e in clades2leaves[k]: if not lst: for i in ff[e]: lst.append(i) else: lst1 = [] i = 0 while i < len(lst): lst1.append(lst[i] + ff[e][i]) i += 1 lst = lst1 ret[k] = lst return ret
def scale_bytes(value, units): """Convert a value in bytes to a different unit. Parameters ---------- value : int Value (in bytes) to be converted. units : string Requested units for output. Options: 'bytes', 'kB', 'MB', 'GB', 'TB' Returns ------- float Value in requested units. """ allowed_units = { 'bytes': 1, 'kB': 1024, 'MB': 1048576, 'GB': 1073741824, 'TB': 1099511627776 } if units not in allowed_units: raise ValueError("Units must be one of {}".format(list(allowed_units.keys()))) scale = allowed_units[units] return value / scale
def _format_range_unified(start, stop): """Convert range to the "ed" format""" beginning = start + 1 length = stop - start if length == 1: return '{}'.format(beginning) if not length: beginning -= 1 return '{},{}'.format(beginning, length)
def delete_nodes_from_list(connecting_points, point_remove): """ Deletes the nodes from the connecting_points list to avoid creation of virtual points. """ for i in range(len(point_remove)): try: connecting_points.RemoveAll(point_remove[i]) except ValueError: continue return connecting_points
def extract_column(table, index): """ Returns the values of a specific column in a table given the column index """ try: return [j[index] for j in table] except IndexError: raise IndexError("Index outside of table")
def generate_date_id(mx_room: str, name: str) -> str: """ Generate a date-id from room-name and date-name :param mx_room: matrix room id :param name: name of the date :return: a combination of room-id and name """ return f"{mx_room}::{name}"
def _convert_str_to_float(str): """ TypeError will take care the case that str is None ValueError will take care the case that str is empty """ if not str: return None try: return float(str) except (TypeError, ValueError): return None
def dsr_pb(D_eq): """ Pruppacher and Beard drop shape relationship function. Arguments: D_eq: Drop volume-equivalent diameter (mm) Returns: r: The vertical-to-horizontal drop axis ratio. Note: the Scatterer class expects horizontal to vertical, so you should pass 1/dsr_pb """ return 1.03 - 0.062*D_eq
def delay_from_foffsets(df, dfd, dfdd, times): """ Return the delays in phase caused by offsets in frequency (df), and two frequency derivatives (dfd, dfdd) at the given times in seconds. """ f_delays = df * times fd_delays = dfd * times**2 / 2.0 fdd_delays = dfdd * times**3 / 6.0 return (f_delays + fd_delays + fdd_delays)
def parse_tabbed_table(txt): """Parse a tab-separated table into list of dicts. Expect first row to be column names. Very primitive. """ txt = txt.replace("\r\n", "\n") fields = None data = [] for ln in txt.split("\n"): if not ln: continue if not fields: fields = ln.split("\t") continue cols = ln.split("\t") if len(cols) != len(fields): continue row = dict(zip(fields, cols)) data.append(row) return data
def int_to_roman(input): """ Convert an integer to Roman numerals. Examples: >>> int_to_roman(0) Traceback (most recent call last): ValueError: Argument must be between 1 and 3999 >>> int_to_roman(-1) Traceback (most recent call last): ValueError: Argument must be between 1 and 3999 >>> int_to_roman(1.5) Traceback (most recent call last): TypeError: expected integer, got <type 'float'> >>> for i in range(1, 21): print int_to_roman(i) ... I II III IV V VI VII VIII IX X XI XII XIII XIV XV XVI XVII XVIII XIX XX >>> print int_to_roman(2000) MM >>> print int_to_roman(1999) MCMXCIX """ if type(input) != type(1): raise TypeError if not 0 < input < 4000: raise ValueError ints = (1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1) nums = ('M', 'CM', 'D', 'CD','C', 'XC','L','XL','X','IX','V','IV','I') result = "" for i in range(len(ints)): count = int(input / ints[i]) result += nums[i] * count input -= ints[i] * count return result
def to_deg(value, loc): """convert decimal coordinates into degrees, munutes and seconds tuple Keyword arguments: value is float gps-value, loc is direction list ["S", "N"] or ["W", "E"] return: tuple like (25, 13, 48.343 ,'N') """ if value < 0: loc_value = loc[0] elif value > 0: loc_value = loc[1] else: loc_value = "" abs_value = abs(value) deg = int(abs_value) t1 = (abs_value - deg) * 60 min = int(t1) sec = round((t1 - min) * 60, 5) return (deg, min, sec, loc_value)
def pentagonal(n): """Returns the n-th pentagonal number""" return n*(3*n-1)/2
def f(t,x,p,q): """ rhs of the ODE""" return p[1] + q[0]*x