content
stringlengths
42
6.51k
def rotcon2pmi(rotational_constant): """ Convert rotational constants in units of MHz to Inertia, in units of amu A^2. The conversion factor is adapted from: Oka & Morino, JMS (1962) 8, 9-21 This factor comprises h / pi^2 c. :param rotational_constant: rotational constant i...
def subtract_year(any_date): """Subtracts one year from any date and returns the result""" date = any_date.split("-") date = str(int(date[0])-1) + "-" + date[1] + "-" + date[2] return date
def KK_RC24(w, Rs, R_values, t_values): """ Kramers-Kronig Function: -RC- Kristian B. Knudsen (kknu@berkeley.edu / kristianbknudsen@gmail.com) """ return ( Rs + (R_values[0] / (1 + w * 1j * t_values[0])) + (R_values[1] / (1 + w * 1j * t_values[1])) + (R_values[2] / (...
def _double_quotes(unquoted): """ Display String like redis-cli. escape inner double quotes. add outter double quotes. :param unquoted: list, or str """ if isinstance(unquoted, str): # escape double quote escaped = unquoted.replace('"', '\\"') return f'"{escaped}"' ...
def parse_as_unsigned_int(value, size_in_bits): """This is necessary because some fields in spans are decribed as a 64 bits unsigned integers, but java, and other languages only supports signed integer. As such, they might send trace ids as negative number if >2**63 -1. The agent parses it signed and interp...
def get_span_labels(sentence_tags, inv_label_mapping=None): """Go from token-level labels to list of entities (start, end, class).""" if inv_label_mapping: sentence_tags = [inv_label_mapping[i] for i in sentence_tags] span_labels = [] last = 'O' start = -1 for i, tag in enumerate(sentence_tags): po...
def mogrify(cursor, query, queryArgs = None): """ Logs the query statement and execute it""" query = query.upper() if queryArgs == None: return query else: cursor.prepare(query) bindnames = cursor.bindnames() if len(queryArgs) != len(bindnames): raise Exceptio...
def correct_names_ERA5(x,y, options): """ """ z = x if x in ['tp', 'sd', 'e']: y = 'mm' z = options[x] elif x in ['t2m']: y = 'C' z = options[x] elif x in ['u10', 'v10']: y = 'm/s' z = options[x] return z, y
def _create_folds_list(data, count): """ Creates folds from the given data. :param data: the data to fold :param count: the number of folds to create :return: a list of folds """ fold_count = len(data) / count folds = list() for fold_index in range(count): low = int(fold_...
def read_file(path): """ Read a file and return the contents as string :param f: (str) The file to read :return: (str) The file contents """ with open(path, 'r') as file: return file.read()
def no_trailing_comma(l): """ By-lines wikidata dumps have trailing commas (on all but the last line). Remove them. """ if l[-1] == ',': return l[:-1] else: return l
def bisect(a, x, lo=0, hi=None): """Find the index where to insert item x in list a, assuming a is sorted.""" if hi is None: hi = len(a) while lo < hi: mid = (lo+hi)/2 if x < a[mid]: hi = mid else: lo = mid+1 return lo
def _set_bit(current, epaddr, v): """ >>> bin(_set_bit(0, 0, 1)) '0b1' >>> bin(_set_bit(0, 2, 1)) '0b100' >>> bin(_set_bit(0b1000, 2, 1)) '0b1100' >>> bin(_set_bit(0b1100, 2, 0)) '0b1000' >>> bin(_set_bit(0b1101, 2, 0)) '0b1001' """ if v: return current | 1 <<...
def d2h(d): """Convert degrees into hours.""" return d * (24.0 / 360.0)
def approximately_equal(x, y, tol=0.00000000000001): """ Determines if floats x and y are equal within a degree of uncertainty Inputs: x --- a float y --- a float tol --- an error tolerance """ return abs(x - y) <= tol
def merge(line): """ Merge Function for the 2048 Game """ new_line = [0]*len(line) ind = 0 for ele in line: if ele == 0: continue elif new_line[ind] == 0: new_line[ind] = ele elif new_line[ind] == ele: new_line[ind] += ele ...
def is_grpc_service_dir(files): """Returns true iff the directory hosts a gRPC service.""" return ".grpc_service" in files
def fizz_buzz(num: int) -> str: """This is my great and neat function to solve the famous Fizz Buzz problem. :param num: That's the number which we want the answer for :return: fizz, buzz, fizzbuzz or the number itself """ if num % 15 == 0: return "fizzbuzz" if num % 5 == 0: ...
def match_name(s, l): """ Return if s matches l, where s can include wildcards '*'.""" assert(isinstance(s,str)) assert(isinstance(l,str)) spl = s.split('*') if not l.find(spl[0])==0: return False start = len(spl[0]) for si in spl[1:]: idx = l.find(si,start) if idx<0: return False else: start...
def _exclude(term: str) -> str: """ Returns a query term excluding messages that match the given query term. Args: term: The query term to be excluded. Returns: The query string. """ return f'-{term}'
def IRAF_image_type(image_type): """ Convert MaximDL default image type names to IRAF Parameters ---------- image_type : str Value of the FITS header keyword IMAGETYP; acceptable values are below in Notes. Returns ------- str IRAF image type (one of 'BIAS', 'DAR...
def choices_on_ballots(L, printing_wanted=False): """ Return a dict of the choices shown on ballot list L, with counts. Args: L (list): list of ballots Returns: C (dict): dict of distinct strings appearing in ballots in L, each with count of number of occurren...
def clip(number,start,end): """Returns `number`, but makes sure it's in the range of [start..end]""" return max(start, min(number, end))
def _PathFromRoot(module_tree, module): """Computes path from root to a module. Parameters: module_tree: Dictionary mapping each module to its parent. module: Module to which to compute the path. Returns: Path from root the the module. """ path = [module] while module_tree.get(module): mod...
def format_error(error_code, message): """ Converts an error_code and message into a response body """ return {"errors": [{"code": error_code, "message": message}]}
def to_list(val): """ Do whatever it takes to coerce val into a list, usually for blind concatenation """ if isinstance(val, list): return val if not val: return [] return [val]
def Summation(xs, mu, cache={}): """Computes the sum of (x-mu)**2 for x in t. Caches previous results. xs: tuple of values mu: hypothetical mean cache: cache of previous results """ try: return cache[xs, mu] except KeyError: ds = [(x-mu)**2 for x in xs] total = ...
def do_datetime(dt, format=None): """Jinja template filter to format a datetime object with date & time.""" if dt is None: # By default, render an empty string. return '' if format is None: # No format is given in the template call. Use a default format. # # Format ti...
def get_mode(input_list: list): """ Get's the mode of a certain list. If there are few modes, the function returns False. This is a very slow way to accomplish this, but it gets a mode, which can only be 4 things, so it should be OK """ if len(input_list) == 0: return False distinguish...
def quick_sort(items): """ the quick sort algorithm takes in an unsorted list of numbers. returns a list in ascending order. Parameters ---------- items : list list of unordered numbers Returns ------- list list of elements in items in ascending order Exam...
def letter_tuple_to_string(letter_tuple): """ Ronseal. """ string = "" for letter in letter_tuple: string = string+letter return string
def check_certificate_data(certificates): """ Checks the correctness of the certificates provided by the CS. :param certificates: the provided certificates. :type certificates: DER str list :return: True if the certificates are correct, False otherwise. :rtype: bool """ # ToDo: Decide wi...
def remove_duplicates_and_nones(items): """Removes all duplicates and None values from a list.""" new_list = [item for item in items if item is not None] return list(set(new_list))
def sanitize_host(host): """Return the hostname or ip address out of a URL""" for prefix in ['https://', 'http://']: host = host.replace(prefix, '') host = host.split('/')[0] host = host.split(':')[0] return host
def read_metadatablockpicture( data ): """Extract picture from a METADATA_BLOCK_PICTURE""" off = 8 + int.from_bytes( data[4:8], 'big' ) off += 4 + int.from_bytes( data[off:off+4], 'big' ) + 16 size = int.from_bytes( data[off:off+4], 'big' ) return data[4+off:4+off+size]
def bytes_to_str(bytes_arr): """ This function print all bytes in the same way as C/C++. When we have 2 in python we get 10, but I want to see it as like 00000010 """ res_str = "" for byte in bytes_arr: byte_str = "{0:b}".format(byte) res_str += "0" * (8 - len(byt...
def get_trained_policies_name(policies, num_trained_agent): """ Get index of the max reward of the trained policies in most recent episode. """ train_policies_name = [] i = 0 for k,v in policies.items(): if i < num_trained_agent: train_policies_name.append(k) i = i +...
def nodetype(anode): """return the type of node""" try: return anode[1] except IndexError as e: return None
def make_subsets(data, size: int) -> list: """ Creates subsets out of ``data``, each subset having ``size`` elements. Used in ``graphs/multiple_results.html`` and ``graphs/single_result.html``. """ subset_list = list() if type(data) is list: subset = list() while True: ...
def read_cube_name_from_mdx(mdx): """ Read the cubename from a valid MDX Query :param mdx: The MDX Query as String :return: String, name of a cube """ mdx_trimed = ''.join(mdx.split()).upper() post_start = mdx_trimed.rfind("FROM[") + len("FROM[") pos_end = mdx_trimed.find("]WHERE", post_st...
def fizz_buzz(num): """ return 'Fizz', 'Buzz', 'FizzBuzz', or the argument it receives, all depending on the argument of the function, a number that is divisible by, 3, 5, or both 3 and 5, respectively. """ if not isinstance(num, int): raise TypeError("Expected integer as...
def parser_add_help_from_doc(doc): """Find the conventional H/ Help Option and return True, else False or None""" if doc is None: return None lines = doc.splitlines() for (index, line) in enumerate(lines): next_line = lines[index + 1] if lines[(index + 1) :] else "" stripped ...
def create_metadata(metadata, data, **kwargs): """Function: create_metadata2 Description: Merge a list of data sets into an existing dictionary based on the keys in the dictionary or create new keys in the dictionary based on the data set in the list. Arguments: (input) metadata...
def atoi(s : str): """ Converts integer jobId as string to integer Args: s (string): Microsoft jobId Returns: integer form """ if not s: print("Cannot convert empty string to integer") n = 0 for i in s: n = n * 10 + o...
def partition_around_index(list_to_partition, index): """ Partitions a list around the given index, returning 2 lists. The first contains elements before the index, and the second contains elements after the index (the given index is excluded). Examples: partition_around_index([1,2,3,4,5], 2) =...
def contiguous_seq_eff2(A, maxx=0, max_seq=set()): """ No need for any recursion and only one for loop """ # Stop if if len(A) < 1: return False sum_ = 0 seq = set() for n in A: sum_ += n seq.add(n) if sum_ > maxx: maxx = sum_ max...
def _to_gj_point(obj): """ Dump a Esri JSON Point to GeoJSON Point. :param dict obj: A EsriJSON-like `dict` representing a Point. :returns: GeoJSON representation of the Esri JSON Point """ if obj.get("x", None) is None or \ obj.get("y", None) is None: retu...
def SizeToReadableString(filesize): """Turn a filesize int into a human readable filesize. From http://stackoverflow.com/questions/1094841/ Args: filesize: int Returns: string: human readable size representation. """ for x in ["bytes", "KiB", "MiB", "GiB", "TiB"]: if filesize < 1000.0: r...
def _range_is_valid (list, range): """checks if each element of the range is a valid element of the list and returns True if this is the case.""" return (0 <= min(range) and max(range) < len(list))
def is_sibling_of(page1, page2): """ Determines whether a given page is a sibling of another page {% if page|is_sibling_of:feincms_page %} ... {% endif %} """ if page1 is None or page2 is None: return False return (page1.parent_id == page2.parent_id)
def _find_prime_factors(n): """ Find all the prime factors of `n`, sorted from largest to smallest Parameters ---------- n : int Number to factorize Returns ------- factors : list[int] Notes ----- From http://stackoverflow.com/questions/15347174/python-finding-prim...
def suba(a, b, c, d=0, e=0): """Subtract numbers b and c from number a. Optionally also subtract either or both of numbers d and e from the result. """ print(f"Function `suba` called with arguments a={a} b={b} c={c}", end="") if d: print(f" d={d}", end="") if e: print(f" e={e}", end="") pri...
def bayes_factor(model_1, model_2): """ Use the `Bayes factor`_ to compare two models. Using Table from `Kass and Raftery`_ to compare. Args: model_1 (:py:class:`uncertainties.core.Variable` or :py:attr:`float`): ln evidence for model 1. model_2 (:py:class:`uncertainties.core.Variable` or :...
def format_markdown(content, params): """Format content with config parameters. Arguments: content {str} -- Unformatted content Returns: {str} -- Formatted content """ try: fmt = content.format(**params) except KeyError: fmt = content return fmt
def mandel_numba(x, y, max_iters): """ Given the real and imaginary parts of a complex number, determine if it is a candidate for membership in the Mandelbrot set given a fixed number of iterations. """ i = 0 c = complex(x, y) z = 0.0j for i in range(max_iters): z = z * z + c...
def max_no_repeat(s): """ Returns the first longest substring of s containing no repeated characters. """ max_start = -1 max_end = -1 max_len = -1 char_set = set() # {} initializes an empty dict instead of an empty set. curr_start = 0 for curr_end in range(len(s)): char = s[...
def nocomment(st,com): """ just like the comment in python. removes any text after the phrase 'com' """ ls=st.splitlines() for i in range(len(ls)): el=ls[i] pt=el.find(com) if pt!=-1: ls[i]=el[:pt] return '\n'.join(ls)
def griddef(gridname): """ Returns a tuple of grid parameters for an EASE grid gridname - standard name of grid """ gdef = { 'Nh': {'c': 12.5, 'nx': 1441, 'ny': 1441, 'r0': 720, 's0': 720} } try: result = gdef[gridname] return result except: ...
def round_coordinates(coord_x, coord_y): """ Round coordinates to 1 decimal """ x = round(coord_x, 1) y = round(coord_y, 1) return x, y
def cast_int(value): """ Cast value to 32bit integer Usage: cast_int(1 << 31) == -1 (where as: 1 << 31 == 2147483648) """ value = value & 0xFFFFFFFF if value & 0x80000000: value = ~value + 1 & 0xFFFFFFFF return -value else: return value
def convert_ddmmss_to_float(astring): """Convert sexigesimal to decimal degrees Parameters ---------- astring: str The sexigesimal coordinate. Returns ------- hour_or_deg : float The converted coordinate. """ aline = astring.split(':') d = float(al...
def _parse_tshape(tshape): """Parse tshape in string.""" return [int(x.strip()) for x in tshape.strip('()').split(',')]
def is_float(string): """Checks if the string is a float Args: string (str): The string to check Returns: Boolean: Whether the string could be converted to a float or not """ try: float(string) return True except ValueError: return False
def conf_full(): """complete config used for tests. """ return { "jwt_secret": "SECRET", "user_claim": "jid", "jwt_secret_old": "OLDSECRET", "jwt_algorithm": "HS256", "issuer": "https://www.myapplication.com", "audience": "https://www.myapplication.com", ...
def average_nonmissing(row, cols, missing=-999, adjustfactor=1, countmissings=False): """Average the non-missing columns in cols, adjusting denominator""" nonmissingcols = [row[col] for col in cols if row[col] != missing] return missing if len(nonmissingcols) == 0 \ else sum(nonmissingcols)/((len(co...
def is_supported_english_translation(translation): """ A helper function to determine if the provided string is a supported English translation. :param translation: Translation code :type translation: str :return: True = the translation is not supported, False = the translation is supported :rt...
def compute_sv_offset(frequency, pulse_length): """ A correction must be made to compensate for the effects of the finite response times of both the receiving and transmitting parts of the instrument. The magnitude of the correction will depend on the length of the transmitted pulse, and the respons...
def unzip_pairs(tups): """ turn a list of pairs into a pair of lists """ return zip(*tups) if tups else ([],[])
def reversebits6(max_bits, num): """ Like reversebits5, plus avoidance of an unnecessary shift. """ rev_num = 0 rev_left_shifts_to_do = max_bits - 1 while True: rev_num |= num & 1 num >>= 1 if num == 0 or rev_left_shifts_to_do == 0: break rev_num <<= 1 ...
def comparing_tuple(A,B, tol=0.01): """ comparing two same sized tuple """ assert len(A) == len(B) for i in range(0,len(A)): if abs(A[i] - B[i]) <= tol: continue else: return False return True
def encode(text: str) -> str: """ Reverse order of given text characters. :param text: Text to reverse. :return: Reversed text. """ reversed_text = "".join(char for char in text[-1::-1]) return reversed_text
def flaghandler_note(mastodon, rest): """Parse input for flagsr. """ # initialize kwargs to default values kwargs = {'mention': True, 'favourite': True, 'reblog': True, 'follow': True} flags = {'m': False, 'f': False, 'b': False, ...
def strings_match_at_indices(string_a, index_a, string_b, index_b): """Check if both strings match at given indices and indices aren't 0. Args: string_a (str): First string. index_a (int): Index of character in first string. string_b (str): Second string. index_b (int): Index of...
def wrap_html_source(text): """ wrap the text with html tags to force the browser show the code as was created without corrupting it """ if text is None: text = "ERROR: got None value!" return "<html><pre><code> " + text + "</code></pre></html>"
def pawssible_patches(start, goal, limit): """A diff function that computes the edit distance from START to GOAL. >>> pawssible_patches('place', 'wreat', 100) 5 """ # assert False, 'Remove this line' # print(start, goal, limit) if start == goal: return 0 elif limit == 0: ...
def get_meta_name_and_modifiers(name): """ Strips a meta name from any leading modifiers like `__` or `+` and returns both as a tuple. If no modifier was found, the second tuple value is `None`. """ clean_name = name modifiers = None if name[:2] == '__': modifiers = '__' ...
def tag_seq(words, seq, tag): """Sub in a tag for a subsequence of a list""" words_out = words[:seq[0]] + ['{{%s}}' % tag] words_out += words[seq[-1] + 1:] if seq[-1] < len(words) - 1 else [] return words_out
def clean_regex(regex): """ Escape any regex special characters other than alternation. :param regex: regex from datatables interface :type regex: str :rtype: str with regex to use with database """ # copy for return ret_regex = regex # these characters are escaped (all except alte...
def get_step_limit(lines): """Computes the maximum number of IPA-GNN steps allowed for a program.""" step_limit = 1 # Start with one step for reaching exit. indents = [] for line in lines: indent = len(line) - len(line.lstrip()) while indents and indent <= indents[-1]: indents.pop() step_limi...
def sequence_delta(previous_sequence, next_sequence): """ Check the number of items between two sequence numbers. """ if previous_sequence is None: return 0 delta = next_sequence - (previous_sequence + 1) return delta & 0xFFFFFFFF
def _count_set_bits(i): """ Counts the number of set bits in a uint (or a numpy array of uints). """ i = i - ((i >> 1) & 0x55555555) i = (i & 0x33333333) + ((i >> 2) & 0x33333333) return (((i + (i >> 4) & 0xF0F0F0F) * 0x1010101) & 0xffffffff) >> 24
def get_group_key(group_name): """Build group key""" return 'cephx.groups.{}'.format(group_name)
def flatten_doc(doc, return_fields, exceptions=None): """ Parameters ---------- doc : dict The document in the Solr response. return_fields : string A string of comma-separated field names. exceptions : list, optional A list of names of fields that should not be flattened...
def sorted_with_prefix(prefix, it, drop_exact=True, drop_special=True): """ >>> sorted_with_prefix("foo", ["fooZ", "fooAA", "fox"]) ['fooAA', 'fooZ'] >>> sorted_with_prefix("", ["fooZ", "fooAA", "_f", "__f", "fox"]) ['fooAA', 'fooZ', 'fox', '_f'] >>> sorted_with_prefix("", ["fooZ", "fooAA", "_f"...
def compute_in_degrees(digraph): """ dict -> dict Takes a digraph represented as a dictionary, and returns a dictionary in which the keys are the nodes and the values is the node's indegree value. """ indegrees = {} for node in digraph: indegrees[node] = 0 for node in digraph: ...
def nset(dic, keys, val): """ Set a nested key-value pair - in-place. No-op when a value already exists. Example: x = {} nset(x, ['a', 'b', 'c'], 0) print(x) > {'a': {'b': {'c': 0}}} """ for key in keys[:-1]: dic = dic.setdefault(key, {}) dic[keys[-1]] = ...
def loadConfigFromValuesNoCase(conf, key, values): """NOTE: The values must all be lowercase (e.x. \"highest\")""" value = conf.get('all', key).lower() if value in values: return value else: raise Exception("ERROR: Configuration \'" + key + "\' was an invalid value, unable to run!")
def check_if_present(a,b): """ to check if b contains only letters from a, only once a='abcdei' b='is' """ _len=0 for i in a: if b.count(i) > a.count(i): return -1 if b.count(i)== a.count(i): _len+=1 #print i,b.count(i) if _len == len(b): return 1 else: return 0
def interleave_lists(*args): """Interleaves N lists of equal length.""" for l in args: assert len(l) == len(args[0]) # all lists need to have equal length return [val for tup in zip(*args) for val in tup]
def sort_module(module_reqs): """Sort modules based on dependency relations. """ module_sorted = [] module_depth = {} def dfs(module_name): max_depth = 0 if module_name in module_reqs.keys(): for req in module_reqs[module_name]: max_depth = max(max_depth, ...
def munge_level(lvl): """ Turn obnoxious data like 'level': 'wizard/sorceror 2, bard 3' into 'level': {'wizard': 2, 'sorceror': 2, 'bard': 3} """ lvls = {} for spec in lvl.split(','): if len(spec) < 0: continue cls, lvl = spec.split() if '/' in cls: cls = cls.split('/') else: ...
def update_hand(hand, word): """ Does NOT assume that hand contains every letter in word at least as many times as the letter appears in word. Letters in word that don't appear in hand should be ignored. Letters that appear in word more times than in hand should never result in a negative count...
def schedule(epoch, lr): """ The learning rate schedule Parameters: epoch and current learning rate Returns: lr: updated learning rate """ if epoch==15: lr=lr/4 return lr
def _is_currency(shape): """ Check if this shape represents a Currency question; a 'ROUND_RECTANGLE' """ return shape.get('shapeType') == 'ROUND_RECTANGLE'
def s3_str(s, encoding="utf-8"): """ Convert an object into a str Args: s: the object encoding: the character encoding """ if type(s) is str: return s elif type(s) is bytes: return s.decode(encoding, "strict") else: return str(s)
def list_minus(l, minus): """Returns l without what is in minus >>> list_minus([1, 2, 3], [2]) [1, 3] """ return [o for o in l if o not in minus]
def _get_node_url(node_type: str, node_name: str) -> str: """Constructs the URL to documentation of the specified node. Args: node_type (str): One of input, model, dabble, draw or output. node_name (str): Name of the node. Returns: (str): Full URL to the documentation of the specif...
def layer_is_in_mark(layer, mark): """ Whether the given layer is in the given mark. """ return layer["mark"] == mark or ("type" in layer["mark"] and layer["mark"]["type"] == mark)
def join(*args): """Concatenation of paths. Just for compatibility with normal python3.""" return "/".join(args)
def hexstr_to_dbytes(h,swap=True): """ converts and swaps hex string represenation of hash to bytes for generating digest """ if h[:2] == "0x": h = h[2:] if len(h)%2 != 0: h = h.zfill(len(h)+1) num_bytes = len(h)//2 if swap: return int(h,16).to_bytes(num_bytes,"little") e...