content
stringlengths
42
6.51k
def normalize_enum_constant(s): """Return enum constant `s` converted to a canonical snake-case.""" if s.islower(): return s if s.isupper(): return s.lower() return "".join(ch if ch.islower() else "_" + ch.lower() for ch in s).strip("_")
def combine(list_of_values, sep=','): """Split and sum list of sep string into one list. """ combined = sum( [str(values).split(sep) for values in list(list_of_values)], [] ) if combined == ['-']: combined = None return combined
def pa_bbm_hash_mock(url, request): """ Mock for Android autoloader lookup, new site. """ thebody = "http://54.247.87.13/softwareupgrade/BBM/bbry_qc8953_autoloader_user-common-AAL093.sha512sum" return {'status_code': 200, 'content': thebody}
def index2slot(sx, sy, ox, oy): """**Return slot number of an inventory correlating to a 2d index**.""" print((sx, sy, ox, oy)) if not (0 <= sx < ox and 0 <= sy < oy): raise ValueError(f"{sx, sy} is not within (0, 0) and {ox, oy}!") return sx + sy * ox
def _to_camel_case(string): """Switch from snake to camelcase strict. Note: This currently capitalizes the first word which is not correct camelcase. """ return string.replace('_', ' ').title().replace(' ', '')
def dump_cookies(cookies_list): """Dumps cookies to list """ cookies = [] for c in cookies_list: cookies.append({ 'name': c.name, 'domain': c.domain, 'value': c.value}) return cookies
def generate_base_code(naval_base: bool, scout_base: bool, pirate_base: bool) -> str: """Returns a base code, one of: A -- Naval Base and Scout Base/Outpost G -- Scout Base/Outpost and Pirate Base N -- Naval Base P -- Pirate Base S -- Scout Base/Outpost ...
def c_to_f(c): """ Convert celcius to fahrenheit """ return c * 1.8 + 32.0
def xyz_to_rgb(cs, xc, yc, zc): """ Given an additive tricolour system CS, defined by the CIE x and y chromaticities of its three primaries (z is derived trivially as 1-(x+y)), and a desired chromaticity (XC, YC, ZC) in CIE space, determine the contribution of each primary in a linear combinatio...
def get_pod_unique_name(pod): """Returns a unique name for the pod. It returns a pod unique name for the pod composed of its name and the namespace it is running on. :returns: String with namespace/name of the pod """ return "%(namespace)s/%(name)s" % pod['metadata']
def _octet_bits(o): """ Get the bits of an octet. :param o: The octets. :return: The bits as a list in LSB-to-MSB order. :rtype: list """ if not isinstance(o, int): raise TypeError("o should be an int") if not (0 <= o <= 255): raise ValueError("o should be between 0 and ...
def average_even_is_average_odd(hand): """ :param hand: list - cards in hand. :return: bool - are even and odd averages equal? """ even = 0 odd = 0 even_count = 0 odd_count = 0 for index, element in enumerate(hand): if index % 2 == 0: even += element ...
def css_dict(style): """ Returns a dict from a style attribute value. Usage:: >>> css_dict('width: 2.2857142857142856%; overflow: hidden;') {'overflow': 'hidden', 'width': '2.2857142857142856%'} >>> css_dict('width:2.2857142857142856%;overflow:hidden') {'overflow': 'hidden...
def billing_mode_validator(x): """ Property: Table.BillingMode """ valid_modes = ["PROVISIONED", "PAY_PER_REQUEST"] if x not in valid_modes: raise ValueError( "Table billing mode must be one of: %s" % ", ".join(valid_modes) ) return x
def format_size(size): """Return file size as string from byte size.""" for unit in ('B', 'KB', 'MB', 'GB', 'TB'): if size < 2048: return "%.f %s" % (size, unit) size /= 1024.0
def latex_bold(text: str) -> str: """Format text in bold font using Latex.""" return rf"\textbf{{{text}}}"
def get_right_index_of_name(clean_tree_str, one_name): """Get the right index of givin name. # 111111111122222222 # 0123456789012345678901234567 # | >>> get_right_index_of_name('((a,((b,c),(ddd,...
def _get_hostname(server): """Get server hostname from an atest dict. >>> server = {'hostname': 'foo.example.com'} # from atest >>> _get_hostname(server) 'foo' """ return server['hostname'].partition('.')[0]
def indent_string(string: str) -> str: """Indents string for printing. Parameters ---------- string : str Input string to be printed. Returns ------- str A string representation of lines with indentation. """ output = "" for line in string.splitlines(): ...
def unravel_group_params(unfolded_parameters_group): """Take a dict('group:k'-> p) and return a dict(group -> {k->p}) """ parameters_group = {} for k, p in unfolded_parameters_group.items(): group_name, k = k.split(':') group_params = parameters_group.get(group_name, {}) group_pa...
def permutations(input_list): """Return a list containing all permutations of the input list. Note: This is a recursive function. >>> perms = permutations(['a', 'b', 'c']) >>> perms.sort() >>> for perm in perms: ... print perm ['a', 'b', 'c'] ['a', 'c', 'b'] ['b', 'a', 'c'] ...
def as_tuple(*values): """ Convert sequence of values in one big tuple. Parameters ---------- *values Values that needs to be combined in one big tuple. Returns ------- tuple All input values combined in one tuple Examples -------- >>> as_tuple(None, (1, 2,...
def dump_datetime(datetime_obj): """convert datetime object to string format""" if datetime_obj is None: return None return datetime_obj.strftime("%Y-%m-%dT%H:%M:%SZ")
def fib(n): """Fibonacci example function Args: n (int): integer Returns: int: n-th Fibonacci number """ assert n > 0 a, b = 1, 1 for _i in range(n - 1): a, b = b, a + b return a
def return_both_present(xs, ys): """ merge sorted lists xs and ys. Return a sorted result """ result = [] xi = 0 yi = 0 while True: if xi >= len(xs): return result if yi >= len(ys): return result if xs[xi] < ys[yi]: xi += 1 elif ...
def get_vars(theme): """ Return dict of theme vars. """ return {k: theme[k] for k in iter(theme)}
def price_text(price): """Give price text to be rendered in HTML""" if price == 0: return "Gratis" return str(price)
def to_string(obj, digits=0): """Gets a list or dictionary and converts to a readable string""" if isinstance(obj, dict): return [''.join([str(k), ": ", ("{0:0.%df}" % digits).format(v)]) for k, v in obj.items()] return [("{0:0.%df}" % digits).format(i) for i in obj]
def make_placeholder(s): """Converts a string to placeholder format {{string}}""" return '{{'+s+'}}'
def scale2D(v,scale): """Returns a scaled 2D vector""" return (v[0] * scale, v[1] * scale)
def get_unique_combinations(combinations_per_row): """Performs set.union on a list of sets Parameters ---------- combinations_per_row : List[Set[Tuple[int]]] list of combination assignments per row Returns ------- Set[Tuple[int]] all unique label combinations """ r...
def _indent(content): """Add indentation to all lines except the first.""" lines = content.split("\n") return "\n".join([lines[0]] + [" " + l for l in lines[1:]])
def adjacency_from_edges(edges): """Construct an adjacency dictionary from a set of edges. Parameters ---------- edges : list A list of index pairs. Returns ------- dict A dictionary mapping each index in the list of index pairs to a list of adjacent indices. E...
def derive_single_object_url_pattern(slug_url_kwarg, path, action): """ Utility function called by class methods for single object views """ if slug_url_kwarg: return r'^%s/%s/(?P<%s>[^/]+)/$' % (path, action, slug_url_kwarg) else: return r'^%s/%s/(?P<pk>\d+)/$' % (path, action)
def extractDidParts(did): """ Parses and returns a tuple containing the prefix method and key string contained in the supplied did string. If the supplied string does not fit the pattern pre:method:keystr a ValueError is raised. :param did: W3C DID string :return: (pre, method, key string) a tuple...
def resource_record(record): """ """ alias_target_dns_name = '' alias_target_evaluate_health = '' if record.get("AliasTarget"): alias_target_dns_name = record.get("AliasTarget")['DNSName'] or None alias_target_evaluate_health = str(record.get("AliasTarget")['EvaluateTargetHealth']) o...
def normalized_total_time(p, max_time=86400000): # by default 24 h (in ms) """If time was longer than max_time, then return max_time, otherwise return time.""" v = int(p["result.totalTimeSystem"]) return max_time if v > max_time else v
def does_need_adjust(change, next_value, limit): """Check if change of the next_value will need adjust.""" return change and (next_value - 1 < 0 or next_value + 1 >= limit)
def float_to_decimal(f: float): """ This function is necessary because python transform float like 2.0 in '2.00' """ return "{:.2f}".format(f)
def glonass_nav_decode(dwrds: list) -> dict: """ Helper function to decode RXM-SFRBX dwrds for GLONASS navigation data. :param list dwrds: array of navigation data dwrds :return: dict of navdata attributes :rtype: dict """ return {"dwrds": dwrds}
def divisible(num): """Divisible by 100 is True, otherwise return False.""" return num % 100 == 0
def configget(config, section, var, default): """ gets parameter from config file and returns a default value if the parameter is not found """ try: ret = config.get(section, var) except: print("returning default (" + default + ") for " + section + ":" + var) ret = defaul...
def userpar_override(pname, args, upars): """ Implement user parameter overrides. In this implementation, user parameters *always* take precedence. Any user parameters passed to the Primitive class constructor, usually via -p on the 'reduce' command line, *must* override any specified recipe paramet...
def parse_int(str, fallback): """ Safely parses string to integer. Args: str: (str) Strint to be parsed. fallback: (str) Default value. Returns: (int) Parsed value or default value in case of failure. """ try: return int(str) except (ValueError, TypeError): return fallback
def repr_args(args, kwargs): """Stringify a set of arguments. Arguments: args: tuple of arguments as a function would see it. kwargs: dictionary of keyword arguments as a function would see it. Returns: String as you would write it in a script. """ args_s = ("{}, " if kwargs...
def replace(filename, replacements): """Applies any number of substitutions in the replacements map to the file referenced by filename. Any modified file is written back, and the original file overwritten. The number of lines modified is returned. """ zero = 0 try: alpha = open(filename)...
def encodeUnicodeToBytes(value, errors="strict"): """ Accepts an input "value" of generic type. If "value" is a string of type sequence of unicode (i.e. in py2 `unicode` or `future.types.newstr.newstr`, in py3 `str`), then it is converted to a sequence of bytes. This function is useful for enc...
def stripped_lines(lines, ignore_comments, ignore_docstrings, ignore_imports): """return lines with leading/trailing whitespace and any ignored code features removed """ strippedlines = [] docstring = None for line in lines: line = line.strip() if ignore_docstrings: ...
def pprint_lon_lat(lon, lat, decimals=0): """Pretty print a lat and and lon Examples: >>> pprint_lon_lat(-104.52, 31.123) 'N31W105' >>> pprint_lon_lat(-104.52, 31.123, decimals=1) 'N31.1W104.5' """ # Note: strings must be formatted twice: # ff = f"{{:02.1f}}" ; f"{hemi_ew}{ff}".form...
def _get_avoid_options(avoid_boxes): """ Extracts checked boxes in Advanced avoid parameters. :param avoid_boxes: all checkboxes in advanced parameter dialog. :type avoid_boxes: list of QCheckBox :returns: avoid_features parameter :rtype: JSON dump, i.e. str """ avoid_features = [] ...
def default_scrubber (text): """ remove spurious punctuation (for English) """ return text.lower().replace("'", "")
def difference(a, b): """ Returns the symmetric difference of sets 'a' and 'b'. In plain english: Removes all items that occur in both 'a' and 'b' Difference is actually set_a.symmetric_difference(set_b), not set.difference(). See 'minus' for set.difference(). """ return a.symmetr...
def get_angle_from_rotated_rect(rotrect): """ Computes the relative angle to the sub needed to align to the rectangle along its long axis. """ # True if taller than wide if rotrect[1][0] < rotrect[1][1]: return rotrect[2] return rotrect[2] + 90
def rf_on_val(n): """Returns RF 'ON' value for bunchers, DTL or CCL rf, n can be a string e.g. 'TA' or '05', or a number 5. Arguments: n(str or int): module or buncher number """ # Make two character area from input area = str(n).upper().zfill(2) if area in ['PB', 'MB', 'TA', 'TB', ...
def get_last_digits_of_bignum(base:int, power:int, digitcount:int) -> str: """ Pessimized algorithm for getting the last digits of a bignum. :param base: base of exponent. :param power: power of exponent. :param digitcount: how many digits to return. :return: str containing the last digits. ...
def make_iterable(obj): """Get a iterable obj.""" if isinstance(obj, (tuple, list)): return obj return obj,
def is_prime(number): """States if a number is prime. :param number: A number :type number: int :rtype: bool **Examples** >>> is_prime(31) True >>> is_prime(42) False """ for factor in range(2, number): if not number % factor: return False return ...
def proj4_dict_to_str(proj4_dict, sort=False): """Convert a dictionary of PROJ.4 parameters to a valid PROJ.4 string""" items = proj4_dict.items() if sort: items = sorted(items) params = [] for key, val in items: key = str(key) if key.startswith('+') else '+' + str(key) if ke...
def time2float(line): """ converts formatted time 'nn:nn:nn:nnnnn' to float >>> time2float('21:33:25:5342') 77605.005342000004 """ spline = line.split(':') ints = [int(spline[i]) for i in range(4)] result = 3600*ints[0] + 60*ints[1] + ints[2] + 1E-6*ints[3] return result
def arrow_out(value): """Convert an Arrow object to timestamp. :param Arrow value: The Arrow time or ``None``. :returns int: The timestamp, or ``None`` if the input is ``None``. """ return value.timestamp if value else None
def get_bin(x, n=0): """ Get the binary representation of x. Parameters ---------- x : int n : int Minimum number of digits. If x needs less digits in binary, the rest is filled with zeros. Returns ------- str """ return format(x, 'b').zfill(n)
def findKeyInJson(jsonDict, searchKey): """ Search for recursive for a key in a JSON dictionary. General purpose function to look for a key in a json file. Parameters ---------- jsonDict : dict() Dictionary containing a json structure searchKey : str The key to look for in the ...
def kelvin_to_rankine(temp): """ From Kelvin (K) to Rankine (R) """ return temp*9/5
def hex2rgb(str_rgb): """Transform hex RGB representation to RGB tuple. :param str_rgb: 3 hex char or 6 hex char string representation :returns: RGB 3-uple of float between 0 and 1 >>> from ase_notebook.color import hex2rgb >>> hex2rgb('#00ff00') (0.0, 1.0, 0.0) >>> hex2rgb('#0f0') (...
def dump_required_field(value): """dump required_field""" if value is True: return "y" return "n"
def check_views(views): """Checks which views were selected.""" if views is None: return range(3) views = [int(vw) for vw in views] out_views = list() for vw in views: if vw < 0 or vw > 2: print('one of the selected views is out of range - skipping it.') out_vie...
def is_dataclass(value): """ Dataclass support is only enabled in Python 3.7+, or in 3.6 with the `dataclasses` backport installed """ try: from dataclasses import is_dataclass return is_dataclass(value) except ImportError: return False
def validate_rsvps(args): """validate rsvp details""" try: if args["response"] == '' or \ args["user_id"] == '' or \ args["meetup_id"] == '': return{ "status": 401, "error": "Fields cannot be left empty" }, 401 elif...
def reverse(str): """Reverses the characters in a string.""" return str[::-1]
def statement_passive_verb(stmt_type): """Return the passive / state verb form of a statement type. Parameters ---------- stmt_type : str The lower case string form of a statement type, for instance, 'phosphorylation'. Returns ------- str The passive/state verb form...
def _parse_file_move(file_move): """Return the (old_filename, new_filename) tuple for a file move.""" _, old_filename, new_filename = file_move.split() return (old_filename, new_filename)
def try_read_file(path, length): """Try to read the designated file with the specified length. Fill with zeroes if it does not exist.""" try: with open(path, "rb") as f: bytes = f.read() # If the file was as long as expected, return its contents if len(bytes) ...
def cell_background_number_of_cases(val,max): """Creates the CSS code for a cell with a certain value to create a heatmap effect Args: val ([int]): the value of the cell Returns: [string]: the css code for the cell """ opacity = 0 try: v = abs(val) color = '193, ...
def _MakeCounterName(key_id, tag): """Helper to create a sharded Counter name. Args: key_id: Int unique id (usually a model entity id). tag: String tag which hints at the counter purpose. Returns: String to be used as a sharded Counter name. """ return '%s_%s' % (key_id, tag)
def format_usgs_sw_site_id(stationID): """Add leading zeros to NWIS surface water sites, if they are missing. See https://help.waterdata.usgs.gov/faq/sites/do-station-numbers-have-any-particular-meaning. Zeros are only added to numeric site numbers less than 15 characters in length. """ if not str(s...
def format_sort_key(sort_key): """ format sort key (list of integers) with | level boundaries >>> str(format_sort_key([1, 0, 65535])) '0001 | FFFF' """ return " ".join( ("{:04X}".format(x) if x else "|") for x in sort_key )
def calcFixedAspectRatio(win_dim, tar_dim): """ @param: win_dim current window dim (width, height) @param: tar_dim target image dim (width, height) """ w, h = win_dim tw, th = tar_dim if w > h: h_r = h ; w_r = int(h * (tw/ th)) if w_r > w: h_r = int(w * (th / tw))...
def s_to_min(value): """Convert seconds to minutes.""" return "{}:{:02d}".format(int(value // 60), int(value % 60))
def split_dict(dic, *keys): """Return two copies of the dict. The first will contain only the specified items. The second will contain all the *other* items from the original dict. Example:: >>> split_dict({"From": "F", "To": "T", "Received", R"}, "To", "From") ({"From": "F", "To": ...
def fill_width(bytes_, width): """ Ensure a byte string representing a positive integer is a specific width (in bytes) :param bytes_: The integer byte string :param width: The desired width as an integer :return: A byte string of the width specified """ while ...
def __trimTrailingSlash__(args): """ Takes in a list filepaths and removes any trailing /'s :param arg: list of string file paths :return: list of filepaths with trailing /'s removed """ for i in range(len(args)): if args[i][-1] == "/": args[i] = args[i][:-1] return args
def utf8len(s): """ Get the byte number of the utf-8 sentence. """ return len(s.encode('utf-8'))
def is_lambda_map(mod): """check for the presence of the LambdaMap block used by the torch -> pytorch converter """ return 'LambdaMap' in mod.__repr__().split('\n')[0]
def get_tag_type(tag): """ Simple helper """ return tag.split('-')[-1]
def demo(name: str, demo: str) -> str: """Description.""" return f"{name}: {demo}"
def int_to_bytes(n, minlen=0): # helper function """ Int/long to byte string. """ nbits = n.bit_length() + (1 if n < 0 else 0) # plus one for any sign bit nbytes = (nbits+7) // 8 # number of whole bytes b = bytearray() for _ in range(nbytes): b.append(n & 0xff) n >>= 8 if minl...
def flatten_dict(d, delim="_"): """Go from {prefix: {key: value}} to {prefix_key: value}.""" flattened = {} for k, v in d.items(): if isinstance(v, dict): for k2, v2 in v.items(): flattened[k + delim + k2] = v2 else: flattened[k] = v return flatten...
def extended_gcd(a, b): """ >>> extended_gcd(10, 6) (2, -1, 2) >>> extended_gcd(7, 5) (1, -2, 3) """ assert a >= 0 and b >= 0 if b == 0: d, x, y = a, 1, 0 else: (d, p, q) = extended_gcd(b, a % b) x = q y = p - q * (a // b) assert a % d == 0 and...
def simtelHistogramFileName(run, primary, arrayName, site, zenith, azimuth, label=None): """ sim_telarray histogram file name. Warning ------- zst extension is hardcoded here. Parameters ---------- arrayName: str Array name. site: str Paranal or LaPalma. zen...
def sort_module_names(modlst): """ Sort a list of module names in order of subpackage depth. Parameters ---------- modlst : list List of module names Returns ------- srtlst : list Sorted list of module names """ return sorted(modlst, key=lambda x: x.count('.'))
def rreplace(s, old, new, occurrence=-1): """ Replace old with new starting from end of the string :param s: The string to be transformed :param old: Search string :param new: Replacement string :param occurrence: Number of replacements to do :return: """ li = s.rsplit(old, occurrenc...
def dedup_and_title_case_names(names): """Should return a list of title cased names, each name appears only once""" # return a list of a dict keys # by rule the keys of a dict are unique # list comprehension # title() capitalize all the words and lowers # the rest return list({name.ti...
def nn_min(x: int, y: int) -> int: """ the non-negative minimum of x and y """ if x < 0: return y if y < 0: return x if x < y: return x return y
def markup_num(n_str): """Generate Wikipedia markup for case numbers in region table.""" return ' style="color:gray;" |0' if n_str == '0' else n_str
def axiom_generator_percept_sentence(t, tvec): """ Asserts that each percept proposition is True or False at time t. t := time tvec := a boolean (True/False) vector with entries corresponding to percept propositions, in this order: (<stench>,<breeze>,<glitter>,<bump>,<scream...
def get_config_options(otype): """ Return list of valid configuration options for nodes and dispatcher.""" if otype is 'node': return ['node_name', 'node_type', 'node_id', 'node_description', 'primary_node', 'ip', 'port_frontend', 'port_backend', 'port_publisher', 'n_responders', 'lsl_stream_name', 'pri...
def Or(input1,input2): """ Logic for OR operation Parameters ---------- input1 (Required) : First input value. Should be 0 or 1. input2 (Required) : Second input value. Should be 0 or 1. """ return f"( {input1} | {input2} )"
def filter_dict_values(D): """Return a shallow copy of D with all `None` values excluded. >>> filter_dict_values({'a': 1, 'b': 2, 'c': None}) {'a': 1, 'b': 2} >>> filter_dict_values({'a': 1, 'b': 2, 'c': 0}) {'a': 1, 'b': 2, 'c': 0} >>> filter_dict_values({}) {} >>> filter_dict_value...
def parse_input(puzzle_input: str) -> range: """Split the input of dash-separated numbers into an inclusive range""" start, last = map(int, puzzle_input.split("-")) return range(start, last + 1)
def get_rhombus_image (key: str) -> str: """Return the full uri of a face image given an aws s3 key :param key: The key to get the URI for :return: The full URI of the image """ return "https://media.rhombussystems.com/media/faces?s3ObjectKey=" + key