content
stringlengths
42
6.51k
def update_resource(payload): """Update resource""" return {'Dummy': 'ResourceUpdated'}
def get_target_variable(target_variable, clinical_dict, sel_patient_ids): """Extract target_variable from clinical_dict for sel_patient_ids If target_variable is a single str, it is only one line of code If target_variable is a list, recursively call itself and return a list of target variables Assume all sel_patient_ids have target_variable in clinical_dict """ if isinstance(target_variable, str): return [clinical_dict[s][target_variable] for s in sel_patient_ids] elif isinstance(target_variable, (list, str)): return [[clinical_dict[s][tar_var] for s in sel_patient_ids] for tar_var in target_variable]
def cookie_repr(c): """ Return a pretty string-representation of a cookie. """ return f"[key]host=[/key][cyan3]{c['host_key']}[/cyan3] " +\ f"[key]name=[/key][cyan3]{c['name']}[/cyan3] " +\ f"[key]path=[/key][cyan3]{c['path']}[/cyan3]"
def maybe_merge_mappings(mapping_1, mapping_2): """ Merges the two maybe mapping if applicable returning a new one. Parameters ---------- mapping_1 : `None`, `mapping` Mapping to merge. mapping_2 : `None`, `mapping` Mapping to merge. Returns ------- merged : `None`, `dict` """ if (mapping_1 is not None) and (not mapping_1): mapping_1 = None if (mapping_2 is not None) and (not mapping_2): mapping_2 = None if mapping_1 is None: if mapping_2 is None: merged = None else: merged = {**mapping_2} else: if mapping_2 is None: merged = {**mapping_1} else: merged = {**mapping_1, **mapping_2} return merged
def dict_of_str(json_dict): """Given a dictionary; return a new dictionary with all items as strings. Args: json_dict(dict): Input JSON dictionary. Returns: A Python dictionary with the contents of the JSON object as strings. """ result = {} for key, value in json_dict.items(): result[key] = '{}'.format(value) return result
def parse_choice(choices, row, column, validation_messages): """ Can be either the key or values in a choice (of any case) """ choice_string = row[column] if choice_string is None: return None choice_string = choice_string.upper() choice_dict = dict(choices) if choice_string in choice_dict: return choice_string reverse_choice_dict = {b.upper(): a for a, b in choices} value = reverse_choice_dict.get(choice_string) if value is None: valid = ','.join(list(choice_dict.keys()) + list(reverse_choice_dict.keys())) message = f"{column}: Could not parse choice '{choice_string}' (valid: {valid})" validation_messages.append(message) return value
def numf(n): """Formats a number between -999 and 9999 to 2-4 characters. Numbers < 10.0 are returned with one decimal after the point, other numbers as integers. Ex.: 0.2341 -> '0.2', 9.0223 -> '9.2', 11.234 -> '11', -5.23 -> '-5.2' """ if abs(n) < 10.0: return "%.1f" % n else: return "%.0f" % n
def count_space(string): """Counts the number of whitespaces to replace with '%20'. Args: string: non-url compliant string Returns: The number of whitespaces that need replacement """ space_count = 0 for index in range(len(string)): character = string[-(index+1)] if character.isspace(): space_count += 1 else: break return space_count / 3
def _transform_interval( interval, first_domain_start, first_domain_end, second_domain_start, second_domain_end ): """ Transform an interval from one domain to another. The interval should be within the first domain [first_domain_start, first_domain_end] For example, _transform_interval((3, 5), 0, 10, 100, 200) would return (130, 150) """ def transform_value(value): position = (value - first_domain_start) / (first_domain_end - first_domain_start) return position * (second_domain_end - second_domain_start) + second_domain_start return [transform_value(value) for value in interval]
def reverse_linear_search(lst, value): """(list, object) -> int Return the index of the first occurence of value in lst, or return -1 if value is not in lst. >>>reverse_linear_search([2, 5, 1, -3], 5) 1 >>>reverse_linear_search([2, 4, 2], 2) 2 >>>reverse_linear_search([], 5) -1 """ i = len(lst) - 1 while i != -1 and lst[i] != value: i = i + 1 if i == -1: return -1 else: return i
def tobin(x, count=8): """ Integer to binary Count is number of bits """ return "".join(map(lambda y:str((x>>y)&1), range(count-1, -1, -1)))
def cpe_compare_version(rule_version, rule_update, conf_version): """ :param rule_version: :param rule_update: :param conf_version: :return: """ rule_version = rule_version.lower() rule_update = rule_update.lower() conf_version = conf_version.lower() result = False try: if rule_version in conf_version and '*' not in rule_update: conf_version_sub = conf_version[len(rule_version):] if conf_version_sub[0] in ('.',): conf_version_sub = conf_version_sub[1:] for i in range(0, len(rule_update)): if conf_version_sub[i] != rule_update[i]: conf_version_sub_suffix = conf_version_sub[i:] if rule_update.endswith(conf_version_sub_suffix): result = True break except IndexError as ex: pass return result
def commaList(ctx, param, value): """Convert comma-separated string to list.""" if not value: return [] return value.split(',')
def filter_missing_rna(s2bins, bins2s, rna_cov): """ remove any bins that don't have 16S """ for bin, scaffolds in list(bins2s.items()): c = 0 for s in scaffolds: if s in rna_cov: c += 1 if c == 0: del bins2s[bin] for scaffold, bin in list(s2bins.items()): if bin not in bins2s: del s2bins[scaffold] return s2bins, bins2s
def kernel_func(x): """ arbitrary function goes here """ return x**4 - 2*x**2 - x - 3
def conv_output_shape(h_w, kernel_size=1, stride=1, pad=0, dilation=1): """ Compute output shape of convolutions """ if type(h_w) is not tuple: h_w = (h_w, h_w) if type(kernel_size) is not tuple: kernel_size = (kernel_size, kernel_size) if type(stride) is not tuple: stride = (stride, stride) if type(pad) is not tuple: pad = (pad, pad) if type(dilation) is not tuple: dilation = (dilation, dilation) h = (h_w[0] + (2 * pad[0]) - (dilation[0] * (kernel_size[0] - 1)) - 1)// stride[0] + 1 w = (h_w[1] + (2 * pad[1]) - (dilation[1] * (kernel_size[1] - 1)) - 1)// stride[1] + 1 return h, w
def toansi(text): """Encode special characters""" trans = { "{": r"\{", "}": r"\}", "\\": r"\\", "|": r"\|", } out = "" for char in text: if char in trans: out += trans[char] elif ord(char) < 127: out += char else: out += r"\'%x" % ord(char) return out
def halve(n): """Halve an integer""" return n // 2 + n % 2, n // 2
def pad(s, pad_to_length): """Pads the given string to the given length.""" return ('%-' + '%ds' % pad_to_length) % (s,)
def _subject(subject: str) -> str: """ Returns a query term matching "subject". Args: subject: The subject of the message. Returns: The query string. """ return f'subject:{subject}'
def _get_uri_from_string(term_string: str) -> str: """ build the url as literal plus only the numbers within [] from the term string """ if '[' in term_string: return 'http://vocab.getty.edu/aat/' + term_string[term_string.index('['):].replace('[', '').replace(']', '') return ''
def clean(s): """ Remove white spaces from <s>. """ return s.strip(' \t\n\r\f\v')
def get_partition_sums(dividers, items): """ Given a list of divider locations and a list of items, return a list the sum of the items in each partition. """ # fix this to take and use prefix sums, but only after you # have written a test. partitions = [.0]*(len(dividers)+1) for x in range(0, len(dividers)+1): if x == 0: left_index = 0 else: left_index = dividers[x-1] if x == len(dividers): right_index = len(items) else: right_index = dividers[x] for y in range(left_index, right_index): partitions[x] += items[y] return partitions
def missing_attrs(attr_dictionary, attr_names): """Gives a dictionary of missing attributes""" mandatory = set(attr_names) missing_attrs = {} for ds_name, ds_attrs_dict in attr_dictionary.items(): ds_attrs_keys = set(ds_attrs_dict.keys()) missing_mandatory = mandatory.difference(ds_attrs_keys) if missing_mandatory: missing_attrs[ds_name] = tuple(missing_mandatory) return missing_attrs
def SplitVariableAndValue(string,sep='='): """ Return variable name nad value in string, i.e. 'var=value'. :param str string: string data :return: varnam(str) - variable name :return: varvasl(str) - value """ var=''; val='' ns=string.find(sep) if ns >= 0: varval=string.split(sep) var=varval[0].strip() try: val=varval[1].strip() except: val='' return var,val
def adjust_site_parameters(site): """Add the PV modeling parameters""" out = site.copy() modeling_params = { 'ac_capacity': 0.00324, # no clipping 'dc_capacity': 0.00324, 'temperature_coefficient': -0.420, 'dc_loss_factor': 0, 'ac_loss_factor': 0, 'surface_tilt': 35, 'surface_azimuth': 180, 'tracking_type': 'fixed'} out['modeling_parameters'] = modeling_params out['extra_parameters']['module'] = 'Suniva 270W' return out
def get_team_from_game(game, home_road): """ Gets abbreviation for team associated with specified home/road denominator. """ if home_road in ['home']: return game['home_abbr'] elif home_road in ['road', 'visitor']: return game['road_abbr'] else: return None
def _get_text(node, tag, default=None): """Get the text for the provided tag from the provided node""" try: result = node.find(tag).text return result except AttributeError: return default
def is_base_pair(s1, s2): """ (str, str) -> bool Precondition: s1 and s2 both contain a single character from 'A', 'T', 'C' or 'G'. Return True iff s1 and s2 form a base pair. >>> is_base_pair('A','T') True >>> is_base_pair('G','T') False """ cond1 = (s1 == 'A' and s2 == 'T') cond2 = (s1 == 'T' and s2 == 'A') cond3 = (s1 == 'G' and s2 == 'C') cond4 = (s1 == 'C' and s2 == 'G') if cond1 or cond2 or cond3 or cond4: return True else: return False
def limit_to_value_max(value_max, value): """ :param 1.(int) value_max -- value that should not be exceed 2.(int) value -- actual value :return 1. return a value in the given range bound with value_max """ if value > value_max: return value_max elif value < -value_max: return -value_max else: return value
def reverseString(s): """ Do not return anything, modify s in-place instead. """ s[:] = s[::-1] return s
def to_indexable(s, caseless=True): """ Normalize table and column surface form to facilitate matching. """ """replace_list = [ ('crs', 'course'), ('mgr', 'manager') ] check_replace_list = { 'stu': 'student', 'prof': 'professor', 'res': 'restaurant', 'cust': 'customer', 'ref': 'reference', 'dept': 'department', 'emp': 'employee' } def to_indexable_name(name): name = name.strip().lower() tokens = name.split() if tokens: tokens = functools.reduce(lambda x, y: x + y, [token.split('_') for token in tokens]) else: if verbose: print('Warning: name is an empty string') for i, token in enumerate(tokens): if token in check_replace_list: tokens[i] = check_replace_list[token] n_name = ''.join(tokens) for s1, s2 in replace_list: n_name = n_name.replace(s1, s2) return n_name if '.' in s: s1, s2 = s.split('.', 1) return to_indexable_name(s1) + '.' + to_indexable_name(s2) else: return to_indexable_name(s) """ if caseless: s = s.lower() return ''.join(s.replace('_', '').split())
def output_to_timeline(timeline_event_map): """Returns a timeline-friendly list from an event mapping. Creates a list of events sorted in ascending numerical order as Advanced Combat Tracker would expect. Returns the list as a Python list, to be altered or printed into the expected parsable format. """ timeline_events = set() for key, values in timeline_event_map.items(): for value in values: timeline_events.add('{time} {event}'.format(time=value, event=key)) return sorted(list(timeline_events), key=lambda s: float(s.split()[0]))
def expand_list(l, n): """Expand a list `l` to repeat its elements till reaching length of `n`""" return (l * (n // len(l) + 1))[:n]
def tloc_to_inc(tloc): """ Convert decimal local time to solar incidence (equator only). """ coinc = (tloc - 6) * 90 / 6 # (6, 18) -> (0, 180) inc = coinc - 90 # (0, 180) -> (-90, 90) return inc
def restore_path( connections, endpoints ): """Takes array of connections and returns a path. Connections is array of lists with 1 or 2 elements. These elements are indices of teh vertices, connected to this vertex Guarantees that first index < last index """ if endpoints is None: #there are 2 nodes with valency 1 - start and end. Get them. start, end = [idx for idx, conn in enumerate(connections) if len(conn)==1 ] else: start, end = endpoints path = [start] prev_point = None cur_point = start while True: next_points = [pnt for pnt in connections[cur_point] if pnt != prev_point ] if not next_points: break next_point = next_points[0] path.append(next_point) prev_point, cur_point = cur_point, next_point return path
def clip_data(x_s, y_s): """ In the case that there are different number of iterations across learning trials, clip all trials to the length of the shortest trial. Parameters: x_s - A list of lists of total timesteps so far per seed. y_s - A list of lists of average episodic return per seed Return: x_s and y_s after clipping both. """ # Find shortest trial length x_len_min = min([len(x) for x in x_s]) y_len_min = min([len(y) for y in y_s]) len_min = min([x_len_min, y_len_min]) # Clip each trial in x_s to shortest trial length for i in range(len(x_s)): x_s[i] = x_s[i][:len_min] # Clip each trial in y_s to shortest trial length for i in range(len(y_s)): y_s[i] = y_s[i][:len_min] return x_s, y_s
def first_char_is_number(text): """Check if string starts with a number.""" return text[0].isdigit()
def filter_iterations(tree, key=lambda i: i, stop=lambda: False): """ Given an iterable of :class:`Iteration` objects, return a new list containing all items such that ``key(o)`` is True. This function accepts an optional argument ``stop``. This may be either a lambda function, specifying a stop criterium, or any of the following special keywords: :: * 'any': Return as soon as ``key(o)`` is False and at least one item has been collected. * 'asap': Return as soon as at least one item has been collected and all items for which ``key(o)`` is False have been encountered. It is useful to specify a ``stop`` criterium when one is searching the first Iteration in an Iteration/Expression tree for which a given property does not hold. """ assert callable(stop) or stop in ['any', 'asap'] tree = list(tree) filtered = [] off = [] if stop == 'any': stop = lambda: len(filtered) > 0 elif stop == 'asap': hits = [i for i in tree if not key(i)] stop = lambda: len(filtered) > 0 and len(off) == len(hits) for i in tree: if key(i): filtered.append(i) else: off.append(i) if stop(): break return filtered
def render_section(contents): """ Render an abstract section with the given contents """ return '\n'.join(contents)
def quad4_ctr(elem_coords): """Compute the coordinates of the center of a quad4 element. Simple average in physical space. The result is the same as for quad4_subdiv with intervals=1. Input: elem_coords: coordinates of element's nodes, assuming exodus node order convention - (counter clockwise around the element) """ X_pt = 0.25*( elem_coords[0][0] + elem_coords[1][0] + elem_coords[2][0] + elem_coords[3][0] ) Y_pt = 0.25*( elem_coords[0][1] + elem_coords[1][1] + elem_coords[2][1] + elem_coords[3][1] ) return [ X_pt, Y_pt, 0.0 ]
def processGOTerm(goTerm): """ In an object representing a GO term, replace single-element lists with their only member. Returns the modified object as a dictionary. """ ret = dict(goTerm) #Input is a defaultdict, might express unexpected behaviour for key, value in ret.items(): if len(value) == 1: ret[key] = value[0] return ret
def quick_sort(lst): """Implement quick sort algorithm.""" if len(lst) < 2: return lst lst = list(lst) left, right, equal = [], [], [] pivot = lst[0] for i in range(len(lst)): if lst[i] < pivot: left.append(lst[i]) elif lst[i] > pivot: right.append(lst[i]) else: equal.append(lst[i]) # list comprehension shortcut: # left = [i for i in lst if i <= pivot] # right = [i for i in lst if i > pivot] return quick_sort(left) + equal + quick_sort(right)
def ackermann(m, n): """Computes the Ackermann function A(m, n) See http://en.wikipedia.org/wiki/Ackermann_function n, m: non-negative integers """ if m == 0: return n+1 if n == 0: return ackermann(m-1, 1) return ackermann(m-1, ackermann(m, n-1))
def normalize_feature(year, feature): """Normalize feature.""" feature = {**feature, "year": feature.get("year", year)} return feature
def header_files(file_list): """Filter header files only from source files list.""" return sorted({file for file in file_list if file.endswith(".h")})
def normalise_dict(d): """ Recursively convert dict-like object (eg OrderedDict) into plain dict. Sorts list values. """ out = {} for k, v in dict(d).items(): if hasattr(v, 'items'): out[k] = normalise_dict(v) elif isinstance(v, list): out[k] = [] for item in sorted(v): if hasattr(item, 'items'): out[k].append(normalise_dict(item)) else: out[k].append(item) else: out[k] = v return out
def dotted_dict_get(key, d): """ >>> dotted_dict_get('foo', {'foo': {'bar': 1}}) {'bar': 1} >>> dotted_dict_get('foo.bar', {'foo': {'bar': 1}}) 1 >>> dotted_dict_get('bar', {'foo': {'bar': 1}}) """ parts = key.split('.') try: while parts and d: d = d[parts.pop(0)] except KeyError: return None if parts: # not completely resolved return None return d
def print_cards(arr): """ Print Cards in a single line Args: arr: array of Card Objects Returns: a displayable string representation of the Cards in the arr """ s = "" for card in arr: s = s + " " + str(card) return s
def lsquare_of_sums(inlist): """ Adds the values in the passed list, squares the sum, and returns the result. Usage: lsquare_of_sums(inlist) Returns: sum(inlist[i])**2 """ s = sum(inlist) return float(s)*s
def get_face_points(input_points, input_faces): """ From http://rosettacode.org/wiki/Catmull%E2%80%93Clark_subdivision_surface 1. for each face, a face point is created which is the average of all the points of the face. """ # 3 dimensional space NUM_DIMENSIONS = 3 # face_points will have one point for each face face_points = [] for curr_face in input_faces: face_point = [0.0, 0.0, 0.0] for curr_point_index in curr_face: curr_point = input_points[curr_point_index] # add curr_point to face_point # will divide later for i in range(NUM_DIMENSIONS): face_point[i] += curr_point[i] # divide by number of points for average num_points = len(curr_face) for i in range(NUM_DIMENSIONS): face_point[i] /= num_points face_points.append(face_point) return face_points
def parts(lst, n=25): """Split an iterable into parts with size n.""" return [lst[i:i + n] for i in iter(range(0, len(lst), n))]
def check_path_valid(obtainpath): """ function: check path valid input : envValue output: NA """ PATH_CHECK_LIST = [" ", "|", ";", "&", "$", "<", ">", "`", "\\", "'", "\"", "{", "}", "(", ")", "[", "]", "~", "*", "?", "!", "\n"] if obtainpath.strip() == "": return for rac in PATH_CHECK_LIST: flag = obtainpath.find(rac) if flag >= 0: return False return True
def create_object_detected_msg(position): """creates an xyz message of target location""" return {'coords':position}
def _hidden_function(num: int) -> str: """ Example which is documented but hidden. :param num: A thing to pass :return: A return value """ return f'{num}'
def serialize_value(value): """Serialize a single value. This is used instead of a single-shot `.format()` call because some values need special treatment for being serialized in YAML; notably, booleans must be written as lowercase strings, and floats exponents must not start with a 0. """ if isinstance(value, bool): return repr(value).lower() elif isinstance(value, float): return "{0:.16}".format(value).replace("e+0", "e+").replace("e-0", "e-") else: return repr(value)
def _replace_chars(name, substitutes): """ Replaces characters in `name` with the substitute characters. If some of the characters are both to be replaced or other characters are replaced with them (e.g.: ? -> !, ! ->#), than it is not safe to give a dictionary as the `substitutes` (because it is unordered). .. warning:: Order matters, because otherwise some characters could be replaced more than once. Parameters ---------- name : str Name substitutes: tuple or None Character pairs with old and substitute characters Returns ------- str """ if substitutes: for (k, v) in substitutes: name = name.replace(k, v) return name
def generateActMessage(estopState:bool, enable: bool, height, angle): """ Accepts an input of two ints between -100 and 100 """ # Empty list to fill with our message messageToSend = [] messageToSend.append(int(estopState)) messageToSend.append(int(enable)) messageToSend.append(int(height)) messageToSend.append(int(angle)) print("Sending: %s" % str(messageToSend)) return messageToSend
def distL1(x1,y1,x2,y2): """Compute the L1-norm (Manhattan) distance between two points. The distance is rounded to the closest integer, for compatibility with the TSPLIB convention. The two points are located on coordinates (x1,y1) and (x2,y2), sent as parameters""" return int(abs(x2-x1) + abs(y2-y1)+.5)
def _valid_value(value): """ this function is used to determine if the result of the consolidate function is valid. Valid types include int, float and lists of numbers. :param value: return value of the `consolidate` function :return: True if type is valid otherwise False """ value_type = type(value) if value_type == int or value_type == float: return True elif value_type == list: for v in value: v_type = type(v) if v_type != int and v_type != float: return False return True else: return False
def _match_to_tuple_index(x, tuple_list): """Apply function to see if passed fields are in the tuple_list""" sid, ncesid, home_away = x return (sid, ncesid, home_away) in tuple_list
def _cmplx_sub_ ( s , o ) : """subtract complex values >>> r = v - other """ return (-o ) + complex ( s )
def convert_case(s): """ Given a string in snake case, conver to CamelCase """ return ''.join([a.title() for a in s.split("_") if a])
def binomial(n, k): """ Return binomial coefficient ('n choose k'). This implementation does not use factorials. """ k = min(k, n - k) if k < 0: return 0 r = 1 for j in range(k): r *= n - j r //= j + 1 return r
def user_model(username, id=1, is_admin=False): """Return a user model""" return { 'username': username, 'id': id, 'is_admin': is_admin }
def _parse_row(row): """Parses a row of raw data from a labelled ingredient CSV file. Args: row: A row of labelled ingredient data. This is modified in place so that any of its values that contain a number (e.g. "6.4") are converted to floats and the 'index' value is converted to an int. Returns: A dictionary representing the row's values, for example: { 'input': '1/2 cup yellow cornmeal', 'name': 'yellow cornmeal', 'qty': 0.5, 'range_end': 0.0, 'unit': 'cup', 'comment': '', } """ # Certain rows have range_end set to empty. if row['range_end'] == '': range_end = 0.0 else: range_end = float(row['range_end']) return { 'input': row['input'], 'name': row['name'], 'qty': float(row['qty']), 'range_end': range_end, 'unit': row['unit'], 'comment': row['comment'], }
def earth_radius(lat): """Calculate the radius of the earth for a given latitude Args: lat (array, float): latitude value (-90 : 90) Returns: array: radius in metres """ from numpy import cos, deg2rad, sin lat = deg2rad(lat) a = 6378137 b = 6356752 r = ( ((a ** 2 * cos(lat)) ** 2 + (b ** 2 * sin(lat)) ** 2) / ((a * cos(lat)) ** 2 + (b * sin(lat)) ** 2) ) ** 0.5 return r
def area_triangle(base: float, height: float) -> float: """ Calculate the area of a triangle given the base and height. >>> area_triangle(10, 10) 50.0 >>> area_triangle(-1, -2) Traceback (most recent call last): ... ValueError: area_triangle() only accepts non-negative values >>> area_triangle(1, -2) Traceback (most recent call last): ... ValueError: area_triangle() only accepts non-negative values >>> area_triangle(-1, 2) Traceback (most recent call last): ... ValueError: area_triangle() only accepts non-negative values """ if base < 0 or height < 0: raise ValueError("area_triangle() only accepts non-negative values") return (base * height) / 2
def get_lines(inp): """ Splits input values into an array of strings """ return inp.strip().split('\n')
def get_extrema_2loops( ximg, yimg, ref_position ): """ Function to determine the two extrema of a set of points through a reference point. The first extreme point (P1) is found by searching for the point furthest from the reference point (usually is some definition of center). The second extreme point is the furthest one from point P1. Input: - ximg <list> : x coordinates of the image - yimg <list> : y coordinates of the image - ref_position <int> : the (Python) position of the reference point in the ximg and yimg lists Output: - <int> : position in the lists ximg and yimg of one extreme point - <int> : position in the lists ximg and yimg of the other extreme point """ # define the reference point coordinates x_ref = ximg[ref_position] y_ref = yimg[ref_position] # find the furthest point from the reference point (1st extreme) furthest_pt1 = 0 distmax = -1 for i in range(0,len(ximg)): # loops over all points if (ximg[i] - x_ref)**2 + (yimg[i] - y_ref)**2 > distmax: distmax = (ximg[i] - x_ref)**2 + (yimg[i] - y_ref)**2 furthest_pt1 = i # find the furthest point from the first extreme (2nd extreme) furthest_pt2 = 0 distmax = -1 for j in range(0,len(ximg)): # loops over all points if (ximg[j] - ximg[furthest_pt1])**2 + (yimg[j] - yimg[furthest_pt1])**2 > distmax: distmax = (ximg[j] - ximg[furthest_pt1])**2 + (yimg[j] - yimg[furthest_pt1])**2 furthest_pt2 = j return furthest_pt1,furthest_pt2;
def resource_id(source_id: str, checksum: str, output_format: str) -> str: """Get the resource ID for an endpoint.""" return f"{source_id}/{checksum}/{output_format}"
def hex_to_dec(x): """Convert hex to decimal """ return int(x, 16)
def _link_gold_predicted(gold_list, predicted_list, matching_fn): """Link gold standard relations to the predicted relations A pair of relations are linked when the arg1 and the arg2 match exactly. We do this because we want to evaluate sense classification later. Returns: A tuple of two dictionaries: 1) mapping from gold relation index to predicted relation index 2) mapping from predicted relation index to gold relation index """ gold_to_predicted_map = {} predicted_to_gold_map = {} gold_arg12_list = [(x['DocID'], (tuple(t[2] for t in x['Arg1']['TokenList']), tuple(t[2] for t in x['Arg2']['TokenList']))) for x in gold_list] predicted_arg12_list = [(x['DocID'], (tuple(x['Arg1']['TokenList']), tuple(x['Arg2']['TokenList']))) for x in predicted_list] predictions = {k: i for i, k in enumerate(predicted_arg12_list)} pi = -1 for gi, gold_span in enumerate(gold_arg12_list): if gold_span in predictions: pi = predictions[gold_span] gold_to_predicted_map[gi] = predicted_list[pi] predicted_to_gold_map[pi] = gold_list[gi] return gold_to_predicted_map, predicted_to_gold_map
def pprint_list(data): """Format list as a bulleted list string. Args: data (list): the list to pprint. Returns: str: a newline separated pretty printed list. """ return '\n - {}'.format('\n - '.join(str(x) for x in data))
def bundle_maker(biglist, size=200): """ Divides a list into smaller lists @param biglist: A big list @param size: The integer representing how large each sub-list should be @return A list of lists that are size `size` """ return [biglist[x:x + size] for x in range(0, len(biglist), size)]
def format_error_message(exception_message): """Improve the formatting of an exception thrown by a remote function. This method takes a traceback from an exception and makes it nicer by removing a few uninformative lines and adding some space to indent the remaining lines nicely. Args: exception_message (str): A message generated by traceback.format_exc(). Returns: A string of the formatted exception message. """ lines = exception_message.split("\n") # Remove lines 1, 2, 3, and 4, which are always the same, they just contain # information about the main loop. lines = lines[0:1] + lines[5:] return "\n".join(lines)
def basenumberconverter(dec, base, numbers): """ Convert decimal number to number of given base Parameters: dec (int) : Decimal to convert base (int) : Base of the number to convert into numbers (str): Numbers of the given base Returns: str: The converted number in given base """ length = 0 dec_copy = dec outnumber = "" while dec > 0: dec = dec // base length = length + 1 while dec_copy > 0: outnumber = outnumber + numbers[dec_copy % base] dec_copy = dec_copy // base length = length - 1 return outnumber[::-1]
def find_left_element(sorted_data, right, comparator): """! @brief Returns the element's index at the left side from the right border with the same value as the last element in the range `sorted_data`. @details The element at the right is considered as target to search. `sorted_data` must be sorted collection. The complexity of the algorithm is `O(log(n))`. The algorithm is based on the binary search algorithm. @param[in] sorted_data: input data to find the element. @param[in] right: the index of the right element from that search is started. @param[in] comparator: comparison function object which returns `True` if the first argument is less than the second. @return The element's index at the left side from the right border with the same value as the last element in the range `sorted_data`. """ if len(sorted_data) == 0: raise ValueError("Input data is empty.") left = 0 middle = (right - left) // 2 target = sorted_data[right] while left < right: if comparator(sorted_data[middle], target): left = middle + 1 else: right = middle offset = (right - left) // 2 middle = left + offset return left
def _relpath(path, basepath): """Generate path part of relative reference. based on: cpython/Lib/posixpath.py:relpath """ path = [x for x in path.split('/')] basepath = [x for x in basepath.split('/')][:-1] i = 0 for index in range(min(len(path), len(basepath))): if path[index] == basepath[index]: i += 1 else: break parent_dirs = len(basepath) - i relpath = (['..'] * parent_dirs) + path[i:] if relpath == ['']: return '.' # gray zone: # if you want to remove the last slash, you have to climb up one directory. # 'http://h/p'(url), 'http://h/p/'(baseurl) -> '../p' if relpath == []: return '../' + path[-1] # gray zone generalized: # 'http://h/p'(url), 'http://h/p/p2'(baseurl) -> '../../p' if all((p == '..' for p in relpath)): return ('../' * (len(relpath) + 1)) + path[-1] # the first segment of a relative-path reference cannot contain ':'. # change e.g. 'aa:bb' to './aa:bb' if ':' in relpath[0]: relpath.insert(0, '.') return '/'.join(relpath)
def get_subattr(obj, name, default=None): """ Return an attribute given a dotted name, or the default if there is not attribute or the attribute is None. """ for attr in name.split('.'): obj = getattr(obj, attr, None) return default if obj is None else obj
def create_filename(star_id): """ Creates the file name for the given star id. This is used to keep the naming consistent throughout and easier to change. """ return "curves/" + star_id + ".csv"
def lin_shced(start, end, pos): """Linear scheduler.""" return start + pos * (end - start)
def flatten(seq): """Converts a list of lists [of lists] to a single flattened list. Taken from the web. """ res = [] for item in seq: if (isinstance(item, (tuple, list))): res.extend(flatten(item)) else: res.append(item) return res
def get_identifiers(code_string): """ Return all valid identifiers found in the C++ code string by finding uninterrupted strings that start with a character or an underscore and continues with characters, underscores or digits. Any spaces, tabs, newlines, paranthesis, punctuations or newlines will mark the end of an identifier (anything that is not underscore or alphanumeric). The returned set will include reserved keywords (if, for, while ...), names of types (float, double, int ...), names of functions that are called (cos, sin ...) in addition to any variables that are used or defined in the code. """ identifiers = set() identifier = [] for c in code_string + ' ': if identifier and (c == '_' or c.isalnum()): identifier.append(c) elif c == '_' or c.isalpha(): identifier = [c] elif identifier: identifiers.add(''.join(identifier)) identifier = None return identifiers
def get_wildcard(name): """ Create a wildcard of the form `<NAME>_VAL` from name. This is supposed to ensure that when replacing the wildcard in the bash script, no accidental mismatch occurs. """ return name.upper() + "_VAL"
def RemoveBadCarac(mot): """ remove a list of bad carac in a word """ bad_carac = [",", "*", "'", "]", "[", "-", " ", '', "(", ")", "//", "\\", "\"", ".", "_"] mot_propre = list() for carac in mot: if carac not in bad_carac and not carac.isnumeric(): mot_propre.append(carac) else: pass #return mot return("".join(mot_propre))
def parse_dimension_string(dim): """ Parse a dimension string ("WxH") into (width, height). :param dim: Dimension string :type dim: str :return: Dimension tuple :rtype: tuple[int, int] """ a = dim.split('x') if len(a) != 2: raise ValueError('"dim" must be <width>x<height>') width, height = a try: width = int(width) height = int(height) except: width = height = 0 if not (width > 0 and height > 0): raise ValueError("width and height must be positive integers") # FIXME: Check allowed image dimensions better return (width, height)
def is_error(value): """Checks if `value` is an ``Exception``. Args: value (mixed): Value to check. Returns: bool: Whether `value` is an exception. Example: >>> is_error(Exception()) True >>> is_error(Exception) False >>> is_error(None) False .. versionadded:: 1.1.0 """ return isinstance(value, Exception)
def convert_qty2gram(qty = {'val': '', 'unit': ''}): """ Convert OFF quantity to a standard quantity (in grams) Args: qty (dict): OFF quantity value and unit Returns: dict with value converted to grams (if possible) and two new keys: std: True if value could be converted using a standard conversion factor approx: True if the original units were not in 'g', 'kg', 'mg' """ init_val = qty['val'] init_unit = qty['unit'] convert_matrix = {'g':1.0, 'kg':1000, 'mg':0.001, 'gal':3785.41, 'egg':50.0, # TO BE VALIDATED 'portion':100.0, # TO BE VALIDATED 'l':1000.0, 'ml':1.0, 'cl':10.0, 'dl':100.0, 'oz':28.3495, 'lb':453.592} if (init_val!='') & (init_unit in convert_matrix.keys()): conv_val = convert_matrix[init_unit]*init_val conv_unit = 'g' conv_std = True else: conv_val = init_val conv_unit = init_unit conv_std = False # all conversions not from g, kg or mg are approximate conversions approx = True if init_unit in ['g', 'kg', 'mg']: approx = False return {'val': conv_val, 'unit': conv_unit, 'std': conv_std, 'approx': approx}
def item_version(item): """ Split the item and version based on sep ':' """ sep = ':' count = item.count(sep) if count == 0: return item, None elif count == 1: return item.split(sep) else: msg = "Found multiple instances of '%s'" % sep raise ValueError(msg)
def check_none(v): """Return None if v is the empty string or the string 'None'.""" return None if (v == 'None' or v == '') else v
def _pad_sequences(sequences, pad_tok, max_length): """ Args: sequences: a generator of list or tuple pad_tok: the char to pad with Returns: a list of list where each sublist has same length """ sequence_padded, sequence_length = [], [] for seq in sequences: seq = list(seq) seq_ = seq[:max_length] + [pad_tok]*max(max_length - len(seq), 0) sequence_padded += [seq_] sequence_length += [min(len(seq), max_length)] return sequence_padded, sequence_length
def parse_pair(pair): """parse a json pair res queried with last actions""" token0 = pair['token0']['symbol'] token1 = pair['token1']['symbol'] return token0, token1
def valid_coordinates(marker): """Checks wether coordinates are valid: a number between 90 and -90 for latitude and -180 and 180 for longitude :param marker: :type marker: dict[str, str] :return: :rtype: bool """ try: if abs(float(marker['long'])) > 180 or abs(float(marker['lat'])) > 90: raise ValueError except (KeyError, ValueError): return False return True
def valid_pt(pt, shape): """ Determine if a point (indices) is valid for a given shaped """ for i, j in zip(pt, shape): if i < 0: # index is not negative return False if i >= j: # index is less than j return False return True
def get_one_ready_index(results): """Get index of a single async computation result that is ready. Given a list containing results of asynchronous computations dispatched to a worker pool, obtain the index of the last computation that has concluded. (Last is better to use the pop() function in the list.) Parameters ---------- results : List[(multiprocessing.pool.AsyncResult, any)] A list of tasks, where each task is a list and the first element is the output of a call to apply_async. The other elements of the list will never be scanned by this function, and they could be anything. Returns ------- int Index of last computation that completed, or len(results) if no computation is ready. """ for i in reversed(range(len(results))): if results[i][0].ready(): return i return len(results)
def _id_to_element_type(player_id, players): """Helper for converting a player's ID to their respective element type: 1, 2, 3 or 4. :param player_id: A player's ID. :type player_id: int :param players: List of all players in the Fantasy Premier League. :type players: list :return: The player's element type. :rtype: int """ player = next(player for player in players if player["id"] == player_id) return player["element_type"]
def split_first(s, delims): """ Given a string and an another delimiters as strings, split on the first found delimiter. Return the two split parts and the matched delimiter. If not found, then the first part is the full input string. Example: :: >>> split_first('foo/bar?baz', '?/=') ('foo', 'bar?baz', '/') >>> split_first('foo/bar?baz', '123') ('foo/bar?baz', '', None) Scales linearly with number of delimiters. Not ideal for a large number of delimiters. .. warning: This function was borrowed from the urllib3 project. It may be removed in future versions of GoLismero. :param s: string to delimit to. :type s: str :param delims: string with delimits characters :type delims: str :return: a tuple as format: (FIRST_OCCURRENCE, REST_OF_TEXT, MATCHING_CHAR) :rtype: (str, str, str|None) :raises: TypeError """ min_idx = None min_delim = None for d in delims: idx = s.find(d) if idx < 0: continue if min_idx is None or idx < min_idx: min_idx = idx min_delim = d if min_idx is None or min_idx < 0: return s, '', None return s[:min_idx], s[min_idx+1:], min_delim
def jwt_get_user_id_from_payload_handler(payload): """ Override this function if user_id is formatted differently in payload """ user_id = payload.get('user_id') return user_id
def extract_sample_info(sample_str): """Extract kit, sample, and technical replicate from sample_str. Inputs - sample_str - string from sample name Returns - tuple (kit, biological sample name, technical replicate) """ s = sample_str.replace('Ftube', '') # The biological sample in now the first character in name bio = s[0] # Extract what kit is in sample kit = '' if 'kapabc' in s.lower(): kit = 'Kapa' elif 'pbat' in s.lower(): kit = 'PBAT' elif 'neb' in s.lower(): kit = 'NEB' elif 'swift' in s.lower(): kit = 'Swift' # Determine if low or high input if '10ng' in s: kit = 'Low ' + kit # Determine technical replicate rep = '1' if 'rep2' in s.lower(): rep = '2' if (bio not in ['A', 'B']) or (kit == ''): print('[extract_sample_info] ERROR: Incorrect entry') return ('', '', '') return (kit, bio, rep)