content
stringlengths
42
6.51k
def Rule110(universe): """Performs a single iteration of the Rule 110 in a borderless universe.""" new = set() for x in universe: if x+1 not in universe: new.add(x) if x-1 not in universe: new.add(x); new.add(x-1) return new
def _prefixed_config(config, prefix): """Returns a dictionary containing only items from the supplied dictionary `config` which start with `prefix`, also converting the key to lowercase and removing that prefix from it. _prefixed_config({'ONE': 1, 'MYPREFIX_TWO': 2}, 'MYPREFIX_') == {'two': 2} """ result = {} for k, v in config.items(): if k.startswith(prefix): result[k[len(prefix):].lower()] = v return result
def build_ec2_metrics(instances): """Build EC2 CPU Utilization metrics""" metrics = [] for instance in instances: metric = ["AWS/EC2", "CPUUtilization", "InstanceId", instance.get('InstanceId')] metrics.append(metric) return metrics
def _apply_probability(kmer, label, compare_label): """Compute binary probability of a label for a kmer. Parameters ---------- kmer : int Kmer count (assumes binary presence/absence (0, 1)). label : str Label value for a given kmer. compare_label : str Label value to assess a given kmer against. Returns ------- list Binary probability (0, 1) of valid kmer with given label for all kmers in the kmer count array. e.g. [0, 1, 1, 0] for an input kmer array of length 4 """ return (kmer == 1) * 1 * (label == compare_label)
def bytes2set(b, delimiter=b'\x00', encoding='utf-8'): """Deserialize bytes into a set of unicode strings. >>> int2byte(b'a\x00b\x00c') {u'a', u'b', u'c'} """ if not b: return set() list_ = b.split(delimiter) return set(bword.decode(encoding) for bword in list_)
def collapse_soloists(present_track_info: dict) -> dict: """ DAVID can provide up to 6 soloists and NEXGEN can provide up to two. They are parsed as soloist1 .. soloist6 (or soloist2 for NG). This squishes them down into one array element for a cleaner client experience. There is probably a way to do this a _bit_ more cleanly than this implementation, but I am going with the Law of Good Enuff here. """ soloists = [f'soloist{number}' for number in range(1, 7)] present_track_info['soloists'] = [] for soloist in soloists: if present_track_info[soloist]: present_track_info['soloists'].append(present_track_info[soloist]) del present_track_info[soloist] return present_track_info
def bold(string): """Return an ANSI bold string.""" from os import name return string if name == "nt" else "\033[1m{}\033[0;0m".format(string)
def SetupPMLForGroup(GroupName, GroupMembersList, Enable = None, Action = None): """Setup PML commands for creating a group from a list of group members. The display and open status of the group may be optionally set. The 'None' values for Enable and Action imply usage of PyMOL defaults for the creation of group. Arguments: GroupName (str): Name of a PyMOL group. GroupMembersList (list): List of group member names. Enable (bool): Display status of group. Action (str): Open or close status of group object. Returns: str: PML commands for creating a group object. """ PMLCmds = [] GroupMembers = " ".join(GroupMembersList) PMLCmds.append("""cmd.group("%s", "%s")""" % (GroupName, GroupMembers)) if Enable is not None: if Enable: PMLCmds.append("""cmd.enable("%s")""" % GroupName) else: PMLCmds.append("""cmd.disable("%s")""" % GroupName) if Action is not None: PMLCmds.append("""cmd.group("%s", action="%s")""" % (GroupName, Action)) PML = "\n".join(PMLCmds) return PML
def sum_of_n_odd_numbers(n): """ Returns sum of first n odd numbers """ try: n+1 except TypeError: # invlid input hence return early return if n < 0: # invlid input hence return early return return n*n
def tau(pv: float, compr_total: float, pi: float): """ Time Constant Parameters --- pv : float pore volume compr_total : float total compressibility pi : float productivity index """ return pv*compr_total/pi
def get_number_from_string(s, number_type, default): """Returns a numeric value of number_type created from the given string or default if the cast is not possible.""" try: return number_type(s.replace(",", ".")) except ValueError: return default
def node_pairs(graph): """Collect 'from-to' nodes in directed graph Args: graph: An instance of dict. Returns: pairs: A list of node pairs. """ stack = [] pairs = [] visited = set() for vertex in graph: stack.append(vertex) while stack: node = stack.pop() if node not in visited: visited.add(node) # ask for permission because it can be a defaultdict! # (no try, except) if node in graph: next_nodes = graph[node] stack.extend(next_nodes) # save reverse direction for other in next_nodes: pairs.append((other, node)) return pairs
def reverse_num_situation(num_situation): """ Returns opposing numerical situation for specified one. """ if num_situation == 'PP': return 'SH' elif num_situation == 'SH': return 'PP' else: return num_situation
def leaves(t): """Returns the leaves of a tree of dotdicts as a list""" if isinstance(t, dict): return [l for v in t.values() for l in leaves(v)] return [t]
def grid_traveller(m: int, n: int) -> int: """ :param m: number of rows in grid :param n: number of columns in grid :return: number of ways to reach bottom right of the grid from a top right corner """ if m == 1 and n == 1: # base case return 1 if m == 0 or n == 0: # either dims empty no way to travel return 0 return grid_traveller(m - 1, n) + grid_traveller(m, n - 1)
def fake_bin(x): """Convert a string of numbers to a string of binary.""" l = list(x) new_l = [] for digit in l: if int(digit) <5: new_l.append("0") else: new_l.append("1") return "".join(new_l)
def change_str(name): """Remove spaces, commas, semicolons, periods, brackets from given string and replace them with an underscore.""" changed = '' for i in range(len(name)): if name[i]=='{' or name[i]=='}' or name[i]=='.' or name[i]==':' \ or name[i]==',' or name[i]==' ': changed += '_' elif name[i]=='\'': changed += '' else: changed += name[i] return changed
def merge_two_dicts(x, y): """A quick function to combine dictionaries. Parameters ---------- x : dict Dictionary 1. y : dict Dictionary 2. Returns ------- dict The merged dictionary. """ z = x.copy() # start with keys and values of x z.update(y) # modifies z with keys and values of y return z
def round_if_int(val): """ Rounds off the decimal of a value if it is an integer float. Parameters ---------- val : float or int A numeric value to be rounded. Retruns ------- val : int The original value rounded if applicable. """ if isinstance(val, float) and val.is_integer(): val = int(val) return val
def parse_crop(cropstr): """ Crop is provided as string, same as imagemagick: size_x, size_y, offset_x, offset_y, eg 10x10+30+30 would cut a 10x10 square at 30,30 Output is the indices as would be used in a numpy array. In the example, [30,40,30,40] (ie [miny, maxy, minx, maxx]) """ split = cropstr.split("x") xsize = int(split[0]) split = split[1].split("+") ysize = int(split[0]) xoff = int(split[1]) yoff = int(split[2]) crop = [yoff, yoff+ysize, xoff, xoff+xsize] return crop
def escaped_size(string): """ >>> escaped_size(r'""') 6 >>> escaped_size(r'"abc"') 9 >>> escaped_size(r'"aaa\\"aaa"') 16 >>> escaped_size(r'"\\x27"') 11 """ return len(string) + 2 + string.count('"') + string.count('\\')
def have_colours(stream): """ Detect if output console supports ANSI colors. :param stream: :return: """ if not hasattr(stream, "isatty"): return False if not stream.isatty(): return False # auto color only on TTYs try: import curses curses.setupterm() return curses.tigetnum("colors") > 2 except BaseException: # guess false in case of error return False
def rename_band(bandpath): """ Bring bandname from CAAPR convention to Williams convention. """ def _any_in(candidate_parts, string): for part in candidate_parts: if part in string: return True return False # GALEX_NUV.fits -> GALEX_NUV bandname = bandpath[:-5] # WISE_3.4.fits -> WISE3_4 bandname = bandname.replace('_', '').replace('.', '_') if 'Spitzer' not in bandname: return bandname # Spitzer -> IRAC or MIPS if _any_in(['3_6', '4_5', '5_8'], bandname): # Spitzer3_6 -> IRAC3_6 return bandname.replace('Spitzer', 'IRAC') elif '8_0' in bandname: # IRAC8_0 -> IRAC8 return 'IRAC8' # Spitzer24 -> MIPS24 return bandname.replace('Spitzer', 'MIPS')
def get_iiif_image_url(iiif_manifest): """Given a IIIF manifest dictionary, derives the value for the info.json file URL, which can then be stored in the roll metadata and eventually used to display the roll image in a viewer such as OpenSeadragon.""" resource_id = iiif_manifest["sequences"][0]["canvases"][0]["images"][0]["resource"][ "@id" ] return resource_id.replace("full/full/0/default.jpg", "info.json")
def combine_ids(paramid_tuples): """ Receives a list of tuples containing ids for each parameterset. Returns the final ids, that are obtained by joining the various param ids by '-' for each test node :param paramid_tuples: :return: """ # return ['-'.join(pid for pid in testid) for testid in paramid_tuples]
def transceive_uid(uid, max_bits): """ Slices the supplied uid List based on the maximum bits the UID should contain.""" return uid[:int(max_bits / 8) + (1 if (max_bits % 8) else 0)]
def g(n): """assume n >= 0 1. Computes n ** 2 very inefficiently 2. When k dealing with nested loops, look at the ranges 3. Nested loops, each iterating n times >>> g(3) 9 >>> g(5) 25 >>> g(7) 49 """ x = 0 for i in range(n): for j in range(n): x += 1 return x
def to_pos(i, j): """Convert a coordinate (with 0,0 at bottom left) on the board to the standard representation >>> to_pos(0,0) 'a1' >>> to_pos(3,3) 'd4' """ return 'abcdefgh'[i] + str(j + 1)
def convert_to_base(num, base): """ Convert a base-10 integer to a different base. """ q = num//base r = num % base if (q == 0): return [r] else: return convert_to_base(q, base) + [r]
def int_d(v, default=None): """Cast to int, or on failure, return a default Value""" try: return int(v) except: return default
def flatten(obj): """ Flattens an object into a list of base values. """ if isinstance(obj, list) or isinstance(obj, dict): l = [] to_flatten = obj if isinstance(obj, list) else obj.values() for sublist in map(flatten, to_flatten): if isinstance(sublist, list): l += flatten(sublist) else: l.append(sublist) return l return obj
def fmt_latency(lat_min, lat_avg, lat_max): """Return formatted, rounded latency. :param lat_min: Min latency :param lat_avg: Average latency :param lat_max: Max latency :type lat_min: string :type lat_avg: string :type lat_max: string :return: Formatted and rounded output "min/avg/max" :rtype: string """ try: t_min = int(round(float(lat_min))) except ValueError: t_min = int(-1) try: t_avg = int(round(float(lat_avg))) except ValueError: t_avg = int(-1) try: t_max = int(round(float(lat_max))) except ValueError: t_max = int(-1) return "/".join(str(tmp) for tmp in (t_min, t_avg, t_max))
def is_point_in_poly_array(test_x, test_y, poly): """Implements the ray casting/crossing number algorithm. Returns TRUE if the point is within the bounds of the points that specify the polygon (poly is a list of points).""" # Sanity checks. if not isinstance(poly, list): return False num_crossings = 0 num_vertices = len(poly) if num_vertices < 3: # Need at least three points to make a polygon return False for i in range(0, num_vertices): # Cache the y coordinate for the first point on the edge. poly_pt = poly[i] if len(poly_pt) != 2: return False poly_pt1_y = poly_pt[1] # Cache the second point on the edge, handling the wrap around that happens when we close the polygon. if i == num_vertices - 1: poly_pt = poly[0] poly_pt2_x = poly_pt[0] poly_pt2_y = poly_pt[1] else: poly_pt = poly[i + 1] poly_pt2_x = poly_pt[0] poly_pt2_y = poly_pt[1] # Test if the point is within the y limits of the edge. crosses_y = ((poly_pt1_y <= test_y) and (poly_pt2_y > test_y)) or ((poly_pt1_y > test_y) and (poly_pt2_y <= test_y)) if crosses_y: # Test if the ray extending to the right of the point crosses the edge. poly_pt1_x = (poly[i])[0] if test_x < poly_pt1_x + ((test_y - poly_pt1_y) / (poly_pt2_y - poly_pt1_y)) * (poly_pt2_x - poly_pt1_x): num_crossings = num_crossings + 1 return num_crossings & 1
def rmcode(txt): """Remove code blocks from markdown text""" if '```' not in txt: return txt i = txt.find('```') n = txt.find('```', i + 3) if n == -1: return txt.replace('```', '') txt = txt.replace(txt[i:n + 3], '') if '```' in txt: return rmcode(txt) return txt.strip()
def hamming_similarity(s1, s2): """ Hamming string similarity, based on Hamming distance https://en.wikipedia.org/wiki/Hamming_distance :param s1: :param s2: :return: """ if len(s1) != len(s2): return .0 return sum([ch1 == ch2 for ch1, ch2 in zip(s1, s2)]) / len(s1)
def nsKey(comps): """ Returns bytes namespaced key from concatenation of ':' with qualified Base64 prefix bytes components If any component is a str then converts to bytes """ comps = map(lambda p: p if not hasattr(p, "encode") else p.encode("utf-8"), comps) return b':'.join(comps)
def book_name_addrs(nms): """Returns a list of the named range addresses in a workbook. Arguments: nms -- Named range list """ return [nm.refers_to_range.get_address(include_sheetname=True) for nm in nms]
def get_var_names(variable): """ get the long variable names from 'flow' or 'temp' :param variable: [str] either 'flow' or 'temp' :return: [str] long variable names """ if variable == "flow": obs_var = "discharge_cms" seg_var = "seg_outflow" elif variable == "temp": obs_var = "temp_c" seg_var = "seg_tave_water" else: raise ValueError('variable param must be "flow" or "temp"') return obs_var, seg_var
def overlap_hashes(hash_target, hash_search): """Return a set of hashes common between the two mappings""" return set(hash_target).intersection(set(hash_search))
def unnormalize(img, norm_min, norm_max): """ Unnormalize numpy array or torch tensor from given norm range [norm_min, norm_max] to RGB range. """ assert norm_max > norm_min norm_range = norm_max - norm_min return (img - norm_min)/norm_range*255.0
def _parse_extra_options(opt_array): """ Convert any options that can't be parsed by argparse into a kwargs dict; if an option is specified multiple times, it will appear as a list in the results :param opt_array: a list of "option=value" strings :returns: a dict mapping from options -> values """ kwargs = {} for opt_string in opt_array: opt, val = [s.strip() for s in opt_string.split("=")] if opt in kwargs: if not isinstance(kwargs[opt], list): kwargs[opt] = [kwargs[opt]] kwargs[opt].append(val) else: kwargs[opt] = val return kwargs
def l32(pos, b, l): """ Find out if position is over line 3 bottom """ x, y = pos if (y >= 0): return True else: return False
def pascal_triangle(n): """gets pascal triangle for n, -> n assumed to always be int -> handles NO exceptions Return: matrix of list of values representing triangle """ ret_mat = [] for i in range(0, n): mat_len = len(ret_mat) if mat_len <= 1: ret_mat.append([1 for q in range(0, mat_len + 1)]) else: new_row = [] for j in range(0, len(ret_mat[i - 1]) + 1): if j == 0 or j == len(ret_mat[i - 1]): new_row.append(1) else: new_row.append(ret_mat[i - 1][j - 1] + ret_mat[i - 1][j]) ret_mat.append(new_row) return ret_mat
def get_letters_set_from_algo(algo): """ Returns 1 if it's a chord algo, 3 if it's a melody algo. This is an arbitraty choice. :param algo: :return: """ prefix = algo.split("_")[0] if prefix == "chords": return 1 elif prefix == "melody": return 3 else: raise IOError("Unexpected algo type")
def _R2FromGaussian(sigmax, sigmay, pixel=0.1): """ """ return (sigmax*pixel)**2 + (sigmay*pixel)**2
def features_to_edges(list_features, edges): """ Transform a list of QgsFeatures objects into a list of the corresponding Edge objects of the layer. :param list_features: list of the features corresponding to the desired edges :type list_features: list of QgsFeatures objects :param input_layer: layer of the features (and the corresponding edges) :type input_layer: QgsVectorLayer object :return: list of edges :rtype: list of Edge objects """ # List of the edges to return list_edges = [] # For each feature of the list for feature in list_features: # ID of the feature id_feature = feature.id() # Corresponding edge: index in the edges list edge = edges[id_feature] # Update list list_edges.append(edge) return list_edges
def _add_param(params, value, key): """ If value is not None then return dict params with added (key, value) pair :param params: dictionary of parameters :type: dict :param value: Value :param key: Key :return: if value not ``None`` then a copy of params with (key, value) added, otherwise returns params """ if value: params[key] = value return params
def removeNumbers(text): """ Removes integers """ text = ''.join([i for i in text if not i.isdigit()]) return text
def basic_sobject_to_dict(obj): """Converts suds object to dict very quickly. Does not serialize date time or normalize key case. :param obj: suds object :return: dict object """ if not hasattr(obj, '__keylist__'): return obj data = {} fields = obj.__keylist__ for field in fields: val = getattr(obj, field) if isinstance(val, list): data[field] = [] for item in val: data[field].append(basic_sobject_to_dict(item)) else: data[field] = basic_sobject_to_dict(val) return data
def _to_utf8_string(s): """Encodes the input csv line as a utf-8 string when applicable.""" return s if isinstance(s, bytes) else s.encode('utf-8')
def mag2flux(mag): """Convert flux to arbitrary flux units""" return 10.**(-.4*mag)
def age_category(age, average=-1): """ We divided the age into 5 steps taking care of the responsibility that a person has of himself and looking at how mush "strength" it has. This is an insteresting parameter to change while seeing inference. In case of nan values we put the average eta of the people who was embarked :param age: int with number :param average: average eta of people :return: class. -1 is returned in case of some strange value """ if 'nan' in str(age): age = average if age < 11: return 0 elif age < 20: return 1 elif age < 40: return 2 elif age < 60: return 3 elif age < 200: return 4 return -1
def valid_date_of_birth(date_of_birth): """ Does the supplied date string meet our criteria for a date of birth """ #Do whatever you need to do... return True
def contains_number(s): """Check if string contains any number""" return any(map(str.isdigit, s))
def normal_power(x, n): """Complexity: O(n)""" if n == 0: return 1 else: return x * normal_power(x, n-1)
def isclose(a, b, rel_tol=1e-09, abs_tol=0.0): """Compare too floating point numbers.""" return abs(a - b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol)
def merge_dicts(*dict_args): """ Given any number of dicts, shallow copy and merge into a new dict, precedence goes to key value pairs in latter dicts. http://stackoverflow.com/questions/38987/how-to-merge-two-python-dictionaries-in-a-single-expression """ result = {} for dictionary in dict_args: result.update(dictionary) return result
def get_photo_page(photo_info): """ Get the photo page URL from a photo info object """ ret = '' if photo_info.get('urls') and photo_info['urls'].get('url'): for url in photo_info['urls']['url']: if url.get('type') == 'photopage': ret = url.get('text') return ret
def obj_in_list_always(target_list, obj): """ >>> l = [1,1,1] >>> obj_in_list_always(l, 1) True >>> l.append(2) >>> obj_in_list_always(l, 1) False """ for item in set(target_list): if item is not obj: return False return True
def count_interval_times(start_event, end_event, messages): """ Count the time in all [start_event,end_event] intervals and return the sum. """ interval_times = 0.0 last_start_stamp = None last_start_time = None # If messages is empty, return 0 if not messages: return interval_times # The name of a message's 'event' field depends on its class. attr_name = None sample_msg = messages[0] # if isinstance(sample_msg, mrta.msg.ExperimentEvent): if sample_msg.__class__.__name__ == '_mrta__ExperimentEvent': attr_name = 'event' # elif isinstance(sample_msg, mrta.msg.TaskStatus): elif sample_msg.__class__.__name__ == '_mrta__TaskStatus': attr_name = 'status' else: # Should actually raise an error here print('Unrecognized message class: {0}'.format(sample_msg.__class__.__name__)) return interval_times for message in messages: event = message.__getattribute__(attr_name) if event == start_event: # print("setting last_start_stamp to: {0}".format(pp.pformat(message.header.stamp))) last_start_stamp = message.header.stamp # print("message: {0}".format(pp.pformat(message))) # print("setting last_start_time to: {0}".format(pp.pformat(message.time))) # last_start_stamp = message.time continue elif event == end_event: if not last_start_stamp: print("count_interval_time(): {0} not preceded by a {1}!".format(end_event, start_event)) continue else: # print("start time: {0}, end time: {1}".format(pp.pformat(last_start_stamp), pp.pformat(message.header.stamp))) if message.header.stamp < last_start_stamp: print("Interval end time is earlier than its start time. Something is wrong!") interval_time = message.header.stamp - last_start_stamp interval_secs = interval_time.secs + (interval_time.nsecs/1000000000.) # print("{0}--{1}=={2}".format(start_event, end_event, interval_secs)) interval_times += interval_secs last_start_stamp = None # print("total: {0}".format(interval_times)) return interval_times
def parse_hook_module(hook_module): """ Parse a hook_module and split it into two parts >>> parse_hook_module('django.core.handlers.base::BaseHandler') ['django.core.handlers.base', 'BaseHandler'] >>> parse_hook_module('django.core.handlers.base') ['django.core.handlers.base', None] """ if "::" in hook_module: return hook_module.split("::", 1) else: return [hook_module, None]
def has_deprecations(cls): """Decorator to ensure that docstrings get updated for wrapped class""" for obj in [cls] + list(vars(cls).values()): if callable(obj) and hasattr(obj, '__new_docstring'): try: obj.__doc__ = obj.__new_docstring except AttributeError: # probably Python 2; we can't update docstring in Py2 # see https://github.com/Chilipp/docrep/pull/9 and related pass del obj.__new_docstring return cls
def getBinaryRep(n, numDigits): """Assumes n and numDigits are non-negative ints Returns a numDigits str that is a binary representation of n""" result = '' while n > 0: result = str(n%2) + result n = n//2 if len(result) > numDigits: raise ValueError('not enough digits') for i in range(numDigits - len(result)): result = '0' + result return result
def toggle_modal(n1, n2, is_open): """toggle_modal() """ if n1 or n2: return not is_open return is_open
def vecInt(vec): """Retruns something.""" return tuple([int(c) for c in vec])
def join_epiweek(year, week): """ return an epiweek from the (year, week) pair """ return year * 100 + week
def isFileLike(thing): """Returns true if thing looks like a file.""" if hasattr(thing, "read") and hasattr(thing, "seek"): try: thing.seek(1, 1) thing.seek(-1, 1) return True except IOError: pass return False
def format_data_comma(data): """ Format the numbers in the string to include commas. Args: data (string or list): A text string. Requires: None Returns: (string): A text string. """ if not isinstance(data,list): data=data.split() new_string=[] for token in data: try: new_token="{:,}".format(int(token)) except ValueError: new_token=token new_string.append(new_token) return " ".join(new_string)
def card_controls(context, card_placement): """Display control buttons for managing one single card """ return { 'user': context['user'], 'card_placement': card_placement, }
def to_int(val): """ Turn the passed in variable into an int; returns 0 if errors Args: val (str): The variable to turn into an int Returns: int: The int value if possible, 0 if an error occurs """ try: return int(val) except ValueError: return 0
def get_reachable_resolved_callable_ids(callables, entrypoints): """ Returns a :class:`frozenset` of callables ids that are resolved and reachable from *entrypoints*. """ return frozenset().union(*(callables[e].get_called_callables(callables) for e in entrypoints))
def cpf_checksum(cpf): """ CPF Checksum algorithm. """ if cpf in map(lambda x: str(x) * 11, range(0, 10)): return False def dv(partial): s = sum(b * int(v) for b, v in zip(range(len(partial) + 1, 1, -1), partial)) return s % 11 dv1 = 11 - dv(cpf[:9]) q2 = dv(cpf[:10]) dv2 = 11 - q2 if q2 >= 2 else 0 return dv1 == int(cpf[9]) and dv2 == int(cpf[10])
def reduced_chi_squared(chi_squared, N, P): """ :param chi_squared: Chi squared value :param N: (int) number of observations :param P: (int) number of important parameters :return: Reduced Chi squared """ return chi_squared / (N - P)
def calculate_bodyfat_per_week(data) -> float: """Reads a list that stores a week's worth of data to calculate and return average body fat per week""" total = 0 day = len(data) for index, body_fat in enumerate(data): total += body_fat[3] return total / day
def Uunbalance_calc(ua,ub,uc): """Calculate voltage/current unbalance.""" uavg = (ua + ub + uc)/3 return (max(ua,ub,uc) - min(ua,ub,uc))/uavg
def combine_names(names, ids=None): """Combine the selected names into one new name. Parameters ---------- names : list of str String names ids : numpy.ndarray, optional Selected index Returns ------- str """ if ids is None: return '+'.join(sorted(names)) else: selected = sorted([names[i] for i in ids]) return '+'.join(selected)
def bits2val(bits): """For a given enumeratable bits, compute the corresponding decimal integer.""" # We assume bits are given in high to low order. For example, # the bits [1, 1, 0] will produce the value 6. return sum(v * (1 << (len(bits)-i-1)) for i, v in enumerate(bits))
def generate_base_map(read_data_list): """ generate data base map """ tx_len = len(read_data_list[0]) rx_len = len(read_data_list[0][0]) sum_list = [([0.0] * rx_len) for i in range(tx_len)] for i in range(len(read_data_list)): for j in range(len(read_data_list[i])): for k in range(len(read_data_list[i][j])): sum_list[j][k] += (float(read_data_list[i][j][k])) for i in range(len(sum_list)): for j in range(len(sum_list[i])): sum_list[i][j] /= len(read_data_list) return sum_list
def is_uppercase(value): """ Is the value all uppercase? Returns True also if there are no alphabetic characters. """ return value == value.upper()
def zone_compare(value, zones): """ Determines whether value is in a known zone """ for zone in zones: if value.endswith("." + zone) or value == zone: return zone return None
def complete_proverb(pvb): """ Checks if the proverb is complete. Assumes the proverb is converted to have underscores replacing unknown letters. Assumes everything is uppercase. :param pvb: a proverb :type pvb: str :return: True | False :rtype: bool """ if "_" not in pvb: return True return False
def _lstrip(source: str, prefix: str) -> str: """ Strip prefix from source iff the latter starts with the former. """ if source.startswith(prefix): return source[len(prefix) :] return source
def check_no_match(expected_id: str, par_id: str) -> bool: """Checks if paragraph ID matches the expected doc ID""" if par_id.split('.pdf')[0].upper().strip().lstrip() == expected_id.upper().strip().lstrip(): return False else: return True
def parse_firewall(firewall): """ Parse firewall into firewall dict """ firewall_dict = {} for connect, v in firewall.items(): firewall_dict[eval(connect)] = v return firewall_dict
def list_if_in(input_list, string_in): """Return a list without input items not containing an input string. Parameters ---------- input_list : list[str] A list of strings. string_in : str A string to check items in the list. Returns ------- list A copy of input list w/o strings not containing string_in. """ return [string for string in input_list if string_in in string]
def set_mathjax_style(style_css, mathfontsize): """Write mathjax settings, set math fontsize """ jax_style = """<script> MathJax.Hub.Config({ "HTML-CSS": { /*preferredFont: "TeX",*/ /*availableFonts: ["TeX", "STIX"],*/ styles: { scale: %d, ".MathJax_Display": { "font-size": %s, } } } });\n</script> """ % (int(mathfontsize), '"{}%"'.format(str(mathfontsize))) style_css += jax_style return style_css
def GetPressure(u, rho, gamma): """ RETURNS: pressure in simulation units INPUT: u : thermal energy rho : density gamma : adiabatic index """ return (gamma-1.)*rho*u
def convert_string_to_list(input_string): """Convert a given string into an array compatible with data model tsvs for array attributes.""" # remove single & double quotes, remove spaces, remove [ ], separate remaining string on commas (resulting in a list) output_list = str(input_string).replace("'", '').replace('"', '').replace(" ", "").strip('[]').split(",") return output_list
def get_number_same_as_index(lst: list) -> int: """ Parameters ----------- lst: the given sorted list Returns --------- Notes ------ binary search """ left, right = 0, len(lst) - 1 while left <= right: mid = (left + right) // 2 if lst[mid] == mid: return mid if lst[mid] > mid: right = mid - 1 else: left = mid + 1 return -1
def has_field_name(s): """ fieldName -> hasFieldName """ return 'has' + s[:1].upper() + s[1:]
def scale(coord_paths, scale_factor): """ Take an array of paths, and scale them all away from (0,0) cartesian using a scalar factor, return the resultinv paths. """ new_paths = [] for path in coord_paths: new_path = [] for point in path: new_path.append( (point[0]*scale_factor, point[1]*scale_factor)) new_paths.append(new_path) return new_paths
def camelcase(name): """Converts a string to CamelCase. Args: name (str): String to convert. Returns: str: `name` in CamelCase. """ return ''.join(x.capitalize() for x in name.split('_'))
def prng(ofs,siz=0,cnt=0): """ create a range of memory map addresses separated by siz bytes """ if siz !=0 and cnt!=0: # an array of cnt elements separated by siz bytes return range(ofs,cnt*siz+ofs,siz) else: # a range with a single address return range(ofs,ofs+1)
def ensure_extension(path, ext): """ Make sure path ends with the correct extension """ if path.endswith(ext): return path else: return path + ext
def ClusterSpecString(num_workers, num_param_servers, port): """Generates general cluster spec.""" spec = 'worker|' for worker in range(num_workers): spec += 'tf-worker%d:%d' % (worker, port) if worker != num_workers-1: spec += ';' spec += ',ps|' for param_server in range(num_param_servers): spec += 'tf-ps%d:%d' % (param_server, port) if param_server != num_param_servers-1: spec += ';' return spec
def shorten(text): """Collapse whitespace in a string.""" return ' '.join(text.split())
def __deep_warn_equal(path, d1, d2, d1name, d2name): """Print warning if two structures are not equal (deeply).""" if type(d1) == dict: iterator = d1 else: if len(d1) != len(d2): return ["Warning: <{}> has length {} in {} but {} in {}".format( path, len(d1), d1name, len(d2), d2name)] iterator = range(len(d1)) warnings = [] for key in iterator: inner_path = path + "/" + str(key) if type(d1) == dict and key not in d2: warnings.append( "<{}> is present in {} but not in {}".format( inner_path, d1name, d2name)) elif not isinstance(d1[key], type(d2[key])): warnings.append( "<{}> has type {} in {} but {} in {}".format( inner_path, type(d1[key]), d1name, type(d2[key]), d2name)) elif type(d1[key]) in (list, tuple, dict): warnings += __deep_warn_equal( inner_path, d1[key], d2[key], d1name, d2name) elif d1[key] != d2[key]: warnings.append( "<{}> has value '{}' in {} but '{}' in {}".format( inner_path, d1[key], d1name, d2[key], d2name)) return warnings
def next_temperature(prev_temp, prev_next_temp, prev_to_prev_temp, lamb): """ Calculator of the next temperature to be computed with the explicit method """ return prev_temp + lamb * (prev_next_temp - 2*prev_temp + prev_to_prev_temp)
def find_plus(word): """ returns 1 if the word containe '+' Input=word Output=flag """ if '+' in word: return 1 return 0
def to_char(value: int) -> str: """ Convert an integer to a single character, where 0 equals A. Note: This method will return an uppercase character. :param value: an integer :return: a character representation """ return chr(ord("A") + value)