content
stringlengths
42
6.51k
def date_str_to_azure_format(date_str): """ Given a string representing a date in some general format, modifies the date to Azure format. That means removing the Z at the end and adding nanoseconds if they don't exist. Moreover, sometimes the date has too many digits for """ date_str = date_str[...
def _get_prefixes_for_action(action): """ :param action: iam:cat :return: [ "iam:", "iam:c", "iam:ca", "iam:cat" ] """ (technology, permission) = action.split(":") retval = ["{}:".format(technology)] phrase = "" for char in permission: newphrase = "{}{}".format(phrase, char) ...
def rivers_with_station(stations): """Creates a list of rivers with at least 1 station""" rivers = [] for i in stations: if i.name != None: if i.river not in rivers: rivers.append(i.river) return rivers
def _all_feature_names(name): """ All feature names for a feature: usually just the feature itself, but can be several features for unhashed features with collisions. """ if isinstance(name, bytes): return [name.decode('utf8')] elif isinstance(name, list): return [x['name'] for x in ...
def compatible_const(const): """See whether we can blobify the constant""" if isinstance(const, tuple): return all(map(compatible_const, const)) return isinstance(const, (type(None), bool, int, float, str, complex))
def _is_namespace_param(namespace: str) -> bool: """Returns whether a dataset namespace is a parameter""" return namespace.lower().startswith("param")
def to_hash(string): """converts strings to hash t_size = size of hash table default is set to 25""" xor = 0 # convert letters to ordinal values # then hash by taking modulo for ind in range(len(string)): xor ^= int(ord(string[ind])) return xor
def verify_board_size(board): """Verify whether the given board size is correct, both column and row should be equal""" row_max_size = len(board) if row_max_size <= 0: return (0, 0) col_max_size = len(board[0]) if col_max_size <= 0: return (0, 0) if row_max_size != col_max_size: ...
def red(string): """ Convert a string to red text :string: the string to convert to red text """ return f'\033[91m{string}\033[0m'
def format_dj(dj): """Format the DJ's name for a playlist description.""" return '' if not dj else f'with {dj}'
def get_labs(kv, key): """ We need this filter because lab values have semicolons in them. """ return int(kv.get("labs:"+str(key), 0))
def sieve_of_eratosthenes(n): """ Search and return the primes lower or equals to 'n' Args: n -- int return list of primes """ primes = [] numbers = range(2, n+1) # continu while there are numbers while len(numbers): # the first is a prime primes.append(numbers...
def get_id_from_name(name): """ Retreives an id from an airlab name :param name: :return: """ newname = name.split('_')[-1] newname = newname.split('(')[0] if newname == '': newname = name return newname
def preprocessed_test_metrics(expected_metrics): """function that creates a single file with metrics that need to be tested in different files In: expected_metrics: List[ Tuple[FileName, Dict[Metric1: Value1, Metric2: Value2, ...], ...] ] Out: res: List[ Tuple[FileName, Metric1...
def to_listlist(list_dict): """Converts a list-of-dicts to a list-of-lists. Ex: [{'a': 1, 'b': 2}, {'a': 3, 'b': 4}] ---> [["a","b"],[1, 2],[3, 4]] Args: list_dict (<list<dict>>): A list of dictionaries. Ex: [{'a': 1, 'b': 2}, {'a': 3, 'b': 4}] Returns: <list<list>>: list-of-lists. Ex...
def add_lead_zero(hour): """ For representing hour as a string, hour must be in the form of two digits. Which means that in the range 0-9, there needs to be a leading zero. This function takes in an integer represting an hour, and adds a leading zero if necessary Parameters ---------- ...
def _hex_to_rgb(color): """ >>> _hex_to_rgb('#dead13') (222, 173, 19) """ return tuple(int(color.lstrip('#')[i:i + 2], 16) for i in (0, 2, 4))
def int2bit(x, w=20): """ Generates a binary representation of an integer number (as a tuple) >>> bits = int2bit(10, w=4) >>> bits (1, 0, 1, 0) >>> bit2int( bits ) 10 """ bits = [ ] while x: bits.append(x%2) x /= 2 # a bit of padding bits = bits ...
def pop(array, index=-1): """Remove element of array at `index` and return element. Args: array (list): List to pop from. index (int, optional): Index to remove element from. Defaults to ``-1``. Returns: mixed: Value at `index`. Warning: `array` is modified...
def clean_empty_keyvalues_from_dict(d): """Clean all key value pairs from the object that have empty values, like [], {} and ''. Arguments: d (dict): The object to be sent to metax. (might have empty values) Returns: dict: Object without the empty values. """ if not isinstance(d, ...
def format_link(stream): """ Convert the JSON structure to a url. Currently supported: - twitch """ if stream["type"] == "twitch": return "https://twitch.tv/{}".format(stream["channel"]) return "https://{}.com/{}".format(stream["type"], stream["channel"])
def get_attribute(event, attr, default_val={}): """ Retrieve attribute from request. if it's null or doesn't exist, return default value. """ return default_val if attr not in event or event[attr] is None else event[attr]
def gray_to_int(s: str) -> int: """Given a zero left-padded gray code representation of an int, return int value.""" s = s.lstrip('0') n = int(s, 2) mask = n >> 1 while mask != 0: n = n ^ mask mask = mask >> 1 return n
def hex_to_rgb(hex_color): """ Helper function to convert hex strings to RGB """ hex_color = hex_color.lstrip('#') h_len = len(hex_color) return tuple(int(hex_color[i:i + h_len // 3], 16) for i in range(0, h_len, h_len // 3))
def normalize_phone_number(number, country_code): """Normalize a phone number to E.123 notation (but without spaces). See: http://de.wikipedia.org/wiki/E.123 """ digits = ''.join(x for x in number if x.isdigit()) if digits.startswith('00'): # old writing of numbers abroad return di...
def get_image_identifier(valueList, year): """ Use the location values and the year to build a string identifier for an image: Shore1;Reef5;...;2008 """ return ';'.join(valueList + [year])
def websub(text, websubtable): """:websub: Any text. Only applies to hgweb. Applies the regular expression replacements defined in the websub section. """ if websubtable: for regexp, format in websubtable: text = regexp.sub(format, text) return text
def find_paths(start_val, start_sides, length, possible): """ Starting from (XX, sides) we use the possible paths to move from one to the next, without repeating E.G. if start is ('95', 7) then we look in possible['95'] and find [('91', 3), ('60', 5), ('17', 7)] so we will extend at that step t...
def rank2int(rank): """Convert a rank/placing string into an integer.""" ret = None try: ret = int(rank.replace(u'.',u'')) except Exception: pass return ret
def is_a_invalid_id(feature_id): """ Check if the id of some feature is valid or not. For a id to be valid, it needs to be: (1) not None; (2) a integer (a digit); (3) if is a integer, so different of 0. IDs are integer numbers greater than zero. :param feature_id: id of a feature in string f...
def quick_sort(sequence): """ 1. Check the length of sequence 2. if length > 1, pop last element from sequence and use that element as pivot. 3. finally concatinate the output eg. lower_sequence + pivot + higher squence """ length = len(sequence) if(length <= 1): ...
def days_in_minutes(days): """ Returns int minutes for float DAYS. """ return days * 60 * 24
def sqrt(x): """ calculate the sqare root of a number x """ # check that x is positive if x < 0: print("error:negative number value was supplied") return -1 else: print("here we go..") # z is an initial guess for the root. z = x / 2.0 # continuously improve the guess . while abs(x - (...
def _fix_floating_point(a): """Iterate through an array of dicts, checking for floats and rounding them.""" def get_type(thing): try: return thing['type'] except KeyError: return 'message' for thing in a: if get_type(thing) not in ['cbg', 'smbg']: ...
def euclidean_gcd(a: int, b: int): """ compute the greatest common divisor of two positive integers, a and b, using the Euclidean algorithm """ while b > 0: a, b = b, a % b return a
def curve_to_string(q,t,k,r,D): """ Description: Returns a string representation of the curve (q,t,r,k,D) Input: q - size of prime field t - trace of Frobenius r - size of prime order subgroup k - embedding degree D - (negative) fundamental disc...
def clamp(minimum, n, maximum): """Return the nearest value to n, that's within minimum to maximum (incl) """ return max(minimum, min(n, maximum))
def convert_color(s): """ Convert a string hexadecimal representation of a color into a tuple RBG where each element of the tuple is between 0.0 to 1.0 :param s: (str) :return: (tuple) With 3 floats representing the color in RGB :rtype : tuple Examples: >>> convert_color('FF5500') ...
def in_range(target, bounds): """ Check whether target integer x lies within the closed interval [a,b] where bounds (a,b) are given as a tuple of integers. Returns boolean value of the expression a <= x <= b """ lower, upper = bounds return lower <= target <= upper
def distance(movie1, movie2): """euclidean distance implementation""" squared_difference = 0 for i in range(len(movie1)): squared_difference += (movie1[i] - movie2[i]) ** 2 final_distance = squared_difference ** 0.5 return final_distance
def num2ip(num): """ num(16670061) to IP(10.0.0.1) """ num_x = "{0:08x}".format(num) num_str = str(num_x) ip = "" for i in [0,2,4,6]: a = int(num_str[i:i+2],16) ip += str(a) if i != 6: ip += '.' return ip
def dbdisconnect(connection) -> bool: """Close connection to SQLite-Database :param connection: :return: Result of success (true/false) """ if connection: connection.close() return True return False
def get_factors(n): """return all the factors of n""" factors = set() for i in range(1, int(n**(0.5)) + 1): if not n % i: factors.update((i, n // i)) return factors
def fun(ham: str, eggs: str = 'eggs') -> str: # -> None for void return """Annotation and types of function""" print("Annotations:", fun.__annotations__) print("Arguments:", ham, eggs) return ham + ' and ' + eggs
def msfpattern(n): """msfpattern-like patterns""" def inc(alphas, indexes, i): indexes[i % 3] += 1 if indexes[i % 3] >= len(alphas[i % 3]): indexes[i % 3] = 0 inc(alphas, indexes, i-1) return alphas = ["ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz...
def get_region(z): """Assign numbers for regions where hyp2f1 must be handled differently.""" if abs(z) < 0.9 and z.real >= 0: return 1 elif abs(z) <= 1 and z.real < 0: return 2 elif 0.9 <= abs(z) <= 1 and abs(1 - z) < 0.9: return 3 elif 0.9 <= abs(z) <= 1 and abs(1 - z) >= 0...
def has_remediation(rid, penalty): """ Test if a penalty contains a remediation with the given remediation ID""" remediations = penalty['remediation'] if isinstance(remediations, list): for rem in remediations: if rem['id'] == rid: return True else: ...
def add_prefix_un(word): """ :param word: str of a root word :return: str of root word with un prefix This function takes `word` as a parameter and returns a new word with an 'un' prefix. """ prefix = 'un' return prefix+word
def _byte_pad(data, bound=4): """ GLTF wants chunks aligned with 4 byte boundaries. This function will add padding to the end of a chunk of bytes so that it aligns with the passed boundary size. Parameters -------------- data : bytes Data to be padded bound : int Length ...
def create_logdir(dataset, weight, label, rd): """ Directory to save training logs, weights, biases, etc.""" return "train_logs/{}/anogan/label{}/weight{}/rd{}".format( dataset, label, weight, rd)
def insert_nested_value(dictionary, path, value): """ Given a `dictionary`, walks the `path` (creating sub-dicts as needed) and inserts the `value` at the bottom. Modifies `dictionary`, and also returns `dictionary` as a convenience. For example: >>> insert_nested_value({}...
def cross_product(matrix_a, matrix_b): """ returns the cross product of matrix_a and matrix_b""" dimension = len(matrix_a) matrix_c = [] for i in range(dimension): matrix_c.append(0) for j in range(dimension): if j != i: for k in range(dimension): ...
def linear_gradient(x, y): """A horizontal linear gradient from 0.0 to 1.0 on the interval [-0.5, 7.5]. This has gamma correction applied. """ return ((x + 0.5) / 8.0)**2.2
def add_nav_cal_to_google_cals(service, err_msg_list): """ This function adds the 'Navigator-Consumer Appointments (DO NOT CHANGE)' calendar to the list of a given navigator's google calendars. :param service: (type: service object) Authenticated Google Calendar API service object :param err_msg_li...
def stringEscapeMD(st, minimal_escaping=False, escape_multiline=False): """ Escape any chars that might break a markdown string :type st: ``str`` :param st: The string to be modified (required) :type minimal_escaping: ``bool`` :param minimal_escaping: Whether replace all special...
def _remove_trailing_chars(text: str) -> str: """ Removes trailing characters from the beginning or end of a string. """ chars = ['.', '@', '/', '&', '-', "'"] for char in chars: text = text.strip(char) return text
def update_navigator_object(nav_obj, coll_descr, schema_descr): """Updates navigator object. Inserts new dataset, new perspective or new issue, it depends on what collections are in navigator object already. Returns dataset description that was added/updated. nav_obj -- previous navigator object ...
def to_bdc(number: int) -> bytes: """ 4 bit bcd (Binary Coded Decimal) Example: Decimal 30 would be encoded with b"\x30" or 0b0011 0000 """ chars = str(number) if (len(chars) % 2) != 0: # pad string to make it a hexadecimal one. chars = "0" + chars bcd = bytes.fromhex(str(cha...
def first(obj): """return first element from object (also consumes it if obj is an iterator)""" return next(iter(obj))
def deploy_ship(y, x, board, ship_length, orientation, ship_num): """ This is a built-in method provided by AIGaming. Deploys a ship at the given coordinate on the board. Checks as to whether it can be placed are done against the board. :param y: an integer, making up the row index. :param x: an int...
def prepare_mongo_query(query): """ Internal function to prepare the ElasticSearch search query from a given json """ archived = query.get('archived') authors = query.get('authors') tags = query.get('tags') status = query.get('status') date_from = query.get('date_from') date_to = query.g...
def wordnumber(text): """ Change number words to numbers """ if text == "four": return 4 return 0
def is_dynamic_uri(uri): """ Determine whether `uri` is a dynamic uri or not. Assumes a dynamic uri is one that ends with '}' which is a Pyramid way to define dynamic parts in uri. :param uri: URI as a string. """ return uri.strip('/').endswith('}')
def bits_to_bytearray(bits): """Convert a list of bits to a bytearray""" ints = [] for b in range(len(bits) // 8): byte = bits[b * 8:(b + 1) * 8] ints.append(int(''.join([str(bit) for bit in byte]), 2)) return bytearray(ints)
def replace_multiple(base_word: str, all_replacements: dict) -> list: """replaces characters in str:base_word with dict:all_replacements replace_multiple replaces all at once instead of one at a time i.e. password -> p@ssw0rd instead of password -> p@ssword -> p@ssw0rd :param base_word: original string...
def add_frac(Zaehler1, Nenner1, Zaehler2, Nenner2): """Diese Funktion addiert 2 Bruche""" import math Nenner_neu = int((Nenner1*Nenner2) / math.gcd(Nenner1, Nenner2)) Zaehler1 = Zaehler1 * (Nenner_neu/Nenner1) Zaehler2 = Zaehler2 * (Nenner_neu/Nenner2) Zaehle...
def print_bin_8(val): """ Print 8 bit int in binary """ return "{0:b}".format(val).zfill(8)
def basic_falling_factorial(high, low): """Returns the high! / low! """ if low == high: return 1 if high < low: return 0 i = low + 1 ans = 1 while i <= high: ans *= i i += 1 return ans
def unique_everseen(seq): """Solution found here : http://stackoverflow.com/questions/480214/how-do-you-remove-duplicates-from-a-list-in-python-whilst-preserving-order""" seen = set() seen_add = seen.add return [x for x in seq if not (x in seen or seen_add(x))]
def convert_lon(lon): """Convert a single longitude value to a floating point number. Input longitude can be string or float and in -135, 135W, 225 or 225E format. Output longitude lies in the range 0 <= lon <= 360. """ lon = str(lon) if 'W' in lon: deg_east = 360 - floa...
def get_shadow_temp(sun_theta, sun_az, temp0): """ Return temperature of shadows. Nominally 100 K less than the rad_eq surf_temp. At high solar incidence, scale shadow temperature by inc angle. Evening shadows are warmer than morning shadows. Tuned for lunar eqautor by Bandfield et al. (2015, 2018)....
def getSortKey(name, namespaces): """Returns the key the functions and structs are sorted for.""" return str(namespaces) + name
def get(obj, path, default=None): """Gets the value at path of object. If the resolved value is undefined, the default value is returned in its place. Exampele: >>> obj = { 'a': [{ 'b': { 'c': 3 } }] } >>> get(obj, 'a.0.b.c') 3 Args: obj (dict,list): The object to query. ...
def calc_check_digit(number): """Calculate the check digit. The number passed should not have the check digit included.""" check = sum((1 + i % 9) * int(n) for i, n in enumerate(number)) % 11 if check == 10: check = sum((1 + (i + 2) % 9) * int(n) for i, n in enumerate(number)) return str(che...
def match_matrix_rows(ass_mat, cons_mat): """ Reorder a second matrix based on the first row element of the 1st matrix :param ass_mat: a 2D list of scores :param cons_mat: a 2D list scores :type ass_mat: list :type cons_mat: list :rtype: 2 matricies (2D lists) """ reordered_ass, r...
def remove_indent(lines): """ Remove all indentation from the lines. """ return [line.lstrip() for line in lines]
def columns_distributed(thelist, n): """ Break a list into ``n`` columns, distributing columns as evenly as possible across the columns. For example:: >>> l = range(10) >>> columns_distributed(l, 2) [[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]] >>> columns_distributed(l, 3)...
def fis_gbellmf(x:float, a:float, b:float, c:float): """Generalized Bell Member Function""" t = (x - c) / a if (t == 0) and (b == 0): return 0.5 if (t == 0) and (b < 0): return 0 return (1.0 / (1.0 + (t ** b)))
def get_pyrex_parameters(line): """ input: GLAPI void GLAPIENTRY glTexSubImage1D (GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLenum type, const GLvoid *pixels); output: ("void", "glTexSubImage1D", ["target", "level", "xoffset", "width", "format", "type", "*pixels"]...
def is_placeholder(x): """Returns whether `x` is a placeholder. # Arguments x: A candidate placeholder. # Returns Boolean. """ return hasattr(x, '_cntk_placeholder') and x._cntk_placeholder
def evaluate(value, final, container_holder): """ Calls ``__evaluate__`` and passes on ``final`` state. """ if hasattr(value, '__evaluate__'): value = value.__evaluate__(container_holder) if not value.final: final = False return value.value, final else: r...
def adjacent_lines_indexes(indexes): """Given a sequence of vertices indexes, return the indexes to be used with GL_LINES_ADJACENCY in order to draw lines between them in a strip.\n Example: (0, 1, 2, 3) -> ( 0, 0, 1, 2, 0, 1, 2, 3, 1, 2, 3, 3 ) """ assert len(ind...
def set_plus_row(sets, row): """Update each set in list with values in row.""" for i in range(len(sets)): sets[i].add(row[i]) return sets
def max_list(arr): """ Count elements in list """ if not isinstance(arr, list): return 'Use only list with numbers for this function' if not len(arr): return None m = arr[0] for i in arr: m = i if i > m else m return m
def check_number_v2(num): """ Faster way :param num: input number integer -> check if this is perfect number :return: bool True/False if the input is perfect number of not """ if num <= 1: return False div = list(filter(lambda x: num % x == 0, range(1, int(num**0.5)+1))) ...
def _as_string(ind, vals, text, gt_ind, freq): """Represent key, val pairs as a string """ def get_status(a, b): return "C" if a in b else "W" output = [] gt_ind = set(gt_ind) if freq is None: for i, (k, v) in enumerate(zip(ind, vals)): output.append(f"{text...
def intize(num): """Round a floating point number to an integer. Parameters ---------- num : float Number to round. Returns ------- int Rounded number. See Also -------- initize_list initize_dict Notes ----- Limited by Python floating point ari...
def Adler32(data): """Computes the unsigned Adler-32 checksum of a string.""" # We're using this instead of zlib.adler32() because it's easier to confirm # that this matches the JavaScript version of the same function below. Also, # zlib.adler32() returns a signed result, and we want an unsigned result. a, b...
def create_domains(prefix: str, n: int): """ Arguments: prefix: string - The prefix for all the domains created. n - How many domains to create. Returns: A list with all the domains """ s = [] for i in range(n): s.append(prefix + str(i)) return s
def greeting(name="World"): """ >>> greeting() 'Hello World!' >>> greeting("Vadym") 'Hello Vadym!' >>> greeting("vadYm") 'Hello Vadym!' """ return f"Hello {name.title()}!"
def dict_filter_keys_start_with(start, row): """ Given a dict, returns a new dict with key-value pairs where the key of each pair starts with start. """ return {k[len(start)+1:]: v for k, v in row.items() if k.startswith(start)}
def si_to_kmh(vals): """Conversion from SI wind speed units to km/hr. Note ---- Code was migrated from https://github.com/nguy/PyRadarMet. Parameters ---------- vals : float float or array of floats Speed in SI units (m/s) Returns ------- output: float ...
def LinearlyScaled(value, maximum, minimum=0.0, offset=0.0): """Returns a value scaled linearly between 0 and 1. Args: value (float): the value to be scaled. maximum (float): the maximum value to consider. Must be strictly positive and finite (i.e., can't be zero nor infinity). Returns: A ``fl...
def sort_tuple(t, key=None, reverse=False): """Returns a list.""" return sorted(t, key=key, reverse=reverse)
def _divide_with_ceil(a, b): """ Returns 'a' divided by 'b', with any remainder rounded up. """ if a % b: return (a // b) + 1 return a // b
def parse_cadence(row: str) -> int: """Parses cadence value string 'Xrpm' and returns X as int""" keyword = 'rpm' if keyword not in row: return -1, row if ',' in row: keyword += ',' cadence, rest = row.split(keyword) if '/' in cadence: cadence = sum([int(c) for c in cadence.split('/')])/2 ...
def uniquifier(seq, key=None): """ Make a unique list from a sequence. Optional key argument is a callable that transforms an item to its key. Borrowed in part from http://www.peterbe.com/plog/uniqifiers-benchmark """ if key is None: key = lambda x: x def finder(seq): seen =...
def formatting_cid_ocn_clusters(cid_ocn_list): """Put cid and ocn pairs into clusters by unique cids. Args: cid_ocn_list: list of dict with keys of "cid" and "ocn". [{"cid": cid1, "ocn": ocn1}, {"cid": cid1, "ocn": ocn2}, {"cid": cid3, "ocn": ocn3}] Returns: A dict with key=unique c...
def calculate_checkbox_match_likeness(value): """Used to determinate likeness with the tech stack. E.g. Node.js, PostgreSQL, Redis, MongoDB, Websockets, Docker, Amazon Web Services, Bash/UNIX scripting -> likeness=9, score=2 Node.js, Docker -> likeness=1, score=0 """ ...
def add_line_break(text, nbchar, maxlen=150): """ adding line break in string if necessary Parameters ---------- text : string string to check in order to add line break nbchar : int number of characters before line break maxlen : int number of characters before trun...