content
stringlengths
42
6.51k
def convert_to_bool(x) -> bool: """Convert string 'true' to bool.""" return x == "true"
def dot(a, b): """Compute the dot product between the two vectors a and b.""" return sum(i * j for i, j in zip(a, b))
def is_set(parameter: str): """ Checks if a given parameter exists and is not empty. :param parameter: param to check for :return: if param is not None and not empty """ return parameter and parameter != ""
def linear_system_example(x): """A simple linear system of equations.""" n = len(x) res = [0] * n for i in range(n): for j in range(n): res[i] += (1 + i * j) * x[j] return res
def fill_zeros(coords): """ fill with zeros, if coord is missing seconds :param coords: :return: """ if len(coords) == 2: if "." in coords[1]: coords = [coords[0], "00", coords[1]] else: coords = [coords[0], coords[1], "00"] return coords
def get_trans_freq_color(trans_count, min_trans_count, max_trans_count): """ Gets transition frequency color Parameters ---------- trans_count Current transition count min_trans_count Minimum transition count max_trans_count Maximum transition count Returns ---------- color Frequency color for visible transition """ transBaseColor = int(255 - 100 * (trans_count - min_trans_count)/(max_trans_count - min_trans_count + 0.00001)) transBaseColorHex = str(hex(transBaseColor))[2:].upper() return "#" + transBaseColorHex + transBaseColorHex + "FF"
def __remove_empty(j): """Remove the empty fields in the Json.""" if isinstance(j, list): res = [] for i in j: # Don't remove empty primitive types. Only remove other empty types. if isinstance(i, int) or isinstance(i, float) or isinstance( i, str) or isinstance(i, bool): res.append(i) elif __remove_empty(i): res.append(__remove_empty(i)) return res if isinstance(j, dict): final_dict = {} for k, v in j.items(): if v: final_dict[k] = __remove_empty(v) return final_dict return j
def deletedup(xs): """Delete duplicates in a playlist.""" result = [] for x in xs: if x not in result: result.append(x) return result
def _inputs_swap_needed(mode, shape1, shape2): """ If in 'valid' mode, returns whether or not the input arrays need to be swapped depending on whether `shape1` is at least as large as `shape2` in every dimension. This is important for some of the correlation and convolution implementations in this module, where the larger array input needs to come before the smaller array input when operating in this mode. Note that if the mode provided is not 'valid', False is immediately returned. """ if (mode == 'valid'): ok1, ok2 = True, True for d1, d2 in zip(shape1, shape2): if not d1 >= d2: ok1 = False if not d2 >= d1: ok2 = False if not (ok1 or ok2): raise ValueError("For 'valid' mode, one must be at least " "as large as the other in every dimension") return not ok1 return False
def trunc(text, max_length: int = 2000): """Truncates output if it is too long.""" if len(text) <= max_length: return text else: return text[0 : max_length - 3] + "..."
def balance_formatter(asset_info): """ Returns the formatted units for a given asset and amount. """ decimals = asset_info.get("decimals") unit = asset_info.get("unitname") total = asset_info.get("total") formatted_amount = total/10**decimals return "{} {}".format(formatted_amount, unit)
def bin_to_hex(binary_string, min_width=0): """ Convert binary string into hex string :param binary_string: binary string :param min_width: width of hex string :return: """ return '{0:0{width}x}'.format(int(binary_string, 2), width=min_width)
def _compute_temp_terminus(temp, temp_grad, ref_hgt, terminus_hgt, temp_anomaly=0): """Computes the (monthly) mean temperature at the glacier terminus, following section 2.1.2 of Marzeion et. al., 2012. The input temperature is scaled by the given temperature gradient and the elevation difference between reference altitude and the glacier terminus elevation. Parameters ---------- temp : netCDF4 variable monthly mean climatological temperature (degC) temp_grad : netCDF4 variable or float temperature lapse rate [degC per m of elevation change] ref_hgt : float reference elevation for climatological temperature [m asl.] terminus_hgt : float elevation of the glacier terminus (m asl.) temp_anomaly : netCDF4 variable or float, optional monthly mean temperature anomaly, default 0 Returns ------- netCDF4 variable monthly mean temperature at the glacier terminus [degC] """ temp_terminus = temp + temp_grad * (terminus_hgt - ref_hgt) + temp_anomaly return temp_terminus
def sanitize_list(mylist): """ Helper function to objectify items """ if mylist is not None: return mylist.split(',') else: return None
def state_string_from_int(i, N): """translates an integer i into a state string by using the binary representation of the integer""" return bin(i)[2:].zfill(N)
def isMatch(s, p): """ Perform regular simple expression matching Given an input string s and a pattern p, run regular expression matching with support for '.' and '*'. Parameters ---------- s : str The string to match. p : str The pattern to match. Returns ------- bool Was it a match or not. """ dp = [[False] * (len(p) + 1) for _ in range(len(s) + 1)] dp[0][0] = True # The only way to match a length zero string # is to have a pattern of all *'s. for ii in range(1, len(p)): if p[ii] == "*" and dp[0][ii-1]: dp[0][ii + 1] = True for ii in range(len(s)): for jj in range(len(p)): # Matching a single caracter c or '.'. if p[jj] in {s[ii], '.'}: dp[ii+1][jj+1] = dp[ii][jj] elif p[jj] == '*': # Double **, which is equivalent to * if p[jj-1] not in {s[ii], '.'}: dp[ii+1][jj+1] = dp[ii+1][jj-1] # We can match .* or c* multiple times, once, or zero # times (respective clauses in the or's) else: dp[ii+1][jj+1] = dp[ii][jj+1] or dp[ii+1][jj] or dp[ii+1][jj-1] return dp[-1][-1]
def check_help_flag(addons: list) -> bool: """Checks to see if a help message needs to be printed for an addon. Not all addons check for help flags themselves. Until they do, intercept calls to print help text and print out a generic message to that effect. """ addon = addons[0] if any(help_arg in addons for help_arg in ("-h", "--help")): print("Addon %s does not yet have a help message." % addon) print("For more information about it, visit https://microk8s.io/docs/addons") return True return False
def _indent(text, amount): """Indent a multiline string by some number of spaces. Parameters ---------- text: str The text to be indented amount: int The number of spaces to indent the text Returns ------- indented_text """ indentation = amount * ' ' return indentation + ('\n' + indentation).join(text.split('\n'))
def _generate_overlap_table(prefix): """ Generate an overlap table for the following prefix. An overlap table is a table of the same size as the prefix which informs about the potential self-overlap for each index in the prefix: - if overlap[i] == 0, prefix[i:] can't overlap prefix[0:...] - if overlap[i] == k with 0 < k <= i, prefix[i-k+1:i+1] overlaps with prefix[0:k] """ table = [0] * len(prefix) for i in range(1, len(prefix)): idx = table[i - 1] while prefix[i] != prefix[idx]: if idx == 0: table[i] = 0 break idx = table[idx - 1] else: table[i] = idx + 1 return table
def skip_14(labels): """Customised label skipping for 14 quantiles.""" return ( labels[0], labels[2], labels[4], labels[6], labels[8], labels[10], labels[13], )
def _llvm_get_rule_name( prefix_dict, name): """Returns a customized name of a rule. When the prefix matches a key from 'prefix_dict', the prefix will be replaced with the 'prefix_dict[key]' value. Args: prefix_dict: the dictionary of library name prefixes. name: rule name. Returns: customized name when the prefix is replaces with a value from 'prefix_dict'. """ concat_format = "%s%s" for old_prefix, new_prefix in prefix_dict.items(): if name.startswith(old_prefix): return concat_format % (new_prefix, name[len(old_prefix) + 1:]) return name
def average_contour(cnt): """ This function smooths out the contours created by the model """ result = [cnt[0]] n = len(cnt) for i in range(1, n): px = (cnt[(i-1)%n][0] + 2*cnt[i%n][0] + cnt[(i+1)%n][0])/4 py = (cnt[(i-1)%n][1] + 2*cnt[i%n][1] + cnt[(i+1)%n][1])/4 result.append([int(px), int(py)]) return result
def findNext ( v, pos, pattern, bodyFlag = 1 ): """ findNext: use string.find() to find a pattern in a Leo outline. v the vnode to start the search. pos the position within the body text of v to start the search. pattern the search string. bodyFlag true: search body text. false: search headline text. returns a tuple (v,pos) showing where the match occured. returns (None,0) if no further match in the outline was found. Note: if (v,pos) is a tuple returned previously from findNext, findNext(v,pos+len(pattern),pattern) finds the next match. """ while v != None: if bodyFlag: s = v.bodyString() else: s = v.headString() pos = s.find(pattern,pos ) if pos != -1: return v, pos v = v.threadNext() pos = 0 return None, 0
def find_comment(s): """ Finds the first comment character in the line that isn't in quotes.""" quote_single, quote_double, was_backslash = False, False, False for i, ch in enumerate(s): if was_backslash: was_backslash = False elif ch == '\\': was_backslash = True elif quote_single: if ch == '\'': quote_single = False elif quote_double: if ch == '"': quote_double = False elif ch == '\'': quote_single = True elif ch == '"': quote_double = True elif ch == '#': return i return -1
def split_cols_with_dot(column: str) -> str: """Split column name in data frame columns whenever there is a dot between 2 words. E.g. price.availableSupply -> priceAvailableSupply. Parameters ---------- column: str Pandas dataframe column value Returns ------- str: Value of column with replaced format. """ def replace(string: str, char: str, index: int) -> str: """Helper method which replaces values with dot as a separator and converts it to camelCase format Parameters ---------- string: str String in which we remove dots and convert it to camelcase format. char: str First letter of given word. index: Index of string element. Returns ------- str: Camel case string with removed dots. E.g. price.availableSupply -> priceAvailableSupply. """ return string[:index] + char + string[index + 1 :] if "." in column: part1, part2 = column.split(".") part2 = replace(part2, part2[0].upper(), 0) return part1 + part2 return column
def snake_to_kebab(text: str) -> str: """ Examples -------- >>> snake_to_kebab('donut_eat_animals') 'donut-eat-animals' """ return text.replace("_", "-")
def exponential_decay_fn(t, t0, t1, eps0, factor): """Exponentially decays. Args: t: Current step, starting from 0 t0: Decay start t1: Decay end factor: Decay factor eps0: start learning rate """ if t < t0: return eps0 lr = eps0 * pow(factor, (t - t0) / (t1 - t0)) return lr
def process_line(line: str) -> dict: """Assign values from lines of a data file to keys in a dictionary.""" name, age, state = line.strip().split(",") result = {"name": name, "age": int(age), "state": state} return result
def data_transformer(x, y, xfactor, yfactor, **kwargs): """Multiplies x or y data by their corresponding factor.""" return {"x": x * xfactor, "y": y * yfactor}
def isglobalelement (domains): """ Check whether all domains are negations.""" for domain in domains.split(","): if domain and not domain.startswith("~"): return False return True
def scaleRect(rect, x, y): """Scale the rectangle by x, y.""" (xMin, yMin, xMax, yMax) = rect return xMin * x, yMin * y, xMax * x, yMax * y
def CleanStrForFilenames(filename): """Sanitize a string to be used as a filename""" keepcharacters = (' ', '.', '_') FILEOUT = "".join(c for c in filename if c.isalnum() or c in keepcharacters).rstrip() return FILEOUT
def _to_int(x): """convert to integers""" return int(x[0]), int(x[1])
def count_true(seq, pred=lambda x: x): """How many elements is ``pred(elm)`` true for? With the default predicate, this counts the number of true elements. >>> count_true([1, 2, 0, "A", ""]) 3 >>> count_true([1, "A", 2], lambda x: isinstance(x, int)) 2 This is equivalent to the ``itertools.quantify`` recipe, which I couldn't get to work. """ ret = 0 for x in seq: if pred(x): ret += 1 return ret
def five(ls): """ returns first five of list """ return ls[:5]
def get_time_in_seconds(time, time_units): """This method get time is seconds""" min_in_sec = 60 hour_in_sec = 60 * 60 day_in_sec = 24 * 60 * 60 if time is not None and time > 0: if time_units in 'minutes': return time * min_in_sec elif time_units in 'hours': return time * hour_in_sec elif time_units in 'days': return time * day_in_sec else: return time else: return 0
def bytes_isupper(x: bytes) -> bool: """Checks if given bytes object contains only uppercase elements. Compiling bytes.isupper compiles this function. This function is only intended to be executed in this compiled form. Args: x: The bytes object to examine. Returns: Result of check. """ found_upper = False for i in x: if ord('A') <= i <= ord('Z'): found_upper = True elif ord('a') <= i <= ord('z'): return False return found_upper
def packHeader(name, *values): """ Format and return a header line. For example: h.packHeader('Accept', 'text/html') """ if isinstance(name, str): # not bytes name = name.encode('ascii') name = name.title() # make title case values = list(values) # make copy for i, value in enumerate(values): if isinstance(value, str): values[i] = value.encode('iso-8859-1') elif isinstance(value, int): values[i] = str(value).encode('ascii') value = b', '.join(values) return (name + b': ' + value)
def _clear_bits(basis_state, apply_qubits): """ Set bits specified in apply_qubits to zero in the int basis_state. Example: basis_state = 6, apply_qubits = [0, 1] 6 == 0b0110 # number in binary representation calling this method returns sets the two right-most bits to zero: return -> 0b0100 == 4 >>> _clear_bits(6, [0, 1]) 4 :type basis_state: int :type apply_qubits: [int] :param basis_state: An arbitrary integer. :param apply_qubits: Bits to set to zero. :return: int """ return basis_state - (sum(1 << i for i in apply_qubits) & basis_state)
def get_bool(bytearray_: bytearray, byte_index: int, bool_index: int) -> bool: """Get the boolean value from location in bytearray Args: bytearray_: buffer data. byte_index: byte index to read from. bool_index: bit index to read from. Returns: True if the bit is 1, else 0. Examples: >>> buffer = bytearray([0b00000001]) # Only one byte length >>> get_bool(buffer, 0, 0) # The bit 0 starts at the right. True """ index_value = 1 << bool_index byte_value = bytearray_[byte_index] current_value = byte_value & index_value return current_value == index_value
def _yes_format(user, keys): """Changes all dictionary values to yes whose keys are in the list. """ for key in keys: if user.get(key): user[key] = 'yes' return user
def get_coordinates(threshold, value, step, direction, current_x, current_y): """Function for looping until correct coordinate is found""" while value <= threshold: for _ in range(0, 2): for _ in range(0, step): value += 1 # Step if direction == 0: current_x += 1 elif direction == 1: current_y += 1 elif direction == 2: current_x -= 1 elif direction == 3: current_y -= 1 if value == threshold: return (current_x, current_y) # Change direction direction = (direction + 1) % 4 # Increase steps step += 1
def get_filename_stem(filename): """ A filename should have the following format: /path/to/file/filename_stem.jpg This function extracts filename_stem from the input filename string. """ filename_stem = filename.split("/") filename_stem = filename_stem[-1].split(".") filename_stem = filename_stem[0] return filename_stem
def compatiblify_phenotype_id(phenotype_id): """RHEmc throws errors on reading weird phenotype headers. This function resolves these characters. """ to_replace = [' ', '|', '>', '<', '/', '\\'] for i in to_replace: phenotype_id = phenotype_id.replace(i, '_') return phenotype_id
def _descExc(reprOfWhat, err): """Return a description of an exception. This is a private function for use by safeDescription(). """ try: return '(exception from repr(%s): %s: %s)' % ( reprOfWhat, err.__class__.__name__, err) except Exception: return '(exception from repr(%s))' % reprOfWhat
def app_create(app, request): """ Create a copy of welcome.w2p (scaffolding) app Parameters ---------- app: application name request: the global request object """ did_mkdir = False try: path = apath(app, request) os.mkdir(path) did_mkdir = True w2p_unpack('welcome.w2p', path) db = os.path.join(path,'models/db.py') if os.path.exists(db): fp = open(db,'r') data = fp.read() fp.close() data = data.replace('<your secret key>','sha512:'+str(uuid.uuid4())) fp = open(db,'w') fp.write(data) fp.close() return True except: if did_mkdir: rmtree(path) return False
def func_create_file(path_to_file): """ Function description Example/s of use (and excutable test/s via doctest): >>> func_create_file("file.txt") 'line in file' :param path_to_file: set a path to file :return: string with first line in file """ with open(path_to_file, "w") as f: f.write("line in file") with open(path_to_file, "r") as f: return f.readline()
def tagToByte(value): """ Converts an ASN1 Tag into the corresponding byte representation :param value: The tag to convert :return: The integer array """ if value <= 0xff: return [value] elif value <= 0xffff: return [(value >> 8), (value & 0xff)] elif value <= 0xffffff: return [(value >> 16), ((value >> 8) & 0xff), (value & 0xff)] elif value <= 0xffffffff: return [(value >> 24), ((value >> 16) & 0xff), ((value >> 8) & 0xff), (value & 0xff)] raise Exception("tagToByte: tag is too big")
def progress_reporting_sum(numbers, progress): """ Sum a list of numbers, reporting progress at each step. """ count = len(numbers) total = 0 for i, number in enumerate(numbers): progress((i, count)) total += number progress((count, count)) return total
def _pipe_separated(val): """ Returns *val* split on the ``'|'`` character. >>> _pipe_separated("a|b|c") ['a', 'b', 'c] """ return [s.strip() for s in val.split('|') if s.strip()]
def ternary_search(array): """ Ternary Search Complexity: O(log3(N)) Requires a unimodal array. That means that the array has to be increasing and then decreasing (or the opposite). The point is to find the maximum (or minimum) element. Small modifications needed to work with descending and then ascending order as well. """ lower = 0 upper = len(array) - 1 while lower < upper: first_third = lower + (upper - lower) // 3 second_third = upper - (upper - lower) // 3 if array[first_third] < array[second_third]: lower = first_third+1 else: upper = second_third-1 # We can return either lower or upper. That happens # because the code is going to stop when lower = upper. return lower
def period_to_date(period): """ Convert a period (in AAAAMM form) to a date (in MM/AAAA form). """ month = period[4:6] year = period[0:4] return month + '/' + year
def palindrome(number): """ Returns True if number is palindrome """ number = str(number) for idx in range(len(number)//2): if number[idx] != number[len(number)-idx-1]: return False return True
def istruthy(val) -> bool or str or int or dict or list or None: """ Returns True if the passed val is T, True, Y, Yes, 1, or boolean True. Returns False if the passed val is boolean False or a string that is not T, True, Y, Yes, or 1, or an integer that is not 1. Returns the passed val otherwise. Ignores case.""" if not val: return val elif isinstance(val, bool): return val elif isinstance(val, str): return { 't': True, 'true': True, 'y': True, 'yes': True, '1': True }.get(str(val).strip().lower(), False) elif isinstance(val, int): return { 1: True }.get(val, False) else: return val
def cross(a, b): """Cross Product. Given vectors a and b, calculate the cross product. Parameters ---------- a : list First 3D vector. b : list Second 3D vector. Returns ------- c : list The cross product of vector a and vector b. Examples -------- >>> import numpy as np >>> from .pyCGM import cross >>> a = [6.25, 7.91, 18.63] >>> b = [3.49, 4.42, 19.23] >>> np.around(cross(a, b), 2) array([ 6.976e+01, -5.517e+01, 2.000e-02]) """ c = [a[1]*b[2] - a[2]*b[1], a[2]*b[0] - a[0]*b[2], a[0]*b[1] - a[1]*b[0]] return c
def is_defined(s, table): """ Test if a symbol or label is defined. :param s: The symbol to look up. :param table: A dictionary containing the labels and symbols. :return: True if defined, False otherwise. """ try: table[s] # Exploiting possible KeyError return True except KeyError: return False
def str_to_orientation(value, reversed_horizontal=False, reversed_vertical=False): """Tries to interpret a string as an orientation value. The following basic values are understood: ``left-right``, ``bottom-top``, ``right-left``, ``top-bottom``. Possible aliases are: - ``horizontal``, ``horiz``, ``h`` and ``lr`` for ``left-right`` - ``vertical``, ``vert``, ``v`` and ``tb`` for top-bottom. - ``lr`` for ``left-right``. - ``rl`` for ``right-left``. ``reversed_horizontal`` reverses the meaning of ``horizontal``, ``horiz`` and ``h`` to ``rl`` (instead of ``lr``); similarly, ``reversed_vertical`` reverses the meaning of ``vertical``, ``vert`` and ``v`` to ``bt`` (instead of ``tb``). Returns one of ``lr``, ``rl``, ``tb`` or ``bt``, or throws ``ValueError`` if the string cannot be interpreted as an orientation. """ aliases = {"left-right": "lr", "right-left": "rl", "top-bottom": "tb", "bottom-top": "bt", "top-down": "tb", "bottom-up": "bt", "top-bottom": "tb", "bottom-top": "bt", "td": "tb", "bu": "bt"} dir = ["lr", "rl"][reversed_horizontal] aliases.update(horizontal=dir, horiz=dir, h=dir) dir = ["tb", "bt"][reversed_vertical] aliases.update(vertical=dir, vert=dir, v=dir) result = aliases.get(value, value) if result not in ("lr", "rl", "tb", "bt"): raise ValueError("unknown orientation: %s" % result) return result
def _value_error_on_false(ok, *args): """Returns None / args[0] / args if ok.""" if not isinstance(ok, bool): raise TypeError("first argument should be a bool") if not ok: raise ValueError("call failed") if args: return args if len(args) > 1 else args[0] return None
def nested_list_elements_to_int(mask): """Recursively convert list of nested lists/tuples to list of nested lists with elements coerced to integers Args: mask (list): List with nested lists/tuples containing start, end positions Returns: (list): List of nested lists containing start, end positions, coerced to integers """ if isinstance(mask, (list, tuple)): return list(map(nested_list_elements_to_int, mask)) else: return int(mask)
def hash_s(_s): """ Hash and sum each charater from string """ s_hashed = 0 for _char in _s: s_hashed += hash(_char) return s_hashed
def truncate_string(string: str, max_length: int) -> str: """ Truncate a string to a specified maximum length. :param string: String to truncate. :param max_length: Maximum length of the output string. :return: Possibly shortened string. """ if len(string) <= max_length: return string else: return string[:max_length]
def transform_boolean(value): """ Transform boolean values that are blank into NULL so that they are not imported as empty strings. """ if value.lower() in ("true", "t", "1"): return True elif value.lower() in ("false", "f", "0"): return False else: return None
def RPL_TRACESERVICE(sender, receipient, message): """ Reply Code 207 """ return "<" + sender + ">: " + message
def validateRange(rangeStr : str) -> bool: """Validates the range argument""" # type cast and compare try: # get range indices ranges = rangeStr.split(",", 1) rangeFrom = 0 if ranges[0] == "" else int(ranges[0]) rangeTo = 0 if ranges[1] == "" else int(ranges[1]) # check first if both ranges are not set # using the -r , hack if ranges == ["", ""]: return False # check if any of the range param is set # and do testing per side # if either range start/end is set and is <= 0: if (ranges[0] != "" and rangeFrom < 0) or\ (ranges[1] != "" and rangeTo < 0): return False elif (ranges[0] != "") and (ranges[1] != ""): # if both are set, do conditions here # if from == to or from > to or from,to <=0, fail if (rangeFrom == rangeTo) or\ (rangeFrom > rangeTo) or\ ((rangeFrom <= 0) or (rangeTo <= 0)): return False except (ValueError, IndexError, AttributeError): return False return True
def compare_floats(float1, float2, f_error=0.01, zero_tolerance=1e-8, inf_tolerance=1e80): """ Compare two numeric objects according to the following algorithm: 1. If float1 < zero_tolerance and float2 < zero_tolerance, then returns True. 2. If abs(float1) > inf_tolerance and abs(float2) > inf_tolerance, and sign(float1) = sign(float2), then returns True. 3. If zero_tolerance < abs(float1, float2) < inf_tolerance, and 2*abs(float1 - float2)/(abs(float1) + abs(float2)) <= f_error, return True. 4. Otherwise, return False. :param float1: First numeric field. :param float2: Second numeric field. :param f_error: Fractional margin of error (default: 0.01) :param zero_tolerance: Zero tolerance (default: 1e-8) :param inf_tolerance: Infinite tolerance (default: 1e80) """ if abs(float1) < zero_tolerance and abs(float2) < zero_tolerance: return True elif abs(float1) > inf_tolerance and abs(float2) > inf_tolerance: if float1/float2 > 0: return True else: return False elif 2*abs(float1 - float2)/(abs(float1) + abs(float2)) <= f_error: return True else: return False
def exp_str(dictionary, key): """Return exponent string. An empty string if exponent is 1. """ if dictionary[key] == 1: return '' else: return '**' + str(dictionary[key])
def fix_aspect_providers(lib_providers): """Change a list of providers to be returnable from an aspect. Args: lib_providers: A list of providers, e.g., as returned from forward_deps(). Returns: A list of providers which is valid to return from an aspect. """ # The DefaultInfo provider can't be returned from aspects. return [p for p in lib_providers if not hasattr(p, "files")]
def to_cuda(data): """ Move an object to CUDA. This function works recursively on lists and dicts, moving the values inside to cuda. Args: data (list, tuple, dict, torch.Tensor, torch.nn.Module): The data you'd like to move to the GPU. If there's a pytorch tensor or model in data (e.g. in a list or as values in a dictionary) this function will move them all to CUDA and return something that matches the input in structure. Returns: list, tuple, dict, torch.Tensor, torch.nn.Module: Data of the same type / structure as the input. """ # the base case: if this is not a type we recognise, return it return data
def station_geojson(stations): """Process station data into GeoJSON """ result = [] for data in stations: result.append( {"type": "Feature", "geometry": { "type": "Point", "coordinates": [data['x'], data['y']] }, "properties": { "id": data['id'], "name": data['name'], "address": data['address'], "city": data['city'], "nb_bikes": data['nb_bikes'] }}) return {"type": "FeatureCollection", "features": result}
def suffix_length(needle, p): """ Returns the maximum length of the substring ending at p that is a suffix. """ length = 0; j = len(needle) - 1 for i in reversed(range(p + 1)): if needle[i] == needle[j]: length += 1 else: break j -= 1 return length
def update_with(left, right, default_value, upd_fn): """ unionWith for Python, but modifying first dictionary instead of returning result """ for k, val in right.items(): if k not in left: left[k] = default_value[:] left[k] = upd_fn(left[k], val) return left
def make_slist(l, t_sizes): """ Create a list of tuples of given sizes from a list Parameters ---------- l : list or ndarray List or array to pack into shaped list. t_sizes : list of ints List of tuple sizes. Returns ------- slist : list of tuples List of tuples of lengths given by t_sizes. """ out = [] # output start = 0 for s in t_sizes: out.append(l[start:start + s]) start = start + s return out
def _unflatten_dims(dims): """ ['a','b,c','d'] ==> ['a','b','c','d'] """ flatdims = [] for d in dims: flatdims.extend(d.split(',')) return flatdims
def codestr2rst(codestr): """Return reStructuredText code block from code string""" code_directive = ".. code-block:: python\n\n" indented_block = '\t' + codestr.replace('\n', '\n\t') return code_directive + indented_block
def _arg_names(f): """Return the argument names of a function.""" return f.__code__.co_varnames[:f.__code__.co_argcount]
def _Error(message, code=400): """ Create an Error framework :param message: :param code: :return: """ return { "error" : message, "code" : code }
def clean_bibitem_string(string): """Removes surrounding whitespace, surrounding \\emph brackets etc.""" out = string out = out.strip() if out[:6] == "\\emph{" and out[-1] == "}": out = out[6:-1] if out[:8] == "\\textsc{" and out[-1] == "}": out = out[8:-1] return out
def calc_center(eye): """ Using for further cropping eyes from images with faces :param eye: :return: x, y, of center of eye """ center_x = (eye[0][0] + eye[3][0]) // 2 center_y = (eye[0][1] + eye[3][1]) // 2 return int(center_x), int(center_y)
def single_number(nums): """ Given an array of integers, every element appears twice except for one. Find that single one. Note: Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? Args: nums: list[int] Returns: int """ # Method 1 nums = sorted(nums) for i in range(0, len(nums) - 2, 2): if nums[i] != nums[i + 1]: return nums[i] return nums[-1] # Method 2 # 1) N XOR N = 0 # 2) XOR is associative & commutative res = 0 for num in nums: res ^= num return res
def tanh_to_sig_scale(tanh_input,scale_multiplier=1.): """For image data scaled between [-1,1], rescale to [0,1] * scale_multiplier (e.g. 255 for RGB images) """ #Due to operator overloading, this also works with tensors return ((tanh_input+1.)/2.)*scale_multiplier
def check_equal(val1, val2): """ Check two values are equal and exit with message if not Args: val1: the first value to compare val2: the second value to compare """ return abs(val1 - val2) < 0.0000000001
def mod_exponent(base, power, mod): """ Modular exponential of a number :param base : number which is going to be raised :param power : power to which the number is raised :param mod : number by modulo has to be performed :return : number raised to power and modulo by mod [(base ^ power) % mod] """ res = 1 # Initialize result base = base % mod # Update base if it is more than or equal mod_ while power > 0: if power & 1: # if pow_ is odd multiply it with result res = (res * base) % mod power = power >> 1 # _pow must be even now base = (base * base) % mod return res
def create_object_detected_msg(position): """creates an xyz message of target location""" return {'coords':position}
def distance_squared(a, b): """The square of the distance between two (x, y) points.""" return (a[0] - b[0])**2 + (a[1] - b[1])**2
def import_function(function): """L{import_function} is a shortcut that will import and return L{function} if it is a I{str}. If not, then it is assumed that L{function} is callable, and is returned.""" if isinstance(function, str): m, f = function.rsplit('.', 1) return getattr(__import__(m, {}, {}, ['']), f) return function
def best3av(a, b, c, d): """ (number, number, numbern number) -> number Precondition: 100 > Numbers > 0. Returns the average of the highest three numbers. >>>average(40, 99, 87, 0) 75.33 >>>average(80, 10, 100, 40) 73.33 """ One = min(a, b, c, d) Two = (a + b + c + d - One) Three = Two / 3 return round(Three, 2)
def compute_power(rawvolts, rawamps): """ Compute the power. Looks trivial, but I'm gonna implement smoothing later. """ power = rawvolts * 1.58 power_low = rawvolts * 1.51 power_high = rawvolts * 1.648 return power, power_low, power_high
def condense_repeats(ll, use_is=True): """ Count the number of consecutive repeats in a list. Essentially, a way of doing `uniq -c` Parameters ---------- ll : list a list Returns ------- list of tuples list of 2-tuples in the format (element, repeats) where element is the element from the list, and repeats is the number of consecutive times it appeared """ count = 0 old = None vals = [] for e in ll: if (use_is and e is old) or (not use_is and e == old): count += 1 else: if old is not None: vals.append((old, count)) count = 1 old = e vals.append((old, count)) return vals
def ordinal_number(n: int): """ Returns a string representation of the ordinal number for `n` e.g., >>> ordinal_number(1) '1st' >>> ordinal_number(4) '4th' >>> ordinal_number(21) '21st' """ # from https://codegolf.stackexchange.com/questions/4707/outputting-ordinal-numbers-1st-2nd-3rd#answer-4712 return'%d%s' % (n, 'tsnrhtdd'[(n // 10 % 10 != 1) * (n % 10 < 4) * (n % 10)::4])
def compareKeys(zotkeys, notkeys): """ Compares the Zotero and Notion keys """ keys = [] for zkey in zotkeys: if zkey in notkeys: pass else: keys.append(zkey) return keys
def ordered(obj): """Ordering a dict object :param obj: Can be list or dict :return obj: """ if isinstance(obj, dict): return sorted((k, ordered(v)) for k, v in obj.items()) if isinstance(obj, list): return sorted(ordered(x) for x in obj) else: return obj
def processFirstLine(x): """work on the values of x """ numbers = (x.split(' ')) return numbers
def _return_parameter_names(num_pars): """ Function that returns the names of the parameters for writing to the dataframe after the fit. num_pars is the number of parameters in the fit. 1,3,5,7,9 are the num_params that constrain the fit. while the even numbers are the parameters for the functions that don't constrain the fits. """ if num_pars==1: return ['C_a', 'tau_a'] elif num_pars==2: return ['C_a', 'tau_a'] elif num_pars==3: return ['C_a', 'tau_a', 'tau_b'] elif num_pars==4: return ['C_a', 'tau_a', 'C_b', 'tau_b'] elif num_pars==5: return ['C_a', 'tau_a', 'C_b', 'tau_b', 'tau_g'] elif num_pars==6: return ['C_a', 'tau_a', 'C_b', 'tau_b', 'C_g', 'tau_g'] elif num_pars==7: return ['C_a', 'tau_a', 'C_b', 'tau_b', 'C_g', 'tau_g', 'tau_d'] elif num_pars==8: return ['C_a', 'tau_a', 'C_b', 'tau_b', 'C_g', 'tau_g', 'C_d', 'tau_d'] elif num_pars==9: return ['C_a', 'tau_a', 'C_b', 'tau_b', 'C_g', 'tau_g', 'C_d', 'tau_d', 'tau_e'] elif num_pars==10: return [ 'C_a', 'tau_a', 'C_b', 'tau_b', 'C_g', 'tau_g', 'C_d', 'tau_d', 'C_e', 'tau_e'] return []
def validate_heart_rate_timestamp(in_heart_rate, heart_rate_expected_keys): """Validate inputted json data This function tests 3 criteria for the inputted json file. 1. It must be a dictionary 2. It must contain all of the expected_keys: "patient_id" and "heart_rate" 3. It must contain the correct data types for each key. All values must be integers or integers in a string format. The appropriate error message will be returned based on what the json file is missing or has incorrect. If the json file has the correct format and data types, the function will return True, 200 as a passing boolean and status_code. This function will also validate any integers that have been entered as a string data type. :param in_heart_rate: This is a dictionary from the inputted json file :param heart_rate_expected_keys: This is a dictionary containing keys for "patient_id" and "heart_rate". The value of each key is the expected data type (int). :returns: This function returns either an error string and an error code describing the validation error, or True, 200 if no errors occurred. """ if type(in_heart_rate) is not dict: return "The input was not a dictionary", 400 for key in heart_rate_expected_keys: if key not in in_heart_rate: return "The key {} is missing from input".format(key), 400 if type(in_heart_rate[key]) is not heart_rate_expected_keys[key]: try: in_heart_rate[key] = int(in_heart_rate[key]) except ValueError: return "The key {} has the wrong data type".format(key), 400 return True, 200
def _insert_breaks(s, min_length, max_length): """Inserts line breaks to try to get line lengths within the given range. This tries to minimize raggedness and to break lines at punctuation (periods and commas). It never splits words or numbers. Multiple spaces may be converted into single spaces. Args: s: The string to split. min_length: The requested minimum number of characters per line. max_length: The requested minimum number of characters per line. Returns: A copy of the original string with zero or more line breaks inserted. """ newline = '\\n' if len(s) < min_length: return s # Try splitting by sentences. This assumes sentences end with periods. sentences = s.split('.') # Remove empty sentences. sentences = [sen for sen in sentences if sen] # If all sentences are at least min_length and at most max_length, # then return one per line. if not [sen for sen in sentences if len(sen) > max_length or len(sen) < min_length]: return newline.join([sen.strip() + '.' for sen in sentences]) # Otherwise, divide into words, and use a greedy algorithm for the first # line, and try to get later lines as close as possible in length. words = [word for word in s.split(' ') if word] line1 = '' while (len(line1) + 1 + len(words[0]) < max_length and # Preferentially split on periods and commas. (not ((line1.endswith('. ') or line1.endswith(', ')) and len(line1) > min_length))): line1 += words.pop(0) + ' ' # If it all fits on one line, return that line. if not words: return line1 ideal_length = len(line1) output = line1 line = '' while words: line += words.pop(0) + ' ' if words: potential_len = len(line) + len(words[0]) if (potential_len > max_length or potential_len - ideal_length > ideal_length - len(line) or (line.endswith('. ') and len(line) > min_length)): output += newline + line line = '' output += newline + line return output
def win_concat_quote(command_line: str, argument: str) -> str: """ appends the given argument to a command line such that CommandLineToArgvW will return the argument string unchanged. """ # from https://blogs.msdn.microsoft.com/twistylittlepassagesallalike/2011/04/23/everyone-quotes-command-line-arguments-the-wrong-way/ # by Daniel Colascione April 23, 2011 # // don't quote unless we actually # // need to do so - -- hopefully avoid problems if programs won't # // parse quotes properly # // result = command_line + " " if command_line else "" # vdc - I will automatically add a space if argument: # if (Force == false &$ Argument.empty() == false && if len(argument.split()) == 1: # // if no white space or double quote embedded in argument if '"' not in argument: # Argument.find_first_of(L" \t\n\v\"") == Argument.npos) result += argument # { CommandLine.append(Argument); } return result # else { result += '"' # CommandLine.push_back(L'"'); it = 0 end = len(argument) while it < end: # for (auto It = Argument.begin () ;; ++It) { number_backslashes = 0 # unsigned NumberBackslashes = 0; char = argument[it] # while char == '\\': # while (It != Argument.end() && * It == L'\\') { it += 1 # ++It; number_backslashes += 1 # ++NumberBackslashes; try: char = argument[it] except IndexError: break # } if it >= end: # if (It == Argument.end()) # // Escape all backslashes, but let the terminating # // double quotation mark we add below be interpreted # // as a metacharacter. result += '\\' * (number_backslashes * 2) # CommandLine.append (NumberBackslashes * 2, L'\\'); break # break; # } elif char == '"': # else if (*It == L'"') { # // Escape all backslashes and the following # // double quotation mark. result += '\\' * (number_backslashes * 2 + 1) # CommandLine.append(NumberBackslashes * 2 + 1, L'\\'); result += char # CommandLine.push_back(*It); else: # else { # // Backslashes aren't special here. result += '\\' * number_backslashes # CommandLine.append(NumberBackslashes, L'\\'); result += char # CommandLine.push_back(*It); it += 1 result += '"' # CommandLine.push_back(L '"'); return result
def return_real_remote_addr(env): """Returns the remote ip-address, if there is a proxy involved it will take the last IP addres from the HTTP_X_FORWARDED_FOR list """ try: return env['HTTP_X_FORWARDED_FOR'].split(',')[-1].strip() except KeyError: return env['REMOTE_ADDR']
def bonenamematch(name1, name2): """Heuristic bone name matching algorithm.""" if name1 == name2: return True if name1.startswith("Bip01 L "): name1 = "Bip01 " + name1[8:] + ".L" elif name1.startswith("Bip01 R "): name1 = "Bip01 " + name1[8:] + ".R" if name2.startswith("Bip01 L "): name2 = "Bip01 " + name2[8:] + ".L" elif name2.startswith("Bip01 R "): name2 = "Bip01 " + name2[8:] + ".R" if name1 == name2: return True return False
def _convert_space_to_shape_index(space): """Map from `feature` to 0 and `sample` to 1 (for appropriate shape indexing). Parameters ---------- space : str, values=('feature', 'sample') Feature or sample space. Returns ------- return : int, values=(0, 1) Index location of the desired space. """ if space == 'feature': return 1 if space == 'sample': return 0
def show_database_like(db_name): """Rerurns the command Arguments: db_name {string} -- [description] Returns: string -- [description] """ return "SHOW DATABASES LIKE '" + db_name+ "'"