content
stringlengths
42
6.51k
def cdm2_to_nl(m): """Convert candelas/m2 to nl. Formula taken from https://converter.eu/luminance/#1_Candela/Square_Meter_in_Lambert """ return 0.000314159265358979*m*(1000000000)
def replace_pad(l, new_symbol='-'): """<pad> refers to epsilon in CTC replace with another symbol for readability""" new_l = [] for x in l: if x == "<pad>": new_l.append(new_symbol) else: new_l.append(x) return new_l
def filter_output_columns(output_columns, filter_columns): """ Filters a list of columns and only keeps those present in a list of allowed columns. Returns original list of columns if no allowed columns specified. :param output_columns: a column list to filter :param filter_columns: a list of allow...
def tags(fs): """Extract tags from a collection of features.""" return type(fs)(f.tag for f in fs)
def round_time_worked(time_worked, block_size=15 * 60): """ Round a period of time worked to the nearest block. Typically this is used to round time worked to the closest 15 minute block. Args: time_worked: The time period to round, in seconds. block_size: T...
def partition(mylist, p, r): """ Purpose: return a position of the pivot Invariant: after the call, everything left of pivot is <= pivot everything right of pivot is >= pivot """ # what if the list passed is empty? # what if the list passed is singleton? if r == p: return r s...
def bytes_isalpha(x: bytes) -> bool: """Checks if given bytes object contains only alphabetic elements. Compiling bytes.isalpha 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 che...
def decode(text): """Decode DNA""" dna = [] end = len(text) - 1 for i, char in enumerate(text): if char.isnumeric(): continue elif i == end: dna.append(char) elif text[i + 1].isnumeric(): dna.append(char * int(text[i + 1])) else: ...
def dot(v,w): """v_1*w_1+...+v_n*w_n""" return sum(v_i*w_i for v_i,w_i in zip(v,w))
def substract(v1, v2): """ Returns the difference of a two 2-D vectors. """ return (v2[0] - v1[0], v2[1] - v1[1])
def contains(list1, list2): """ Check if some elements of list1 appear in list2 Return the intersection of the two lists """ return [ it1 for it1 in list1 if it1 in list2 ]
def find_all_indexes(text=str, pattern=str) -> list: """Return a list of starting indexes of all occurrences of pattern in text, or an empty list if not found. - Best case: O(1) If there is no pattern and one char in the text - Worse Case: O(n) if we have to loop to the end - If there is a pattern: ...
def _repr_strip(mystring): """ Returns the string without any initial or final quotes. """ r = repr(mystring) if r.startswith("'") and r.endswith("'"): return r[1:-1] else: return r
def myfuncPrimeSieve(n): """ This function generates and returns prime numbers from 2 up to n via the Sieve of Eratosthenes algorithm. Example of usage: getAns = myfuncPrimeSieve( 20 ) print(getAns) """ thelist = list(range(3, n, 2)) #generates odd numbers starting from 3 thepri...
def _to_list(key_values_dict, sort = True): """Converts a `dict` to a flattened key-value `list`. Args: key_values_dict: A `dict` whose key-values will be written to the `list`. sort: Optional. Specifies whether the keys should be sorted before s...
def non_adjusted_weight(k0, k1): """ Normalised un-adjusted weight based on kappas. :param k0: Kappa 0, the primary kappa for this weight computation :param k1: Kappa 1, secondry kappa (alternate cue) """ return k0 / (k1 + k0)
def strComp(s1, s2): """Compares string1 vs string2 returns a tuple (a, b) a = number of common caracters at the same position b = number of common caracters at different position """ a, b = 0, 0 ## Count of common caracters at the same position i = 0 while i < len(s1) and i < len(s...
def format_metrics(metrics): """ Method to return dict with formatted metrics keys. From tuple of strings to string with dunder ('__') between values :param metrics: unformatted metrics. keys looks like ('test', 'AUC') :type metrics: dict :return: formatted metrics. keys looks like 'test__AUC' ...
def bounding_box(coords): """Runs through a collection of x,y tuple pairs and extracts the values (xmin,ymin),(xmax,ymax).""" xmin = coords[0][0] ; xmax = coords[0][0] ymin = coords[0][1] ; ymax = coords[0][1] for xy in coords[1:]: x, y, *_ = xy # if coordinates are not 2D then if onl...
def _D0N2_Deg1_2_linear(k1, k2): """ from 1d knots, return int_0^2 x b**2(x) dx """ return (k2 - k1) / 6.
def handler(msg): """ Writes input argument back-out to the standard output returning input as output. Generated by: `SQL Server Big Data Cluster` :param msg: The message to echo. :type msg: str :return: The input message `msg` as output `out`. """ print(msg) out = msg return ...
def make_elastic_uri(schema: str, user: str, secret: str, hostname: str, port: int) -> str: """Make an Elasticsearch URI. :param schema: the schema, e.g. http or https. :param user: Elasticsearch username. :param secret: Elasticsearch secret. :param hostname: Elasticsearch hostname. :param port...
def convert(name: str) -> str: """Convert path name into valid JSON. Parameters ---------- name : str a path name Returns ------- str valid JSON path """ if ('-' in name or ' ' in name): return '["{}"]'.format(name[1:]) return name
def sectionNofTotal (inputList, currentSection, numSections): """Returns the appropriate sublist given the current section (1..numSections)""" currentSection -= 1 # internally, we want 0..N-1, not 1..N size = len (inputList) perSection = size // numSections extra = size % numSections...
def what(func, addr): """Return the item for which we are looking.""" if func: return "func '%s'" % func return "address '%s'" % hex(addr)
def set_up_default_claims(clean_up=False): """Block of text to populate a Text widget.""" claims = ["this-is-a-fake-claim", "livestream-tutorial:b", "abcd0000efgh0000ijkl0000mopq0000rstu0000", "8e16d91185aa4f1cd797f93d7714de2a22622759", "LBRYPlaylists#d"] ...
def get_slice_stride(index_slice, dim_size): """Get slice stride info""" step = 1 if index_slice.step is None else index_slice.step start_default = 0 stop_default = dim_size if step < 0: start_default = -1 stop_default = -(dim_size + 1) start = start_default if index_slice.start ...
def get_label_color(status): """ Get a customized color of the status :param status: The requested status to get a customized color for :return: customized color """ colors = {'NEW':'grey', 'ASSIGNED':'blue', 'OPEN': 'orange', 'FIXED': 'purp...
def semicircles_to_degrees(semicircles): """Positional data conversion for *.fit files https://github.com/kuperov/fit/blob/master/R/fit.R """ return (semicircles * 180 / 2**31 + 180) % 360 - 180
def can_collapse(row): """ returns true if the given row can be collapsed to the left can also be a column """ for a,b in zip(row[1:], row): if a==0: continue if b==0 or a==b: return True return False
def _read_varint(raw_hex): """ Reads the weird format of VarInt present in src/serialize.h of bitcoin core and being used for storing data in the leveldb. This is not the VARINT format described for general bitcoin serialization use. """ n = 0 pos = 0 while True: data = raw_h...
def get_sympy_short_version(version): """ Get the short version of SymPy being released, not including any rc tags (like 0.7.3) """ parts = version.split('.') # Remove rc tags # Handle both 1.0.rc1 and 1.1rc1 if not parts[-1].isdigit(): if parts[-1][0].isdigit(): part...
def get_skolem(base_url: str, count: int) -> str: """Get skolem according to base URL.""" return base_url + ".well-known/skolem/" + str(count)
def format_num(val): """Return a suitable format string depending on the size of the value.""" if val > 50: return ".0f" if val > 1: return ".1f" else: return ".2f"
def merge_sort_counting(A): """Perform Merge Sort and return #comparisons.""" aux = [None] * len(A) def rsort(lo, hi): if hi <= lo: return (0,0) mid = (lo+hi) // 2 (lefts, leftc) = rsort(lo, mid) (rights, rightc) = rsort(mid+1, hi) (nswap, ncomp) = merge...
def _is_json(q): """Check if q is JSON. Parameters ---------- q : str Query string. Returns ------- bool True if q starts with "{" and ends with "}". """ return q.strip().startswith("{") and q.strip().endswith("}")
def get_rna_types_from(xrefs, name): """ Determine the rna_types as annotated by some database. Parameters ---------- xrefs : iterable The list of xrefs to fitler to extract the rna types from. name : str The name of the database to use. Returns ------- rna_types : ...
def find_first(d, aliases, default="<unknown>"): """ Returns the value of the first key found in "aliases" """ for a in aliases: if a in list(d.keys()): return d[a] return default
def write_int_ranges(int_values, in_hex=True, sep=" "): """From a set or list of ints, generate a string representation that can be parsed by parse_int_ranges to return the original values (not order_preserving).""" if not int_values: return "" num_list = [] int_values = iter(sorted(int_v...
def flop_gemm(n, k): """# of + and * for matmat of nxn matrix with nxk matrix, with accumulation into the output.""" return 2*n**2*k
def hypara_check(start, end, num_data): """true:ok, false:out""" ans = True if start > end: ans = False print("####### INVERSE start <=> end ??") elif (start > num_data) or (end > num_data): ans = False print("####### PLEASE INPUT NUMBER:(start,end) UNDER " + str(num_data...
def list_to_dict(dicts): """ Convert a list of dictionaries to a dictionary of list """ new_dict = dict() if isinstance(dicts, list): for key in dicts[0]: new_dict[key] = [d[key] for d in dicts] return new_dict
def flip_ith_occurrence_of_zero(given_string, index): """ :param given_string: :param index: :return: """ local_index = 0 string_builder = "" for item in given_string: if item == "0": local_index += 1 if local_index == index: string_builder += ...
def fmt_dft_token(val): """Generate obfuscated default token argument description This secondary utility function is supporting formatting of command line argument help string """ if val is None: return "" token_len = len(val) char_cnt = max(int((token_len-4)/6), 0) token = "{0:s}{...
def parse_bdist_wininst(name): """Return (base.css,pyversion) or (None,None) for possible .exe name""" lower = name.lower() base, py_ver, plat = None, None, None if lower.endswith('.exe'): if lower.endswith('.win32.exe'): base = name[:-10] plat = 'win32' elif lo...
def numToLetter(N, ABC=u'ABCDEFGHIJKLMNOPQRSTUVWXYZ' ): """ Converts a number in to a letter, or set of letters, based on the contents of ABC. If ABC contains the alphabet (which is the default behaviour) then for a number n this will result in the same string as the name of the nth column in a normal spreads...
def isTIFF(filename: str) -> bool: """Check if file name signifies a TIFF image.""" if filename is not None: if(filename.casefold().endswith('.tif') or filename.casefold().endswith('.tiff')): return True return False
def set_lineage_cube(data: dict, dict_tables: dict): """ "name": "", "description": "", "columns": [...], "partitions": [...], "measures": [...], "annotations": [...] """ print() print(79 * '*') print(f"Configuring parameters in {(data['model']['name'])}") print(79 * '*')...
def ka_cont(T): """ Thermal conductivity of air, neglecting non-continuum effects. See :func:`ka` for details. Parameters ---------- T : ambient air temperature surrounding droplet, K Returns ------- float :math:`k_a(T)` in J/m/s/K See Also -------- ka : i...
def lmap(f, x): """list(map(f, x)). Converts a map into a list containing (key,value) pairs.""" return list(map(f, x))
def va_from_string(value): """ Convert HEX string to int :param str value: int as string :return int: virtual address """ try: return int(value.rstrip("L"), 16) except ValueError: return 0
def prettify_url(url): """Return a URL without its schema """ if not url: return url split = url.split('//', 1) if len(split) == 2: schema, path = split else: path = url return path.rstrip('/')
def largest_prime_factor(n: int) -> int: """ Gets largest prime factor of :param n: """ largest = 1 for d in range(2, n+1): if n % d == 0: largest = max(largest, d) while n % d == 0: n //= d if d * d > n: # n doesnt have at two non-trivi...
def kma(lbm): """ The Katch-McArdle Formula for resting daily energy expenditure (RDEE). This formula takes lean body mass/fat-free mass (in kilograms) as the only argument. McArdle, W (2006). Essentials of Exercise Physiology. Lippincott Williams & Wilkins. p. 266. ISBN 9780495014836. """ return 3...
def parse_line(line): """ line is in the format distance,zipcode,city,state,gender,race,income,price """ line = line.strip().split(",")[3:] state = str(line[0]) gender = str(line[1]) race = str(line[2]) income = str(line[3]) price = str(line[4]) return [state, gender, race, inco...
def get_points_to_next_level(current_level): """ returns the number of average points needed to advance to the next level """ if current_level == 1: return 50 elif current_level == 2: return 125 elif current_level == 3: return 225
def deblank(s): """ Returns: s but with blanks removed Parameter: s the string to edit Precondition s is a string for example: deblank(' 1 23 4') returns '1234' """ if s == '': return s elif len(s) == 1: if s != ' ': return s else: ...
def fs_join(*args): """Like os.path.join, but never returns '\' chars""" from os.path import join return join(*args).replace('\\','/')
def glossary_term_decorator(props): """ Draft.js ContentState to database HTML. """ # return DOM.create_element('span', { # 'data-term_id': props['term_id'], # }, props['children']) return '{}'.format( props['children'] )
def make_mmi_cmd(fa): """Return a minimap2 cmd string to build mmi index. """ return 'minimap2 -x map-pb -d {fa}.mmi {fa}'.format(fa=fa)
def coord(row, col): """ returns coordinate values of specific cell within Sudoku Puzzle""" return row*9+col
def ns_between(l, r, ns): """Checks if all ns are between l and r (inclusive).""" return all(l <= n <= r for n in ns)
def gbslve(shift, a, b): """this procedure performs elimination to solve for the n-th component of the solution delta to the equation (jn - shift*identity) * delta = en, where en is the vector of all zeroes except for 1 in the n-th position. the matrix jn is symmetric tridiagonal, with dia...
def _is_file_valid(name): """Decide if a file is valid.""" return not name.startswith('.')
def generate_file_path(package_path, file_name): """ Dynamically generate full path to file, including filename and extension. :param package_path: (array) ordered list of packages in path to test file :param file_name: (string) name of the file w/ test, including the extension :return: (string) fu...
def try_parse_ticket_ids(title): """Get ticket id from PR title. Assumptions: - ticket id or special prefix before PR title - no whitespace before ticket id - whitespace between ticket id and PR title Transformations (for the worst case): "ggrc-1234/1235: Do something" -> ["GGRC-1234", "GGRC-123...
def get_dir_delta(beforelisting, afterlisting): """Determines which files were added, removed, or remained the same in a directory.""" deltas=[] # Find files added. for a in afterlisting: added=1 for b in beforelisting: added=added and b!=a deltas.append((added, a)...
def find_cutlag(weight): """Compute the maximum valid lag time from trajectory weights. Parameters ---------- weights : (n_frames,) ndarray Weight of each configuration in a trajectory. Returns ------- int Maximum valid lag time in units of frames. """ last = len(...
def m(x0: float, x1: float, y0: float, y1: float) -> float: """ Simple gradient function. Parameters ---------- x0 : float x co-ordinate at time 0. x1 : float x co-ordinate at time 1. y0 : float y co-ordinate at time 0. y1 : float y co-ordinate at time...
def is_quoted(value): """ Return a single or double quote, if a string is wrapped in extra quotes. Otherwise return an empty string. """ ret = "" if ( isinstance(value, str) and value[0] == value[-1] and value.startswith(("'", '"')) ): ret = value[0] retur...
def flatten(list): """Flatten a list of elements into a unique list Author: Christophe Simonis Examples: >>> flatten(['a']) ['a'] >>> flatten('b') ['b'] >>> flatten( [] ) [] >>> flatten( [[], [[]]] ) [] >>> flatten( [[['a','b'], 'c'], 'd', ['e', [], 'f']] ) ['a',...
def scale_up(threshold, dim): """Rescale up to actual values""" out = int(dim * threshold) return out
def checked_etag(etag, *, allow_none=False): """Validate etag string to ensure propare comparison. This function is used to assert that `DAVResource.get_etag()` does not add quotes, so it can be passed as `ETag: "<etag_value>"` header. Note that we also reject weak entity tags (W/"<etag_value>"), since...
def get_verify_listener_ports(module, listener_ports=None): """ Validate and get listener ports :param module: Ansible module object :param listener_ports: list of ports to for which backend server health status is required :return: formatted listener ports """ if listener_ports: i...
def range_factorial(num): """Solution that iterates over a range""" result = 1 i = iter(range(1, num + 1)) try: while True: result *= next(i) except StopIteration: pass return result
def classname(value, options=''): """ Returns classname. If options is given, checks if class name is in there before returning, else it returns None. """ cn = value.__class__.__name__.lower() if not options or cn in options: return cn return ''
def xor(x, y): """N.B.: not lazy like `or` ...""" return bool(x) != bool(y)
def _get_arg_index(line: str, cursor_pos: int) -> int: """Return which argument the cursor is currently on""" arg_idx = -1 i = 0 while i < cursor_pos: if line[i] == " ": arg_idx += 1 # Multiple spaces are treated as a single delimiter while i < cursor_pos and ...
def find(elemento, lista): """Devuelve el indice donde se encuentra el @elemento en la @lista. Si no lo encuentra devuelve -1. """ index = 0 while True: try: if lista[index] == elemento: return index except IndexError: return -1 index ...
def is_nvme_device(dev): """check whether the device path belongs to an NVMe drive. """ return "/dev/nvme" in dev
def similar_values_iter(v1, v2, e=1e-6): """Return True if iterables v1 and v2 are nearly the same.""" if v1 == v2: return True for v1, v2 in zip(v1, v2): if (v1 != v2) and ((abs(v1 - v2) / max(abs(v1), abs(v2))) > e): return False return True
def is_true(str_value: str) -> bool: """Returns True if string represents True value else return False. :param str_value: String to evaluate. """ return str_value.lower() in ("true", "yes", "1", "::ixnet::ok")
def sample_frames_uniform( frame_rate, total_frame_count=None, support=None, fps=None, max_fps=None, always_sample_last=False, ): """Returns a list of frame numbers sampled uniformly according to the provided parameters. Args: frame_rate: the video frame rate total_f...
def html_escape(text: str) -> str: """Escape < and >.""" return text.replace("<", "&lt;").replace(">", "&gt;")
def rescan(context, uri=None): """ *musicpd.org, music database section:* ``rescan [URI]`` Same as ``update``, but also rescans unmodified files. """ return {"updating_db": 0}
def rgb_to_ansi256(r, g, b): """ Convert RGB to ANSI 256 color """ if r == g and g == b: if r < 8: return 16 if r > 248: return 231 return round(((r - 8) / 247.0) * 24) + 232 ansi_r = 36 * round(r / 255.0 * 5.0) ansi_g = 6 * round(g / 255.0 * 5.0...
def B1_rel_diff(v0w, b0w, b1w, v0f, b0f, b1f, prefact, weight_b0, weight_b1): """ Returns the reletive difference in the derivative of the bulk modulus. THE SIGNATURE OF THIS FUNCTION HAS BEEN CHOSEN TO MATCH THE ONE OF ALL THE OTHER FUNCTIONS RETURNING A QUANTITY THAT IS USEFUL FOR COMPARISON, THIS SIM...
def _get_pre(level): """Get prefix indicating a header GO or a user GO.""" if level == 0: return ">" if level == 1: return "-" return ""
def sorted_maybe_numeric(x): """ Sorts x with numeric semantics if all keys are nonnegative integers. Otherwise uses standard string sorting. """ all_numeric = all(map(str.isdigit, x)) if all_numeric: return sorted(x, key=int) else: return sorted(x)
def calculate_total_number_of_travel_requests_in_timetables(timetables): """ Calculate the total number of travel_requests in timetables. :param timetables: [timetable_document] :return: total_number_of_travel_requests: int """ total_number_of_travel_requests = 0 for timetable in timetable...
def __set_aperture(ap_in): """ Make sure that aperture dictionary has correct format. Parameters ---------- ap_in: dict Aperture as defined by user. Returns ------- ap_out: dict Correctly formated and complete aperture dictionary """ sides = ['top', 'right', '...
def _from_hex(value): """INTERNAL. Gets a bytearray from hex data.""" return bytearray.fromhex(value)
def walk(node, key_match): """recursive node walk, returns None if nothing found, returns the value if a key matches key_match""" if isinstance(node, dict): for key, item in node.items(): # print('searching {} for {}'.format(key, key_match)) if str(key) == str(key_match): ...
def get_key(j, key): """ Get the key value from the dictionary object @param j: The dictionary object @param key: The key value (or empty string) """ return j[key] if key in j else '';
def unique_list(list_redundant): """Select only unique elements in a list """ list_unique_elements = [] for element in list_redundant: if element in list_unique_elements: continue else: list_unique_elements.append(element) return list_unique_elements
def crossproduct(vector1, vector2): """Returns the crossproduct of two vectors""" if not len(vector1) == len(vector2): print("Error in MDP.crossproduct(v1, v2)... vectors are not of equal length.") return None else: total = 0 for i in range(len(vector1)): total ...
def _normalize(file): """Convenience function to support path objects.""" if 'Path' in type(file).__name__: return str(file) else: return file
def record(episode, episode_reward, worker_idx, global_ep_reward, total_loss, num_steps, log_print): """Helper function to store score and print statistics. Arguments: episode: Current episode episode_reward: Reward accumulated over the current episode worker_idx: Which thread (worker) ...
def unique(value): """Check that there is only one value in the list, and return it. >>> kb = KB({'John':{'eye_color': ['blue']}}) >>> unique(kb.get_attribute('John', 'eye_color')) 'blue' This is handy in the context of KB, where everything's a list but it's common to expect that there's only one value. ...
def _process_string(value): """Strip a few non-ascii characters from string""" return value.strip('\x00\x16')