content
stringlengths
42
6.51k
def digits_to_skip(distinct_letter_pairs: int) -> int: """The number of letters which can be skipped (i.e. not being incremented one by one) depending on the number of distinct letter pairs present.""" if distinct_letter_pairs == 0: # If no letter pair exists already, we know at least one must be # among the last two digits. Hence we can set those to 0 and continue # from there. return 2 # No optimization possible, have to start at the end. return 0
def get_port_str(port: str) -> str: """Get str representing port for using in human_readable strings. Args: port (str): Port name Returns: str: if port is 'top' return '(port top)' if port is None return '' """ if port: return '(port {0})'.format(port) return ''
def score_distance(x): """Function used to compute the distance score (x should be between 0 and 1 but can be a bit greter than 1)""" a = 10 b = 0.5 s = 0.2 g = 0.18*x + s f = (1/(b*g)**2 - a/(b*g)) * 0.1 *(1-x) / a return min(1, - 4.82*f)
def rescale_score_by_abs (score, max_score, min_score): """ rescale positive score to the range [0.5, 1.0], negative score to the range [0.0, 0.5], using the extremal scores max_score and min_score for normalization """ # CASE 1: positive AND negative scores occur -------------------- if max_score>0 and min_score<0: if max_score >= abs(min_score): # deepest color is positive if score>=0: return 0.5 + 0.5*(score/max_score) else: return 0.5 - 0.5*(abs(score)/max_score) else: # deepest color is negative if score>=0: return 0.5 + 0.5*(score/abs(min_score)) else: return 0.5 - 0.5*(score/min_score) # CASE 2: ONLY positive scores occur ----------------------------- elif max_score>0 and min_score>=0: if max_score == min_score: return 1.0 else: return 0.5 + 0.5*(score/max_score) # CASE 3: ONLY negative scores occur ----------------------------- elif max_score<=0 and min_score<0: if max_score == min_score: return 0.0 else: return 0.5 - 0.5*(score/min_score)
def listify(value, return_empty_list_if_none=True, convert_tuple_to_list=True) -> list: """Ensures that the value is a list. If it is not a list, it creates a new list with `value` as an item. Args: value (object): A list or something else. return_empty_list_if_none (bool, optional): When True (default), None you passed as `value` will be converted to a empty list (i.e., `[]`). When False, None will be converted to a list that has an None (i.e., `[None]`). Defaults to True. convert_tuple_to_list (bool, optional): When True (default), a tuple you passed as `value` will be converted to a list. When False, a tuple will be unconverted (i.e., returning a tuple object that was passed as `value`). Defaults to True. Returns: list: A list. When `value` is a tuple and `convert_tuple_to_list` is False, a tuple. """ if not isinstance(value, list): if value is None and return_empty_list_if_none: value = [] elif isinstance(value, tuple) and convert_tuple_to_list: value = list(value) else: value = [value] return value
def remove_base64(examples): """Remove base64-encoded string if "path" is preserved in example.""" for eg in examples: if "audio" in eg and eg["audio"].startswith("data:") and "path" in eg: eg["audio"] = eg["path"] if "video" in eg and eg["video"].startswith("data:") and "path" in eg: eg["video"] = eg["path"] return examples
def format_bytes(size): """ Format a number of bytes as a string. """ names = ("B", "KB", "MB", "GB", "TB") mag = 0 while size > 1024: mag += 1 size = size / 1024.0 return "{} {}".format(round(size, 2), names[mag])
def _errmsg(argname, ltd, errmsgExtra=''): """Construct an error message. argname, string, the argument name. ltd, string, description of the legal types. errmsgExtra, string, text to append to error mssage. Returns: string, the error message. """ if errmsgExtra: errmsgExtra = '\n' + errmsgExtra return "arg '%s' must be %s%s" % (argname, ltd, errmsgExtra)
def truncate(s, maxlen=128, suffix='...'): # type: (str, int, str) -> str """Truncate text to a maximum number of characters.""" if maxlen and len(s) >= maxlen: return s[:maxlen].rsplit(' ', 1)[0] + suffix return s
def event(): """Event fixture.""" return { "path": "/", "httpMethod": "GET", "headers": {"Host": "test.apigw.com"}, "queryStringParameters": {}, }
def _traverse_pagination(response, endpoint, querystring, no_data): """Traverse a paginated API response. Extracts and concatenates "results" (list of dict) returned by DRF-powered APIs. """ results = response.get('results', no_data) page = 1 next_page = response.get('next') while next_page: page += 1 querystring['page'] = page response = endpoint.get(**querystring) results += response.get('results', no_data) next_page = response.get('next') return results
def replace(s, old, new, maxsplit=0): """replace (str, old, new[, maxsplit]) -> string Return a copy of string str with all occurrences of substring old replaced by new. If the optional argument maxsplit is given, only the first maxsplit occurrences are replaced. """ return s.replace(old, new, maxsplit)
def func_x_a(x, a=2): """func. Parameters ---------- x: float a: int, optional Returns ------- x: float a: int """ return x, None, a, None, None, None, None, None
def format_cmd(cmd): """If some command arguments have spaces, quote them. Then concatenate the results.""" ans = "" for val in cmd: if " " in val or "\t" in cmd: val = '"' + val + '"' ans += val + " " return ans
def xor(b1, b2): """Expects two bytes objects of equal length, returns their XOR""" assert len(b1) == len(b2) return bytes([x ^ y for x, y in zip(b1, b2)])
def bytes_to_int(byte_string) -> int: """ :param byte_string: a string formatted like b'\xd4\x053K\xd8\xea' :return: integer value of the byte stream """ return int.from_bytes(byte_string, "big")
def cross(*args): """ compute cross-product of args """ ans = [] for arg in args[0]: for arg2 in args[1]: ans.append(arg+arg2) return ans #alternatively: #ans = [[]] #for arg in args: #ans = [x+y for x in ans for y in arg] #return ans
def _isSBMLModel(obj): """ Tests if object is a libsbml model """ cls_stg = str(type(obj)) if ('Model' in cls_stg) and ('lib' in cls_stg): return True else: return False
def unique3(s, start, stop): """Return True if there are no duplicates elements in slice s[start:stop].""" if stop - start <= 0: # at most one item return True elif not unique3(s, start, stop - 1): # first part has duplicate return False elif not unique3(s, start + 1, stop): # second part has duplicate return False else: return s[start] != s[stop - 1]
def list_math_addition(a, b): """! @brief Addition of two lists. @details Each element from list 'a' is added to element from list 'b' accordingly. @param[in] a (list): List of elements that supports mathematic addition.. @param[in] b (list): List of elements that supports mathematic addition.. @return (list) Results of addtion of two lists. """ return [a[i] + b[i] for i in range(len(a))]
def process_description(description: str): """ Function to cut the passed in string before \n\n if any Parameters ---------- description: str the passed in string for process Returns ------- str processed string """ if not description: return "No Info Provided" return description.rpartition('\n\n')[0] if "\n\n" in description else description
def non_negative(number: int) -> int: """ :return: Number, or 0 if number is negative """ return max(0, number)
def is_windows_path(path): """Checks if the path argument is a Windows platform path.""" return '\\' in path or ':' in path or '|' in path
def split_section(url): """ Splits into (head, tail), where head contains no '#' and is max length. """ if '#' in url: i = url.index('#') return (url[:i], url[i:]) else: return (url, '')
def home(): """All available api routes.""" return ( f"Available Hawaii Weather Routes:<br/>" f"/api/v1.0/precipitation<br/>" f"/api/v1.0/stations<br/>" f"/api/v1.0/tobs<br/>" f"api/v1.0/<start><br/>" f"api/v1.0/<start>/<end>" )
def relMatches(rel_attr, target_rel): """Does this target_rel appear in the rel_str?""" # XXX: TESTME rels = rel_attr.strip().split() for rel in rels: rel = rel.lower() if rel == target_rel: return 1 return 0
def pad(message_len, group_len, fillvalue): """Return the padding needed to extend a message to a multiple of group_len in length. fillvalue can be a function or a literal value. If a function, it is called once for each padded character. Use this with fillvalue=random_english_letter to pad a message with random letters. """ padding_length = group_len - message_len % group_len if padding_length == group_len: padding_length = 0 padding = '' if callable(fillvalue): for i in range(padding_length): padding += fillvalue() else: padding += fillvalue * padding_length return padding
def _load_file(file): """Load the log file and creates it if it doesn't exist. Parameters ---------- file : str The file to write down Returns ------- list A list of strings. """ try: with open(file, 'r', encoding='utf-8') as temp_file: return temp_file.read().splitlines() except Exception: with open(file, 'w', encoding='utf-8') as temp_file: return []
def listify(item): """ listify a query result consisting of user types returns nested arrays representing user type ordering """ if isinstance(item, (tuple, list)): return [listify(i) for i in item] else: return item
def get_version(v): """ Generate a PEP386 compliant version Stolen from django.utils.version.get_version :param v tuple: A five part tuple indicating the version :returns str: Compliant version """ assert isinstance(v, tuple) assert len(v) == 5 assert v[3] in ('alpha', 'beta', 'rc', 'final') parts = 2 if v[2] == 0 else 3 main = '.'.join(str(i) for i in v[:parts]) sub = '' if v[3] != 'final': mapping = {'alpha': 'a', 'beta': 'b', 'rc': 'c'} sub = mapping[v[3]] + str(v[4]) return str(main + sub)
def min_(xs): """Returns min element (or None if there are no elements)""" if len(xs) == 0: return None else: return min(xs)
def and_sum (phrase): """Returns TRUE iff every element in <phrase> is TRUE""" for x in phrase: if not x: return False return True
def binary_does_not_exist(response): """ Used to figure if the npm, pip, gem binary exists in the container image """ if 'executable file not found in' in response or 'not found' in response \ or 'no such file or directory' in response: return True return False
def dead_zone(controller_input, dead_zone): """Old-style dead zone scaling, required for similar drive behaviour.""" if controller_input <= dead_zone and controller_input >= -dead_zone: return 0 elif controller_input > 0: return ((controller_input-dead_zone)/(1-dead_zone)) else: return ((-controller_input-dead_zone)/(dead_zone-1))
def ImportCinema(filename, view=None): """::deprecated:: 5.9 Cinema import capabilities are no longer supported in this version. """ import warnings warnings.warn("'ImportCinema' is no longer supported", DeprecationWarning) return False
def grid_walk(directions, part_two=False): """Return Manhattan distance of destination or first revisited place.""" x = 0 y = 0 orientation = 0 visited = [[0, 0],] for direction in directions: turn = direction[0] steps = int(direction[1:]) if turn == 'R': orientation = (orientation + 1) % 4 else: orientation = (orientation - 1) % 4 for _ in range(steps): if orientation == 0: y += 1 elif orientation == 1: x += 1 elif orientation == 2: y -= 1 else: x -= 1 if part_two: if [x, y] in visited: return abs(x) + abs(y) else: visited.append([x, y]) return abs(x) + abs(y)
def get_kwcolors(labels, colors): """Generate a dictinary of {label: color} using unique labels and a list of availabel colors """ nc = len(colors) nl = len(labels) n_repeats = int((nl + nc - 1)/nc) colors = list(colors)*n_repeats kw_colors = {l:c for (l,c) in zip(labels, colors)} return kw_colors
def replace_dict_value(d, bad_val, good_val): """ Replaces Dictionary Values whenver bad_val is encountered with good_val """ for k,v in d.items(): if v == bad_val: d[k] = good_val return d
def remove_prefix(string: str, prefix: str) -> str: """ Removes a prefix substring from a given string Params: - `string` - The string to remove the prefix from - `prefix` - The substring to remove from the start of `string` Returns: A copy of `string` without the given `prefix` """ # https://docs.python.org/3/library/stdtypes.html#str.removeprefix return string[len(prefix):]
def time_string(time_seconds): """ Creates a formatted string to express a length of time. Given a value in seconds, the value will be split into hours, minutes, and seconds based on how long that time period is. :param time_seconds: A value of time in seconds. :return: A formatted string expressing the time. """ if time_seconds / 60 >= 1: if time_seconds / 3600 >= 1: # At least one hour time_minutes = time_seconds - (3600 * (time_seconds // 3600)) num_hours = int(time_seconds // 3600) if num_hours == 1: hours_string = "hour" else: hours_string = "hours" num_minutes = int(time_minutes // 60) if num_minutes == 1: minutes_string = "minute" else: minutes_string = "minutes" return "{} {}, {} {}, {:.3f} seconds".format(num_hours, hours_string, num_minutes, minutes_string, time_minutes % 60) else: # At least one minute num_minutes = int(time_seconds // 60) if num_minutes == 1: minutes_string = "minute" else: minutes_string = "minutes" return "{} {}, {:.3f} seconds".format(num_minutes, minutes_string, time_seconds % 60) else: # Less than one minute return "{:.3f} seconds".format(time_seconds)
def strfind(name: str, ch: str) -> list: """Simple function to replicate MATLAB's strfind function""" inds = [] for i in range(len(name)): if name.find(ch, i) == i: inds.append(i) return inds
def clean_thing_description(thing_description: dict) -> dict: """Change the property name "@type" to "thing_type" and "id" to "thing_id" in the thing_description Args: thing_description (dict): dict representing a thing description Returns: dict: the same dict with "@type" and "id" keys are mapped to "thing_type" and "thing_id" """ if "@type" in thing_description: thing_description["thing_type"] = thing_description.pop("@type") if "id" in thing_description: thing_description["thing_id"] = thing_description.pop("id") return thing_description
def validate(config): """ Validate the beacon configuration """ _config = {} list(map(_config.update, config)) # Configuration for log beacon should be a list of dicts if not isinstance(config, list): return False, ("Configuration for log beacon must be a list.") if "file" not in _config: return False, ("Configuration for log beacon must contain file option.") return True, "Valid beacon configuration"
def getShortestPath(source, target, prev, dist): """ Rebuild the shortest path from source to target as a list and its cost Parameters: source (int): the vertex choose as source target (int): the vertex choose as target prev (dict): a dictionary with vertex as key and last previous vertex in the path from the source as value -1 if it is not reachable dist (dict): a dictionary with vertex as key and the total distance from the source as value Returns: path (list): the sequence of nodes covered cost (int): cost of the path """ path = [target] cost = dist[target] # go back from target to source using prev dictionary while target != source: path.append(prev[target]) target = prev[target] path.reverse() return path, cost
def dsub_to_api(job): """Extracts labels from a job, if present. Args: job: A dict with dsub job metadata Returns: dict: Labels key value pairs with dsub-specific information """ labels = job['labels'].copy() if job['labels'] else {} if 'job-id' in job: labels['job-id'] = job['job-id'] if 'task-id' in job: labels['task-id'] = job['task-id'] if 'task-attempt' in job: labels['attempt'] = job['task-attempt'] return labels
def nested_combine(*dicts: dict) -> dict: """Combine an iterable of dictionaries. Each dictionary is combined into a result dictionary. For each key in the first dictionary, it will be overwritten by any same-named key in any later dictionaries in the iterable. If the element at that key is a dictionary, rather than just overwriting we use the same function to combine those dictionaries. Args: *dicts: An iterable of dictionaries to be combined. Returns: `dict`: A combined dictionary from the input dictionaries. """ r: dict = {} for d in dicts: for k in d: if k in r and isinstance(r[k], dict): if isinstance(d[k], dict): r[k] = nested_combine(r[k], d[k]) else: # pragma: no cover raise ValueError( "Key {!r} is a dict in one config but not another! PANIC: " "{!r}".format(k, d[k]) ) else: r[k] = d[k] return r
def flatten_list(list_of_lists): """Will recursively flatten a nested list""" if len(list_of_lists) == 0: return list_of_lists if isinstance(list_of_lists[0], list): return flatten_list(list_of_lists[0]) + flatten_list(list_of_lists[1:]) return list_of_lists[:1] + flatten_list(list_of_lists[1:])
def check_game_status(board): """Return game status by current board status. Args: board (list): Current board state Returns: int: -1: game in progress 0: draw game, 1 or 2 for finished game (winner mark code). """ for t in [1, 2]: for j in range(0, 9, 3): if [t] * 3 == [board[i] for i in range(j, j+3)]: return t for j in range(0, 3): if board[j] == t and board[j+3] == t and board[j+6] == t: return t if board[0] == t and board[4] == t and board[8] == t: return t if board[2] == t and board[4] == t and board[6] == t: return t for i in range(9): if board[i] == 0: # still playing return -1 # draw game return 0
def get_image_type(fileName): """ Get image type. :param fileName: :return: """ if fileName.endswith(".jpg"): return "image/jpeg" elif fileName.endswith(".png"): return "image/png"
def label_index2node(label_index, labels): """ returns the high or medium degree node with a given label index labels contains the output of the label function: the sorted list of high degree nodes with their labels, and the sorted list of medium degree nodes with their labels note that label indices are 0-indexed too """ hi_pairs, med_pairs = labels if label_index < len(hi_pairs): return hi_pairs[label_index][0] else: error_msg = "there is no node with label "+str(label_index) assert label_index-len(hi_pairs) < len(med_pairs), error_msg return med_pairs[label_index-len(hi_pairs)][0]
def parse_line(line): """ line is in the format distance,zipcode,city,state,gender,race,income,price """ line = line.strip().split(",")[1:] # zipcode = str(line[0]) # city = str(line[1]) state = str(line[2]) gender = str(line[3]) race = str(line[4]) income = str(line[5]) price = str(line[6]) return [state, gender, race, income, price]
def get_box_coordinates(box,img_shape): """#convert model coordinates format to (xmin,ymin,width,height) Args: box ((xmin,xmax,ymin,ymax)): the coordinates are relative [0,1] img_shape ((height,width,channels)): the frame size Returns: (xmin,ymin,width,height): (xmin,ymin,width,height): converted coordinates """ height,width, = img_shape[:2] xmin=max(int(box[1]*width),0) ymin=max(0,int(box[0]*height)) xmax=min(int(box[3]*width),width-1) ymax=min(int(box[2]*height),height-1) return ( xmin,#xmin ymin,#ymin xmax-xmin,#box width ymax-ymin#box height )
def pad_base64_str(str): """ Pads the base64 string. """ missing_padding = len(str) % 4 if missing_padding != 0: str += '=' * (4 - missing_padding) return str
def is_valid_byr(birthyear): """Checks for valid Birth Year.""" if birthyear.isdigit() and (1920 <= int(birthyear) <= 2002): return True else: return False
def guess_DMstep(dt, BW, fctr): """Choose a reasonable DMstep by setting the maximum smearing across the 'BW' to equal the sampling time 'dt'. Inputs: dt: sampling time (in seconds) BW: bandwidth (in MHz) fctr: centre frequency (in MHz) """ return dt*0.0001205*fctr**3.0/(BW)
def item_default(list_values, arg): """ Loops over a list and replaces any values that are None, False or blank with arg. """ if list_values: return [item for item in list_values if item ] else: return []
def human_size(bytes): """Return number of bytes as string with most appropriate unit.""" if bytes == 0: return '0 B' suffixes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'YB'] bytes = float(bytes) i = 0 while bytes >= 1024 and i < (len(suffixes) - 1): bytes /= 1024.0 i += 1 if i > 2: f = '{:0.2f}'.format(bytes) else: f = '{:0.1f}'.format(bytes) f = f.rstrip('0').rstrip('.') return '{} {}'.format(f, suffixes[i])
def get_top_keywords(keywords_dict, top_n): """ Used to get the top results to display for keyword filtering Given a dictionary of keywords as keys and the number of times that keyword is linked to a statement in the search results: {Iraq : 300} Returns the top n results as as list of pairs, ordered by appearances: [(Iraq, 300), (Iran, 200)] """ return sorted(keywords_dict.items(), key=lambda student: student[1], reverse=True)[ :top_n ]
def split_name(name): """ Split a long form name like "Derrick J Schommer" into "Derrick" and "J Schommer". The Shopify system uses one long name field, where WooCommerce uses 2 fields for first and last name (and we'll just stuff all the extra letters into the second field if they have middle initials, or are a Jr. or III, etc.) Parameters ---------- name: The name of the customer like "Derrick Schommer" or "Derrick J Schommer III" Returns ------- str, str : returns two strings, the first name and the rest (as last name) """ first_name = "" last_name = "" # Split name by spaces as most humans do (at least many languages) name_array = name.split(" ") first_name = name_array[0] if len(name_array) > 1: # Oh yay, seems the customer has a last name :-) name_array.pop(0) # kick the first name out. last_name = ' '.join([str(elem) for elem in name_array]) return (first_name, last_name)
def camelize(name): """Turns snake_case name into SnakeCase.""" return ''.join([bit.capitalize() for bit in name.split('_')])
def test_none(*args): """Returns true if any of the arguments are None.""" for x in args: if x is None: return True return False
def get_list_elem(obj, idx, dft): """ Returns element at index or default :param obj: list :param idx: index :param dft: default value :return: element """ if len(obj) - 1 < idx: return dft return obj[idx]
def to_int(raw_value, default=0): """ Safely parse a raw value and convert to an integer. If that fails return the default value. :param raw_value: the raw value :param default: the fallback value if conversion fails :return: the value as int or None """ try: return int(float(raw_value)) except (ValueError, TypeError): return default
def _is_ref(schema): """ Given a JSON Schema compatible dict, returns True when the schema implements `$ref` NOTE: `$ref` OVERRIDES all other keys present in a schema :param schema: :return: Boolean """ return '$ref' in schema
def long_tail_reversal(close, open, high, low, trend='up', daily_movement_minimum=0.01): """ try to detect if a chandle stick fall in the pattern of a doji, long-shadow and hammer :daily_movement_minimum: default to 0.01 (1%) """ detected = False mid_point_magnatude_scaling = 0.8 # the move range needs to be large than percentage of open price if abs((high - low)) / open < daily_movement_minimum: return False if trend == 'up': mid_point = (high - low) / 2.0 * mid_point_magnatude_scaling + low # both open and close need to above mid-point if open >= mid_point and close >= mid_point: detected = True else: mid_point = (high - low) / 2.0 * ( 1 + (1 - mid_point_magnatude_scaling)) + low if open <= mid_point and close <= mid_point: detected = True return detected
def remap_unbound(input_val, in_from, in_to, out_from, out_to): """ Remaps input_val from source domain to target domain. No clamping is performed, the result can be outside of the target domain if the input is outside of the source domain. """ out_range = out_to - out_from in_range = in_to - in_from in_val = input_val - in_from val = (float(in_val) / in_range) * out_range out_val = out_from + val return out_val
def _TopImprovements(recent_anomalies, num_to_show): """Fills in the given template dictionary with top improvements. Args: recent_anomalies: A list of Anomaly entities sorted from large to small. num_to_show: The number of improvements to return. Returns: A list of top improvement Anomaly entities, in decreasing order. """ improvements = [a for a in recent_anomalies if a.is_improvement] return improvements[:num_to_show]
def get_attrname(name): """Return the mangled name of the attribute's underlying storage.""" return '_obj_' + name
def get_phone_number(phone_number): """ Following suggested RFC 3966 protocol by open id expect: +111-1111-111111 format """ if '-' in phone_number: phone_split = phone_number.split('-') if len(phone_split) > 2: #if had country code return phone_split[2] return phone_split[1] return phone_number
def is_same_tree(p, q): """ Given two binary trees, write a function to check if they are the same or not. Two binary trees are considered the same if they are structurally identical and the nodes have the same value. Args: p: TreeNode q: TreeNode Returns: bool """ # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None if p and q: return p.val == q.val and is_same_tree(p.left, q.left) and is_same_tree(p.right, q.right) return p is q
def degToDMS(g): """ Convert degrees into arc units (degrees, (arc)minutes, (arc)seconds) Parameters ---------- g : float Value in degrees. Returns ------- d, m, s, sign : float, int Degrees, (arc)minutes, and (arc)seconds. Note that only the degree number is signed. The sign (+1/-1) is also returned to yield a complete result if the value of degree (d) is zero. """ sign = 1 if g < 0.0: sign = -1 g = abs(g) d = int(g) * sign g = g - int(g) m = int(g * 60.0) g = g - m / 60.0 s = g * 3600.0 return d, m, s, sign
def list_to_string(l: list, s: str = "\n") -> str: """Transforms a list into a string. The entries of the list are seperated by a seperator. Args: l (list): the list s (str, optional): the seperator. Defaults to "\\n". Returns: str: the list representation with seperator """ r = "" for e in l: r += e + s return r
def is_int(data): """Checks if data is an integer.""" return isinstance(data, int)
def find_key(wkt, k): """ Find a key in the wkt, return it's name and items. .. versionadded:: 9.2 """ for w in wkt: if type(w) is dict: if w['key'] == k: return w['name'], w.get('items', []) # try the kids name, items = find_key(w.get('items', []), k) if name: return name, items return '', []
def chao1_var_no_doubletons(singles, chao1): """Calculates chao1 variance in absence of doubletons. From EstimateS manual, equation 7. chao1 is the estimate of the mean of Chao1 from the same dataset. """ s = float(singles) return s*(s-1)/2 + s*(2*s-1)**2/4 - s**4/(4*chao1)
def drop_nulls_in_dict(d): # d: dict """Drops the dict key if the value is None ES mapping does not allow None values and drops the document completely. """ return {k: v for k, v in d.items() if v is not None}
def get_table_tree(form): """return a list consisting of multiple lists""" table=[] if len(form) : while form[0] : table.append( get_table_tree( form[1:] ) ) form[0]-=1 return table else : return []
def get_spaceweather_imagefile(if_path, if_date, if_filename, if_extension, \ verbose): """Returns a complete image filename string tailored to the spaceweather site string by concatenating the input image filename (if) strings that define the path, date, filename root, and the filename extension If verbose is truthy, then print the returned image filename string """ sw_imagefile = if_path + if_date + "_" + if_filename + if_extension if verbose: print("Output image file full path: \n{}\n".format(sw_imagefile)) return sw_imagefile
def port_status_change(port, original): """ Checks whether a port update is being called for a port status change event. Port activation events are triggered by our own action: if the only change in the port dictionary is activation state, we don't want to do any processing. """ # Be defensive here: if Neutron is going to use these port dicts later we # don't want to have taken away data they want. Take copies. port = port.copy() original = original.copy() port.pop('status') original.pop('status') if port == original: return True else: return False
def check_cake_order_sequence(take_out, dine_in, served_orders): """Checks that the sequence of served_order is first-come, first-served""" take_out_index = 0 dine_in_index = 0 for i in range(0, len(served_orders)): if take_out[take_out_index] == served_orders[i]: take_out_index += 1 elif dine_in[dine_in_index] == served_orders[i]: dine_in_index += 1 else: return False return True
def subreddit_search_key(sr): """Search key for subreddit.""" return sr['name'] # return '{} {}'.format(sr['name'], sr['title'])
def extract_options(name): """ Extracts comparison option from filename. As example, ``Binarizer-SkipDim1`` means options *SkipDim1* is enabled. ``(1, 2)`` and ``(2,)`` are considered equal. Available options: see :func:`dump_data_and_model`. """ opts = name.replace("\\", "/").split("/")[-1].split('.')[0].split('-') if len(opts) == 1: return {} res = {} for opt in opts[1:]: if opt in ("SkipDim1", "OneOff", "NoProb", "NoProbOpp", "Dec4", "Dec3", "Dec2", 'Svm', 'Out0', 'Reshape', 'SklCol', 'DF', 'OneOffArray'): res[opt] = True else: raise NameError("Unable to parse option '{}'".format( opts[1:])) # pragma no cover return res
def is_deriv_in(coll: list): """Check to see if there are any derivatives acting on fields in `coll`.""" for f in coll: if str(f)[0] == "D": return True return False
def formatPages(pages): """One or more page numbers or range of numbers, such as 42-111 or 7,41,73-97 or 43+ (the `+' in this last example indicates pages following that don't form a simple range). To make it easier to maintain Scribe-compatible databases, the standard styles convert a single dash (as in 7-33) to the double dash used in TEX to denote number ranges (as in 7-33).""" #check -- or ---- or - return pages
def round_to_odd(x): """ :param x: some number (float or int) :return: nearst odd integer """ return int(round((x - 1) / 2) * 2 + 1)
def convert_symbol(text, l1, l2, quote='"'): """convert symbol l1 to l2 if inside quote""" text2 = '' inside = False for c in text: if c == quote: inside = not inside elif c == l1: if inside: text2 += l2 else: text2 += l1 else: text2 += c return text2
def is_dask_collection(x): """Returns ``True`` if ``x`` is a dask collection""" try: return x.__dask_graph__() is not None except (AttributeError, TypeError): return False
def to_pairs(object): """Converts an object into an array of key, value arrays. Only the object's own properties are used. Note that the order of the output array is not guaranteed to be consistent across different JS platforms""" return [list(x) for x in object.items()]
def reverse_iter(lst): """Returns the reverse of the given list. >>> reverse_iter([1, 2, 3, 4]) [4, 3, 2, 1] >>> import inspect, re >>> cleaned = re.sub(r"#.*\\n", '', re.sub(r'"{3}[\s\S]*?"{3}', '', inspect.getsource(reverse_iter))) >>> print("Do not use lst[::-1], lst.reverse(), or reversed(lst)!") if any([r in cleaned for r in ["[::", ".reverse", "reversed"]]) else None """ "*** YOUR CODE HERE ***" rev_list = [] for num in lst: rev_list = [num] + rev_list return rev_list
def calc_timeleft(bytesleft, bps): """ Calculate the time left in the format HH:MM:SS """ try: if bytesleft <= 0: return '0:00:00' totalseconds = int(bytesleft / bps) minutes, seconds = divmod(totalseconds, 60) hours, minutes = divmod(minutes, 60) days, hours = divmod(hours, 24) if minutes < 10: minutes = '0%s' % minutes if seconds < 10: seconds = '0%s' % seconds if days > 0: if hours < 10: hours = '0%s' % hours return '%s:%s:%s:%s' % (days, hours, minutes, seconds) else: return '%s:%s:%s' % (hours, minutes, seconds) except: return '0:00:00'
def get_collection_and_suffix(collection_name): """ Lookup collection and suffix based on the name of the collection as used by GEE Parameters ========== collection_name: str, GEE name of the collection, eg. 'COPERNICUS/S2' Returns ======= collection: str, user-friendly name of the collection, e.g. 'Sentinel2' suffix: str, contraction of collection name, used in the filenames of plots """ if collection_name == 'COPERNICUS/S2': collection = 'Sentinel2' satellite_suffix = 'S2' elif collection_name == 'LANDSAT8': collection = 'Landsat8' satellite_suffix = 'L8' elif collection_name == 'LANDSAT7': collection = 'Landsat7' satellite_suffix = 'L7' elif collection_name == 'LANDSAT5': collection = 'Landsat5' satellite_suffix = 'L5' elif collection_name == 'LANDSAT4': collection = 'Landsat4' satellite_suffix = 'L4' else: raise RuntimeError("Unknown collection_name {}".format(collection_name)) return collection, satellite_suffix
def to_ymd(s): """take a string of the form "YYYY-MM-DD" (or "YYYY"), terurn a tuple (year, month, date) of three integers""" if not s: return s = s + '--' y = s.split('-')[0] m = s.split('-')[1] d = s.split('-')[2] if y: y = int(y) else: y = None if m: m = int(m) else: m = None if d: d = int(d) else: d = None return (y, m, d)
def tupleinsert(tpl, val, idx): """ Return a tuple with *val* inserted into position *idx* """ lst = list(tpl[:idx]) + [val] + list(tpl[idx:]) return tuple(lst)
def reg2bin(rbeg, rend): """Finds the largest superset bin of region. Numeric values taken from hts-specs Args: rbeg (int): inclusive beginning position of region rend (int): exclusive end position of region Returns: (int): distinct bin ID for largest superset bin of region """ left_shift = 15 for i in range(14, 27, 3): if rbeg >> i == (rend - 1) >> i: return int(((1 << left_shift) - 1) / 7 + (rbeg >> i)) left_shift -= 3 else: return 0
def rewrite_attribute_name(name, default_namespace='html'): """ Takes an attribute name and tries to make it HTML correct. This function takes an attribute name as a string, as it may be passed in to a formatting method using a keyword-argument syntax, and tries to convert it into a real attribute name. This is necessary because some attributes may conflict with Python reserved words or variable syntax (such as 'for', 'class', or 'z-index'); and also to help with backwards compatibility with older versions of MoinMoin where different names may have been used (such as 'content_id' or 'css'). Returns a tuple of strings: (namespace, attribute). Namespaces: The default namespace is always assumed to be 'html', unless the input string contains a colon or a double-underscore; in which case the first such occurance is assumed to separate the namespace prefix from name. So, for example, to get the HTML attribute 'for' (as on a <label> element), you can pass in the string 'html__for' or even '__for'. Hyphens: To better support hyphens (which are not allowed in Python variable names), all occurances of two underscores will be replaced with a hyphen. If you use this, then you must also provide a namespace since the first occurance of '__' separates a namespace from the name. Special cases: Within the 'html' namespace, mainly to preserve backwards compatibility, these exceptions ars recognized: 'content_type', 'content_id', 'css_class', and 'css'. Additionally all html attributes starting with 'on' are forced to lower-case. Also the string 'xmlns' is recognized as having no namespace. Examples: 'id' -> ('html', 'id') 'css_class' -> ('html', 'class') 'content_id' -> ('html', 'id') 'content_type' -> ('html', 'type') 'html__for' -> ('html', 'for) 'xml__space' -> ('xml', 'space') '__z__index' -> ('html', 'z-index') '__http__equiv' -> ('html', 'http-equiv') 'onChange' -> ('html', 'onchange') 'xmlns' -> ('', 'xmlns') 'xmlns__abc' -> ('xmlns', 'abc') (In actuality we only deal with namespace prefixes, not any real namespace URI...we only care about the syntax not the meanings.) """ # Handle any namespaces (just in case someday we support XHTML) if ':' in name: ns, name = name.split(':', 1) elif '__' in name: ns, name = name.split('__', 1) elif name == 'xmlns': ns = '' else: ns = default_namespace name.replace('__', '-') if ns == 'html': # We have an HTML attribute, fix according to DTD if name == 'content_type': # MIME type such as in <a> and <link> elements name = 'type' elif name == 'content_id': # moin historical convention name = 'id' elif name in ('css_class', 'css'): # to avoid python word 'class' name = 'class' elif name.startswith('on'): # event handler hook name = name.lower() return ns, name
def set_digital_out(id, signal): """ Function that returns UR script for setting digital out Args: id: int. Input id number signal: boolean. signal level - on or off Returns: script: UR script """ # Format UR script return "set_digital_out({:d}, {})\n".format(id, signal)
def _knapsack(weights, capacity): """ Binary knapsack solver with identical profits of weight 1. Args: weights (list) : list of integers capacity (int) : maximum capacity Returns: (int) : maximum number of objects """ n = len(weights) # sol : [items, remaining capacity] sol = [[0] * (capacity + 1) for i in range(n)] added = [[False] * (capacity + 1) for i in range(n)] for i in range(n): for j in range(capacity + 1): if weights[i] > j: sol[i][j] = sol[i - 1][j] else: sol_add = 1 + sol[i - 1][j - weights[i]] if sol_add > sol[i - 1][j]: sol[i][j] = sol_add added[i][j] = True else: sol[i][j] = sol[i - 1][j] return sol[n - 1][capacity]
def _cc(recipient): """ Returns a query item matching messages that have certain recipients in the cc field. Args: recipient (str): The recipient in the cc field to match. Returns: The query string. """ return f"cc:{recipient}"
def pt_time_estimation(position_0, position_1, pan_speed=22.5, tilt_speed=6.5, unit=1e-2): """ Estimation of time to go from position_0 to position_1 FIXME : Does not take into account forbidden angle, and rotation direction neither (shortest path is chosen) works with """ if position_0 is None or position_1 is None: return pan0, tilt0 = position_0 pan1, tilt1 = position_1 return unit * max(abs(pan1-pan0)/pan_speed, abs(tilt1-tilt0)/tilt_speed)
def normalizeHomogenious(points): """ Normalize a collection of points in homogeneous coordinates so that last row = 1. """ for row in points: row /= points[-1] return points