content
stringlengths
42
6.51k
def curly(content): """ Generate LaTeX code for data within curly braces. Parameters ---------- content : str String to be encapsulated within the curly braces. Returns ------- str LaTeX code for data within curly braces. """ return "\\{" + content + "\\}"
def having_sum_recursive(number: int) -> int: """Returns all elements of the sum are the results of integer division. Args: number (int): a number to get divisible from Examples: >>> assert having_sum_recursive(25) == 47 """ if number == 1: return 1 return number + having_sum_recursive(number // 2)
def bearer_token(token): """ Returns content of authorization header to be provided on all non-auth API calls. :param token: access_token returned from authorization call. :return: Formatted header. """ return 'Bearer {}'.format(token)
def is_null(content, nulls=None, blanks_as_nulls=False): """Determines whether or not content can be converted into a null Args: content (scalar): the content to analyze nulls (Seq[str]): Values to consider null. blanks_as_nulls (bool): Treat empty strings as null (default: False). Examples: >>> is_null('n/a') True >>> is_null(None) True """ def_nulls = ("na", "n/a", "none", "null", ".") nulls = set(map(str.lower, nulls) if nulls else def_nulls) try: passed = content.lower() in nulls except AttributeError: passed = content is None try: if not (passed or content.strip()): passed = blanks_as_nulls except AttributeError: pass return passed
def is_karpekar(n): """ defines wheter given number is karpekar number or not. """ n_square = n**2 len_of_n = len(str(n)) l = str(n_square)[-(len_of_n):] r = str(n_square)[:-(len_of_n)] if r == '': r = 0 if (int(l) + int(r) == n): return True return False
def csum2(numlist): """ 3. Write a Python program of recursion list sum. Go to the editor Test Data: [1, 2, [3,4], [5,6]] Expected Result: 21 """ if len(numlist) == 1: return numlist[0] if isinstance(numlist[0], list): return csum2(numlist[0]) + csum2(numlist[1:]) else: return numlist[0] + csum2(numlist[1:])
def get_output_file_name(infile_name): """Parse input file name to replace text after first dot with 'nc'""" split_str = infile_name.split('.') return split_str[0] + '.nc'
def get_sub_vs_list_from_data(response_data): """Get Sub VS IDs and the "Rs" data portion of the Sub VSs as a tuple :param response_data: Data portion of LM API response :return: Tuple of list of sub VS IDs and a dict of full RS sub VS data """ subvs_entries = [] full_data = {} for key, value in response_data.items(): if key == "SubVS": if isinstance(value, list): for subvs in value: full_data[subvs['VSIndex']] = subvs subvs_entries.append(subvs['VSIndex']) else: full_data[value['VSIndex']] = value subvs_entries.append(value['VSIndex']) return subvs_entries, full_data
def first_non_null(*iterable): """ Returns the first element from the iterable which is not None. If all the elements are 'None', 'None' is returned. :param iterable: Iterable containing list of elements. :return: First non-null element, or None if all elements are 'None'. """ return next((item for item in iterable if item is not None), None)
def _get_id2line(team_stats): """ team_stats: { 'headers':[], 'data': [[],[]] # two teams, don't know which is home/away } """ headers = team_stats['headers'] id_loc = headers.index('TEAM_ID') data0 = team_stats['data'][0] data1 = team_stats['data'][1] try: assert len(headers) == len(data0) == len(data1) except AssertionError: print( "WARNING: line scores of the two teams are incomplete: \nheaders (#={}) = {}\ndata0 (#={}): \n{}\ndata1 (#={}): \n{}".format( headers, len(headers), data0, len(data0), data1, len(data1))) return None id2line = { data0[id_loc]: {k: v for k, v in zip(headers, data0)}, data1[id_loc]: {k: v for k, v in zip(headers, data1)}, } return id2line
def floats_equal(x, y): """A deeply inadequate floating point comparison.""" small = 0.0001 if x == y or x < small and y < small: return True epsilon = max(abs(x), abs(y)) * small return abs(x - y) < epsilon
def overlay_line(base, line): """Overlay a line over a base line ' World ' overlayed over 'Hello ! ! !' would result in 'Hello World!' """ escapes = [('', 0)] if '\x1b' in line: # handling ANSI codes nl = "" while '\x1b' in line: i = line.index('\x1b') nl += line[:i] line = line[i:] escapes.append((line[:line.index('m') + 1], i + escapes[-1][1])) line = line[line.index('m') + 1:] nl += line line = nl if len(line) > len(base): # if overlay line exceeds base line, cut excess line = line[:len(base)] for n, char in enumerate(line): if not char.isspace(): base = base[:n] + char + base[n + 1:] if len(escapes) > 1: inserts = 0 for x in escapes[1:]: base = base[:x[1] + inserts] + x[0] + base[inserts + x[1]:] inserts += len(x[0]) return base
def is_number(n): """ This function checks if n can be coerced to a floating point. Args: n (str): Possibly a number string """ try: float(n) return True except: return False
def _synda_search_cmd(variable): """Create a synda command for searching for variable.""" project = variable.get('project', '') if project == 'CMIP5': query = { 'project': 'CMIP5', 'cmor_table': variable.get('mip'), 'variable': variable.get('short_name'), 'model': variable.get('dataset'), 'experiment': variable.get('exp'), 'ensemble': variable.get('ensemble'), } elif project == 'CMIP6': query = { 'project': 'CMIP6', 'activity_id': variable.get('activity'), 'table_id': variable.get('mip'), 'variable_id': variable.get('short_name'), 'source_id': variable.get('dataset'), 'experiment_id': variable.get('exp'), 'variant_label': variable.get('ensemble'), 'grid_label': variable.get('grid'), } else: raise NotImplementedError( f"Unknown project {project}, unable to download data.") query = {facet: value for facet, value in query.items() if value} query = ("{}='{}'".format(facet, value) for facet, value in query.items()) cmd = ['synda', 'search', '--file'] cmd.extend(query) cmd = ' '.join(cmd) return cmd
def _pop_rotation_kwargs(kwargs): """Pop the keys responsible for text rotation from `kwargs`.""" ROTATION_ARGS = {"ha", "rotation_mode"} rotation = kwargs.pop("rotation", None) rotation_kwargs = {arg: kwargs.pop(arg) for arg in ROTATION_ARGS if arg in kwargs} if rotation is not None: rotation_kwargs = {"rotation": rotation, "ha": "right", "rotation_mode": "anchor", **rotation_kwargs} return rotation_kwargs
def valid_index(index, shape): """Get a valid index for a broadcastable shape. Parameters ---------- index : tuple Given index. shape : tuple of int Shape. Returns ------- tuple Valid index. """ # append slices to index index = list(index) while len(index) < len(shape): index.append(slice(None)) # fill out, in reverse out = [] for i, s in zip(index[::-1], shape[::-1]): if s == 1: if isinstance(i, slice): out.append(slice(None)) else: out.append(0) else: out.append(i) return tuple(out[::-1])
def conv_connected_inputs(input_shape, kernel_shape, output_position, strides, padding): """Return locations of the input connected to an output position. Assume a convolution with given parameters is applied to an input having N spatial dimensions with `input_shape = (d_in1, ..., d_inN)`. This method returns N ranges specifying the input region that was convolved with the kernel to produce the output at position `output_position = (p_out1, ..., p_outN)`. Example: ```python >>> input_shape = (4, 4) >>> kernel_shape = (2, 1) >>> output_position = (1, 1) >>> strides = (1, 1) >>> padding = "valid" >>> conv_connected_inputs(input_shape, kernel_shape, output_position, >>> strides, padding) [xrange(1, 3), xrange(1, 2)] ``` Args: input_shape: tuple of size N: `(d_in1, ..., d_inN)`, spatial shape of the input. kernel_shape: tuple of size N, spatial shape of the convolutional kernel / receptive field. output_position: tuple of size N: `(p_out1, ..., p_outN)`, a single position in the output of the convolution. strides: tuple of size N, strides along each spatial dimension. padding: type of padding, string `"same"` or `"valid"`. Returns: N ranges `[[p_in_left1, ..., p_in_right1], ..., [p_in_leftN, ..., p_in_rightN]]` specifying the region in the input connected to output_position. """ ranges = [] ndims = len(input_shape) for d in range(ndims): left_shift = int(kernel_shape[d] / 2) right_shift = kernel_shape[d] - left_shift center = output_position[d] * strides[d] if padding == 'valid': center += left_shift start = max(0, center - left_shift) end = min(input_shape[d], center + right_shift) ranges.append(range(start, end)) return ranges
def _varbase(values, period=None, population=False): """ Returns final variance. :param values: list of values to iterate and compute stat. :param period: (optional) # of values included in computation. * None - includes all values in computation. :param population: * True - entire population, n. * False - sample set, n - 1 (default). Examples: >>> values = [32.47, 32.70, 32.77, 33.11, 33.25, 33.23, 33.23] >>> result = _varbase(values, 3, population=True) >>> print "%.2f" % result 0.00 """ if not values: return None maxbar = len(values) beg = 0 if period: if period < 1: raise ValueError("period must be 1 or greater") beg = maxbar - int(period) if beg < 0: beg = 0 itemcnt = len(values[beg:]) if itemcnt < 2: return 0.0 sample_adjust = 0.0 if not population: sample_adjust = 1.0 n = 0 meandiffs = 0.0 mean = 0.0 for x in values[beg:]: n += 1 delta = x - mean mean += delta / n meandiffs += delta * (x - mean) return meandiffs / (itemcnt - sample_adjust)
def correctHeading(x, headingCorrection): """ corrects a given column of directional data with the given headingCorrection """ if x + headingCorrection > 360: return (x + headingCorrection) - 360 else: return x + headingCorrection
def hermiteInterpolate(v0, v1, v2, v3, alpha, tension, bias): """ Hermite interpolator. Allows better control of the bends in the spline by providing two parameters to adjust them: * tension: 1 for high tension, 0 for normal tension and -1 for low tension. * bias: 1 for bias towards the next segment, 0 for even bias, -1 for bias towards the previous segment. Using 0 bias gives a cardinal spline with just tension, using both 0 tension and 0 bias gives a Catmul-Rom spline. """ alpha2 = alpha * alpha alpha3 = alpha2 * alpha m0 = (((v1 - v0) * (1 - tension)) * (1 + bias)) / 2.0 m0 += (((v2 - v1) * (1 - tension)) * (1 - bias)) / 2.0 m1 = (((v2 - v1) * (1 - tension)) * (1 + bias)) / 2.0 m1 += (((v3 - v2) * (1 - tension)) * (1 - bias)) / 2.0 a0 = 2 * alpha3 - 3 * alpha2 + 1 a1 = alpha3 - 2 * alpha2 + alpha a2 = alpha3 - alpha2 a3 = -2 * alpha3 + 3 * alpha2 return a0 * v1 + a1 * m0 + a2 * m1 + a3 * v2
def _lt_from_gt(self, other): """Return a < b. Computed by @total_ordering from (not a > b) and (a != b).""" op_result = self.__gt__(other) if op_result is NotImplemented: return NotImplemented return not op_result and self != other
def abbreviate_str(string, max_len=80, indicator="..."): """ Abbreviate a string, adding an indicator like an ellipsis if required. """ if not string or not max_len or len(string) <= max_len: return string elif max_len <= len(indicator): return string[0:max_len] else: return string[0:max_len - len(indicator)] + indicator
def check_int(value: int) -> bool: """Check whether value can be written as 2^p * 5^q where p and q are natural numbers.""" if value == 1: return True else: if value % 2 == 0: return check_int(value//2) if value % 5 == 0: return check_int(value//5) return False
def get_app_details_hr(app_dict): """ Prepare application detail dictionary for human readable in 'risksense-get-app-detail' command. :param app_dict: Dictionary containing application detail. :return: List containing application detail dictionary. """ return [{ 'Address': app_dict.get('uri', ''), 'Name': app_dict.get('name', ''), 'Network Name': app_dict.get('network', {}).get('name', ''), 'Network Type': app_dict.get('network', {}).get('type', ''), 'Discovered On': app_dict.get('discoveredOn', ''), 'Last Found On': app_dict.get('lastFoundOn', '') }, {}]
def convert_dict_to_list(dictionary): """ Accepts a dictionary and return a list of lists. @example: input : { "python" : 50, "json": 100, "text" : 20} output : [['python', 50], ['json', 100], ['text', 20]] """ output_list = [] for k in dictionary.keys(): output_list.append([k, dictionary[k]]) return output_list
def _inc_time(t: int, type_str: str = 'nano') -> int: """Increment time at aprrox rate of 10Hz.""" return int(t + 1e8) if type_str == 'nano' else t + 100
def single_to_list(recipients): """ Ensure recipients are always passed as a list """ if isinstance(recipients, str): return [recipients] return recipients
def check_stc_order(order, symbol): """Return order id if order has an in-effect STC order for input symbol, else return None""" if order["status"] in ["WORKING", "QUEUED", "ACCEPTED"]: if len(order["orderLegCollection"]) == 1: # no multi-leg orders instruct = order["orderLegCollection"][0]["instruction"] ord_symbol = order["orderLegCollection"][0]["instrument"]["symbol"] if ord_symbol == symbol and instruct == "SELL_TO_CLOSE": return str(order["orderId"])
def clean_depparse(dep): """ Given a dependency dictionary, return a formatted string representation. """ return str(dep['dep'] + "(" + dep['governorGloss'].lower() + "-" + str(dep['governor']) + ", " + dep['dependentGloss'] + "-" + str(dep['dependent']) + ")")
def version_string(version): """ Converts a version number into a version string :param version: The version number from the firmware :returns str -- The version string """ major_version = version >> 0x10 minor_version = version & 0xFFFF return '%d.%d' % (major_version, minor_version)
def coor(n,a,b): """ Calculates a list of coordinates using a for loop Parameters ---------- n: integer number of coordinates to use between endpoints a: float starting point b: float ending point Returns ------- coordinates: list list of n coordinates between the beginning point and including the endpoint spacing the interval into n+1 equal subdivisions """ coordinates = [] length = (b-a)/float(n+1) for i in range(n+1): coordinates.append(a + length * (i + 1)) return coordinates
def sort_range(lines, r=None): """ >>> a = sorted(range(10), reverse=True) >>> sort_range(a, (1, 1)) [9, 8, 7, 6, 5, 4, 3, 2, 1, 0] >>> sort_range(a, (1, 2)) [9, 7, 8, 6, 5, 4, 3, 2, 1, 0] >>> sort_range(a, (0, 2)) [7, 8, 9, 6, 5, 4, 3, 2, 1, 0] >>> sort_range(a) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> sort_range(a, (0, 5)) [4, 5, 6, 7, 8, 9, 3, 2, 1, 0] """ start, end = r or (0, len(lines)) return lines[:start] + sorted(lines[start: end + 1]) + lines[end + 1:]
def dunder_to_chained_attrs(value, key): """ If key is of the form "foo__bar__baz", then return value.foo.bar.baz """ if '__' not in key: return getattr(value, key) first_key, rest_of_keys = key.split('__', 1) first_val = getattr(value, first_key) return dunder_to_chained_attrs(first_val, rest_of_keys)
def string_for_attrs(attrs): """Returns string describing tag attributes in the order given.""" if not attrs: return '' return ''.join(' %s="%s"' % (attr, value) for attr, value in attrs)
def heatcap(x, T): """ Calculate heat capacity of wood at temperature and moisture content. Example: cp = heatcap(12, 300) Inputs: x = moisture content, % T = temperature, K Output: cp_wet = heat capacity wet wood, kJ/(kg*K) Reference: Glass and Zelinka, 2010. Wood Handbook, Ch. 4, pp. 1-19. """ cpw = 4.18 # heat capacity of water, kJ/(kg*K) # coefficients for adjustment factor Ac b1 = -0.06191 b2 = 2.36e-4 b3 = -1.33e-4 # adjustment factor for additional energy in wood-water bond, Eq. 4-18 Ac = x*(b1 + b2*T + b3*x) # heat capacity of dry wood, Eq. 4-16a, kJ/(kg*K) cp_dry = 0.1031 + 0.003867*T # heat capacity of wood that contains water, Eq. 4-17, kJ/(kg*K) cp_wet = (cp_dry + cpw*x/100) / (1 + x/100) + Ac return cp_wet
def _getReadHitsSep(cells, readCol, hitCol, hitSep): """ use hitSep to divide hit cell in to multipl hits """ read = cells[readCol] hitCell = cells[hitCol] hits = hitCell.strip().split(hitSep) return (read, hits)
def fibonacciRecursion(sequenceNumber): """ A recursive Algorithm that gets a number from fibonacci sequence at certain point in sequence Args: sequenceNumber {integer} the place in the sequence to get the number from Return: {integer} the number from fibonacci sequence """ if(sequenceNumber<0): return 0 if(sequenceNumber<2): return 1 else: previousNumb = (fibonacciRecursion(sequenceNumber-1)) secondPreviousNumb = (fibonacciRecursion(sequenceNumber-2)) return previousNumb + secondPreviousNumb
def groupID_callback(x): """ image_name = 1_1-1256_1264_2461_2455-12003110450161(_1).jpg big_image_name = 12003110450161 """ img_path = x['info']['image_path'] big_img_name = img_path.split('.')[-2] big_img_name = big_img_name.split('-')[-1].split('_')[0] return big_img_name
def r(x, y, Xi, Yi): """ Return the distance between (x, y) and (Xi, Yi) """ return ((x-Xi)**2 + (y - Yi)**2)**0.5
def fatorial(num,show=False): """ -> CALCULA O FATORIAL DE UM NUMERO :param num: o numero a ser calculado :param show: mostra ou nao calculo :return: retorna o resultado """ f = 1 for c in range(num,0, -1): if show : print(c, end='') if c > 1: print(' x ', end=' ') else: print(' = ', end=' ') f *= c return f
def _is_number(x): """ True if x is numeric i.e. int or float """ from numbers import Number return isinstance(x, Number)
def csv_list(string): """Helper method for having CSV argparse types. Args: string(str): Comma separated string to parse. Returns: list[str]: The parsed strings. """ return string.split(',')
def is_pattern(s): """ Returns *True* if the string *s* represents a pattern, i.e., if it contains characters such as ``"*"`` or ``"?"``. """ return "*" in s or "?" in s
def _get_path_on_disk(inputs, properties): """Returns the path as defined in the volume definition """ disk_path = "" for search in inputs.values(): try: if isinstance(search["path"], str): disk_path = search["path"] break except (KeyError, TypeError): pass else: disk_path = properties.get("path", "") return disk_path
def nullBasedArray(length): """ Returns an array with the given length filled with zeros """ array = [] for i in range (0,length): array.append(0) return array
def infer_type(value, variable=None): """ Tries to infer the type of a variable, based on the default value if given. """ if value in ['T', 'F']: return 'bool' try: throwaway = int(value) return 'int' except ValueError: pass try: throwaway = float(value) return 'float' except ValueError: pass return 'None'
def clean_leetcode(tree: str) -> str: """ >>> clean_leetcode("[1,2,3,null,4]") '1,2,3,None,4,None,None' """ arr = tree[1:-1].replace("null", "None").split(",") height, max_nodes = 0, 1 while len(arr) > max_nodes: height += 1 max_nodes = 2 ** (height + 1) - 1 while len(arr) < max_nodes: arr.append("None") return ",".join(arr)
def sanitize(sinput): """Sanitize `sinput`.""" return " ".join(sinput.split())
def uniquify(l): """Takes a list `l` and returns a list of the unique elements in `l` in the order in which they appeared. """ mem = set([]) out = [] for e in l: if e not in mem: mem.add(e) out.append(e) return out
def producer(number, fib_list): """ Returns the #num fibonacci number using recursion :param number: current number :param fib_list: pointer to shared list of fibonacci numbers """ # If the number has already been computed if fib_list[number] != -1: return fib_list[number] if number <= 1: fib_list[number] = number else: fib_list[number] = producer(number - 1, fib_list) + producer(number - 2, fib_list) return fib_list[number]
def complement(i,j,k): """ Input: i,j elements of {1,2,3,4} returns the only element of (1,2,3,4) not in the SET {i,j} """ list=[1,2,3,4] list.remove(i) list.remove(j) list.remove(k) return list[0]
def check_present_students(students, k): """ :type students: list[int] :type k: int :rtype: str """ present_students = sum(1 for x in students if x < 0) return "YES" if present_students >= k else "NO"
def compact_values(lst): """...""" assert all(x.validate() for x in lst), lst # params_lst = [tuple(x.params.values()) for x in lst] # assert all(len(x) == 1 for x in params_lst), [lst, params_lst] # params = sorted(set(tuple(sorted(x[0])) for x in params_lst)) # return params def trim_str(s): return str(s).strip().replace(' ', ' ') try: values = ', '.join(set(trim_str(x.value) for x in lst)) except TypeError as e: print(e, lst) raise return values
def testAssociate(id_, key, requestor): """Test that keepass has the given identifier and key""" input_data = { 'RequestType': 'test-associate', } return requestor(key, input_data, id_)
def expand_transition(transition, input_list): """Add new (partially) expanded state transition. Parameters ---------- transition: list Specifies a state transition. input_list: list List of inputs, where each input is a string. Returns ------- list New (partially) expanded state transition. """ expanded_transition = list() expanded_transition.append(''.join(input_list)) expanded_transition += transition[1:] return expanded_transition
def generate_custom_inputs(desc_inputs): """ Generates a bunch of custom input dictionaries in order to generate as many outputs as possible (to get their path templates). Currently only works with flag inputs and inputs with defined value choices. """ custom_input_dicts = [] for desc_input in desc_inputs: if desc_input["type"] == "Flag": custom_input_dicts.append({desc_input["id"]: True}) elif desc_input.get("value-choices") and not desc_input.get("list"): for value in desc_input["value-choices"]: custom_input_dicts.append({desc_input["id"]: value}) return custom_input_dicts
def lastchange(pyccd_result, ordinal): """ Number of days since last detected change. Defaults to 0 in cases where the given ordinal day to calculate from is either < 1 or no change was detected before it. Args: pyccd_result: dict return from pyccd ordinal: ordinal day to calculate from Returns: int """ ret = 0 if ordinal > 0: break_dates = [] for segment in pyccd_result['change_models']: if segment['change_probability'] == 1: break_dates.append(segment['break_day']) diff = [(ordinal - d) for d in break_dates if (ordinal - d) > 0] if diff: ret = min(diff) return ret
def stops(a,b): """ Tell if the games with the pair (a,b) will stop at a pair of the form (x,x). """ n = a+b while not bool(n&1): n >>= 1 return (a%n)==0
def render_warning(s) : """ Make rst code for a warning. Nothing if empty """ return """ .. warning:: %s"""%(s) if s else ''
def _create_appconfig_props(config_props, prop_list): """A helper function for mk-appconfig and ch-appconfig that creates the config properties dictionary Arguments: config_props {Dictionary} -- A dictionary with key-value pairs that gives the properties in an appconfig prop_list {List} -- A list with items of the form <Key>=<Value> that describe a given property in an appconfig Returns: config_props {Dictionary} -- A dictionary with key-value pairs that gives the properties in an appconfig """ # Iterate through list of properties, check if correct format, convert each to name/value pairs add to config_props dict # Ex. good proplist is ['name1=value1', 'name2=value2'] # Ex. bad proplist is ['name1=valu=e1', 'name2=value2'] for prop in prop_list: name_value_pair = prop.split("=") if (len(name_value_pair) != 2): raise ValueError("The format of the following property specification is not valid: {}. The correct syntax is: <name>=<value>".format(prop)) config_props[name_value_pair[0]] = name_value_pair[1] return config_props
def valid_version(parameter, min=0, max=100): """ Summary. User input validation. Validates version string made up of integers. Example: '1.6.2'. Each integer in the version sequence must be in a range of > 0 and < 100. Maximum version string digits is 3 (Example: 0.2.3 ) Args: :parameter (str): Version string from user input :min (int): Minimum allowable integer value a single digit in version string provided as a parameter :max (int): Maximum allowable integer value a single digit in a version string provided as a parameter Returns: True if parameter valid or None, False if invalid, TYPE: bool """ # type correction and validation if parameter is None: return True elif isinstance(parameter, int): return False elif isinstance(parameter, float): parameter = str(parameter) component_list = parameter.split('.') length = len(component_list) try: if length <= 3: for component in component_list: if isinstance(int(component), int) and int(component) in range(min, max + 1): continue else: return False except ValueError as e: return False return True
def update_cluster_node_map(cluster_node_map, cluster, max_node_id): """ Updates 'cluster_node_map' which is in format of <cluster name> => <node id> by adding 'cluster' to 'cluster_node_map' if it does not exist :param cluster_node_map: map of cluster names to node ids :type cluster_node_map: dict :param cluster: name of cluster :type cluster: str :param max_node_id: current max node id :type max_node_id: int :return: (new 'max_node_id' if 'cluster' was added otherwise 'max_node_id', id corresponding to 'cluster' found in 'cluster_node_map') :rtype: tuple """ if cluster not in cluster_node_map: max_node_id += 1 cluster_node_map[cluster] = max_node_id cur_node_id = max_node_id else: cur_node_id = cluster_node_map[cluster] return max_node_id, cur_node_id
def upperwhite(safe_string): """Return a username as full name.""" return safe_string.replace("_", " ").title()
def filter_dict_by_keys(dict_, field_names): """ Returns a copy of `dict_` with only the fields in `field_names`""" return {key: value for (key, value) in dict_.items() if key in field_names}
def value_in(value, choices): """Raise an exception if a value doesn't match one of the given choices.""" if value not in choices: raise ValueError("Expected one of %s, received %r." % (", ".join([repr(choice) for choice in choices]), value)) # pragma: no cover return value
def linearSearch(num :int, minimum :int, maximum :int) ->int: """linearly search the num in the range of minimum-maximum Args: num (int): the target number to find minimum (int): the minimum limit of the num maximum (int): the maximum limit of the num Returns: the searching count """ count = 0 for i in range(minimum,maximum+1): count += 1 if (i==num): break return count
def get_timeout(run_type): """Get timeout for a each run type - daily, hourly etc :param run_type: Run type :type run_type: str :return: Number of seconds the tool allowed to wait until other instances finish :rtype: int """ timeouts = { 'hourly': 3600 / 2, 'daily': 24 * 3600 / 2, 'weekly': 7 * 24 * 3600 / 2, 'monthly': 30 * 24 * 3600 / 2, 'yearly': 365 * 24 * 3600 / 2 } return timeouts[run_type]
def _parse_endpoint_url(urlish): """ If given a URL, return the URL and None. If given a URL with a string and "::" prepended to it, return the URL and the prepended string. This is meant to give one a means to supply a region name via arguments and variables that normally only accept URLs. """ if '::' in urlish: region, url = urlish.split('::', 1) else: region = None url = urlish return url, region
def removesuffix(s: str, suffix:str) -> str: """Removes the suffix from s.""" if s.endswith(suffix): return s[:-len(suffix)] return s
def bioconductor_annotation_data_url(package, pkg_version, bioc_version): """ Constructs a url for an annotation package tarball Parameters ---------- package : str Case-sensitive Bioconductor package name pkg_version : str Bioconductor package version bioc_version : str Bioconductor release version """ return ( 'http://bioconductor.org/packages/{bioc_version}' '/data/annotation/src/contrib/{package}_{pkg_version}.tar.gz'.format(**locals()) )
def ERR_NOSUCHSERVICE(sender, receipient, message): """ Error Code 408 """ return "ERROR from <" + sender + ">: " + message
def strictwwid(wwid): """Validity checks WWID for invalid format using strict rules - must be Brocade format""" if len(wwid) != 23: # WWPN must be 23 characters long print("WWID has invalid length " + wwid) return None # Colon separators must be in the correct place if wwid[2:3] != ":" and wwid[5:6] != ":" and wwid[8:9] != ":" and wwid[11:12] != ":" \ and wwid[14:15] != ":" and wwid[17:18] != ":" and wwid[20:21] != ":": print(("WWID invalid format - colon not where expected " + wwid)) return None # Remove colons from expected locations in wwid string. hexwid = wwid[0:2] + wwid[3:5] + wwid[6:8] + wwid[9:11] + wwid[12:14] + wwid[15:17] + wwid[18:20] + wwid[21:23] # Only hex characters allowed in wwpn after extracting colons for nibble in hexwid: if (nibble < "0" or nibble > "f") or (nibble > "9" and nibble < "a"): print("WWID has invalid hex character " + wwid) return None return wwid
def _str_to_int(string, exception=None): """Convert string to integer. Return `exception_value` if failed. Args: string (str): Input string. exception (): Exceptional value returned if failed. Returns: int: """ try: return int(string) except: return exception
def filter_by_year(statistics, year, yearid): """ Inputs: statistics - List of batting statistics dictionaries year - Year to filter by yearid - Year ID field in statistics Outputs: Returns a list of batting statistics dictionaries that are from the input year. """ filtered_lst = [] for row in statistics: if row[yearid] == str(year): filtered_lst.append(row) return filtered_lst
def validate_dialog(dialog, max_turns): """ Check if the dialog consists of multiple turns with equal or less than max_turns by two users without truncated tweets. Args: dialog: target dialog max_turns: upper bound of #turns per dialog Return: True if the conditions are all satisfied False, otherwise """ if len(dialog) > max_turns: return False # skip dialogs including truncated tweets or more users users = set() for utterance in dialog: for tid,tweet in utterance.items(): if tweet['truncated'] == True: return False users.add(tweet['user']['id']) if len(users) != 2: return False return True
def hamming_distance(str1, str2, capdistance=None): """Count the # of differences between equal length strings str1 and str2. Max diff can be capped using capdistance to short-circuit full calculation when only care about a range of distances.""" diffs = 0 if len(str1) != len(str2): raise ValueError('str1 and str2 must be equal lengths, but found %s and %s.' % (len(str1), len(str2))) for ch1, ch2 in zip(str1, str2): if ch1 != ch2: diffs += 1 if capdistance is not None and diffs >= capdistance: return diffs return diffs
def _getitem_list_tuple(items, keys): """Ugly but efficient extraction of multiple values from a list of items. Keys are contained in a tuple. """ filtered = [] for item in items: row = () do_append = True for key in keys: try: row += (item[key],) except KeyError: do_append = False break if row and do_append: filtered.append(row) return filtered
def checksum(sentence): """Calculate and return checsum for given NMEA sentence""" crc = 0 for c in sentence: crc = crc ^ ord(c) crc = crc & 0xFF return crc
def number_is_within_bit_limit(number, bit_width=8): """ Check if a number can be stored in the number of bits given. Negative numbers are stored in 2's compliment binary. Args: number (int): The number to check. bit_width (int, optional): The number of bits available. Returns: bool: True if within limits, False if not. """ min_val = (2**bit_width / 2) * -1 max_val = 2**bit_width - 1 return min_val <= number <= max_val
def next_bet(current, strategy): """Returns the next bet based on the current bet and betting strategy. Standard increases by AUD denominations until reaching 100. Non standard betting strategy doubles each time Parameters: current (int): The current bet to be increased for the next roll strategy (string): 'standard' or 'exponential' which formula to use to determine next bet Returns int: The value of the next bet. """ if strategy == 'standard': if current is None: return 5 elif current == 5: return 10 elif current == 10: return 20 elif current == 20: return 50 else: return 100 else: if current is None: return 5 else: return 2*current
def term_printable(ch): """Return a char if printable, else, a dot.""" if (33 <= ch <= 126): return ch return ord(".")
def max_or_none(iterable): """ Returns the max of some iterable, or None if the iterable has no items Args: iterable (iterable): Some iterable Returns: max item or None """ try: return max(iterable) except ValueError: return None
def replace_last(string, old, new): """ Replace the last occurrence of a pattern in a string :param string: string :type string: ``str`` :param old: string to find :type old: ``str`` :param new: string to replace :type new: ``str`` :returns: ``str`` """ return string[::-1].replace(old[::-1], new[::-1], 1)[::-1]
def list_type_check(lst, data_type): """ Checks if each element of lst has a given type. :param lst: List = list of objects :param data_type: type = estimated type for the objects :return: bool = true if all objects in list have the type data_type """ return all([type(e) == data_type for e in lst])
def frac(x, d): """ Utility func -- Works like fractional div, but returns ceiling rather than floor """ return (x + (d-1)) // d
def addtup(sttup, ndtup): """ Take two tuple as its parameter, where the different length of both tuples is allowed, then return a list of a tuple. How this function work is as follows: sttup:= 4A, ndtup:= 5B, then it will return 4A + 5B or 9 A-B. In this case, it will return [(A, B, 9)] """ if sttup == ndtup: return list(sttup) sumtup = [sttup[:-1] + ndtup[:-1] + (sttup[-1] + ndtup[-1],)] return sumtup
def fix_btwoc(value): """ Utility function to ensure the output conforms the `btwoc` function output. See http://openid.net/specs/openid-authentication-2_0.html#btwoc for details. @type value: bytes or bytearray @rtype: bytes """ # Conversion to bytearray is python 2/3 compatible array = bytearray(value) # First bit must be zero. If it isn't, the bytes must be prepended by zero byte. if array[0] > 127: array = bytearray([0]) + array return bytes(array)
def wf_mutation_rate_from_theta(popsize, theta): """ Given a value for theta (the population-level dimensionless innovation rate, returns the actual probability of mutation per locus per tick. This is a *per locus* innovation rate, however, so if you are using this in code which randomly selects one of M loci to receive a mutation, then you should use M * mutation_rate to determine the actual probability of an event happening in a timestep. theta = 2 * popsize * mutation mutation is thus (theta / 2N) :param popsize: :param theta: :return: """ mutation = float(theta) / float(popsize) #log.debug("WF mutation rate from N: %s and theta: %s: %s", popsize, theta, mutation) return mutation
def startswith(value, arg): """Usage {% if value|startswith:"arg" %}""" if value: return value.startswith(arg) return False
def bin_to_dec(l): """Converts a list "l" of 1s and 0s into a decimal""" return int(''.join(map(str, l)), 2)
def check_eye_colour(val): """ecl (Eye Color) - exactly one of: amb blu brn gry grn hzl oth.""" return val in {"amb", "blu", "brn", "gry", "grn", "hzl", "oth"}
def standardize_breaks(text): """ Converting line endings to the Unix style. The Windows and the old Mac line breaks have been observed in Twitter profiles. These are best replaced with the standard form to make printing and text file handling easier. Especially since "\r" in an unquoted field causes CSV read errors. """ return text.replace("\r\n", "\n").replace("\r", "\n")
def isPotentialMatch(candidate: str, hints: str, guessedLetter: str) -> bool: """Given candidate string, string of hints in form of 011010 and guessed letter decide whether given candidate matches hint""" for serv_let, cand_let in zip(hints, candidate): if serv_let == "0" and cand_let == guessedLetter: return False elif serv_let == "1" and cand_let != guessedLetter: return False return True
def SfromL( L, nmax=25, epsilon= 2**(-50) ): """ Compute sequence of generalized inverses from given Schroder value L. Args: L (real): main arg, range 0.0 to 1.0 nmax (integer): default 22. Max length to allow for S. epsilon (real): smallest change in L you don't care about. Returns: Sequence as list of integers Normally epsilon should be 2 ** -(number of significant bits in L), and for IEEE 64-bit that's 52 bits (the rest being sign and exponent). Fearing trouble with round-offs, I set the default to 50 bits. If you're using some alternative form of real numbers, say a fixed point format built for a fixed range like -1 to 1, or 0 to 1, then set epsilon to something suitable for that type. """ # Prevent accidental use of negative L, or L too close to zero # which can lead to infinite loop if L<1e-22: # 1e-22 is a guess; no real thinking was done return [73] S = [] while len(S) <= nmax: count = 0 while L < 0.5: L = 2.0*L count +=1 S.append( count) if count > 52: break; if abs(L-0.5) < epsilon: break L = 1-L if L<1e-22: break return S
def get_organic_aerosols_keys(chem_opt): """ Return the anthropogenic and biogenic keys """ asoa_keys = None bsoa_keys = None if chem_opt == 106: asoa_keys = ('orgaro1i', 'orgaro1j', 'orgaro2i', 'orgaro2j', 'orgalk1i', 'orgalk1j', 'orgole1i', 'orgole1j') # SOA Anth bsoa_keys = ('orgba4i', 'orgba4j', 'orgba3i', 'orgba3j', 'orgba2i', 'orgba2j', 'orgba1i', 'orgba1j') # SOA Biog elif chem_opt == 108 or chem_opt == 100: asoa_keys = 'asoa1j,asoa1i,asoa2j,asoa2i,asoa3j,asoa3i,asoa4j,asoa4i'.split(',') # SOA Anth bsoa_keys = 'bsoa1j,bsoa1i,bsoa2j,bsoa2i,bsoa3j,bsoa3i,bsoa4j,bsoa4i'.split(',') # SOA Biog else: print('PP: this chem_opt {} is not implemented, dont know how to combine organics') return asoa_keys, bsoa_keys
def getfilename(path): """This function extracts the file name without file path or extension Args: path (file): full path and file (including extension of file) Returns: name of file as string """ return path.split('\\').pop().split('/').pop().rsplit('.', 1)[0]
def factorial(n): """returns n!""" return 1 if n < 2 else n * factorial(n-1)
def zero_insert(input_string): """ Get a string as input if input is one digit add a zero. :param input_string: input digit az string :type input_string:str :return: modified output as str """ if len(input_string) == 1: return "0" + input_string return input_string
def process(data): """ Lower cases and reverses a string Arguments: data (str): The string to transform Returns: result (str): The lower cased, reversed string """ return data.lower()[::-1]
def unstitch_strip(strip): """Revert stitched strip back to a set of strips without stitches. >>> strip = [0,1,2,2,3,3,4,5,6,7,8] >>> triangles = triangulate([strip]) >>> strips = unstitch_strip(strip) >>> _check_strips(triangles, strips) >>> strips [[0, 1, 2], [3, 3, 4, 5, 6, 7, 8]] >>> strip = [0,1,2,3,3,4,4,4,5,6,7,8] >>> triangles = triangulate([strip]) >>> strips = unstitch_strip(strip) >>> _check_strips(triangles, strips) >>> strips [[0, 1, 2, 3], [4, 4, 5, 6, 7, 8]] >>> strip = [0,1,2,3,4,4,4,4,5,6,7,8] >>> triangles = triangulate([strip]) >>> strips = unstitch_strip(strip) >>> _check_strips(triangles, strips) >>> strips [[0, 1, 2, 3, 4], [4, 4, 5, 6, 7, 8]] >>> strip = [0,1,2,3,4,4,4,4,4,5,6,7,8] >>> triangles = triangulate([strip]) >>> strips = unstitch_strip(strip) >>> _check_strips(triangles, strips) >>> strips [[0, 1, 2, 3, 4], [4, 5, 6, 7, 8]] >>> strip = [0,0,1,1,2,2,3,3,4,4,4,4,4,5,5,6,6,7,7,8,8] >>> triangles = triangulate([strip]) >>> strips = unstitch_strip(strip) >>> _check_strips(triangles, strips) >>> strips []""" strips = [] currentstrip = [] i = 0 while i < len(strip)-1: winding = i & 1 currentstrip.append(strip[i]) if strip[i] == strip[i+1]: # stitch detected, add current strip to list of strips strips.append(currentstrip) # and start a new one, taking into account winding if winding == 1: currentstrip = [] else: currentstrip = [strip[i+1]] i += 1 # add last part currentstrip.extend(strip[i:]) strips.append(currentstrip) # sanitize strips for strip in strips: while len(strip) >= 3 and strip[0] == strip[1] == strip[2]: strip.pop(0) strip.pop(0) return [strip for strip in strips if len(strip) > 3 or (len(strip) == 3 and strip[0] != strip[1])]