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 se...
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 :...
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():...
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_...
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)] ...
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), ...
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 ...
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: ...
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 l...
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: ...
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: ...
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 r...
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...
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=st...
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_ti...
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 """ con...
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_ma...
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', ...
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...
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...
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 ...
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 cr...
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 - ...
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 l...
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.app...
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] = [] ...
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)]...
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_poi...
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() == "": ret...
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. """ ...
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 unorde...
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...
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) + ...
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 = ty...
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 t...
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 = ( ((...
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 valu...
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 poi...
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 dicti...
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...
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 bas...
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 ...
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] == ...
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 m...
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)...
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>') ...
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) ...
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 convert...
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 ...
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'])) ...
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 ...
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 playe...
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', '?/=') ...
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...