content
stringlengths
42
6.51k
def add_filter(modifiers, new_filter): """Add filter to the modifiers. :param dict modifiers: modifiers :param sqlalchemy.sql.expression.BinaryExpression new_filter: filter :return dict modifiers: new modifiers """ if modifiers is None: modifiers = {} if 'filter' not in modifiers: ...
def utc_to_gps(utcsec): """ Convert UTC seconds to GPS seconds. Parameters ---------- utcsec: int Time in utc seconds. Returns ------- Time in GPS seconds. Notes ----- The code is ported from Offline. Examples -------- >>> utc_to_gps(315964800) # Jan 6th...
def interpret_distribution(key, value): """ interpret input distribution descriptions into usable entries """ dist_name, args = value.split('(') # uniform(a, b) to ['Uniform', 'a, b)'] dist_name = dist_name.strip() # clear whitespace args = args.strip(')').split(',') ...
def load_items(data): """ Loading items into the game. Parameters: data(dict): Nested dictionaries containing all information of the game. Returns: items_name(list): Returns list of item names. """ items_name = list(data['Items'].keys()) return items_name
def is_palindrome(input): """ Return True if input is palindrome, False otherwise. Args: input(str): input to be checked if it is palindrome """ # Termination / Base condition if len(input) <= 1: return True else: first_char = input[0] last_char = input[-1] ...
def cubic(x, a, b, c, d): """ @type x: number @type a: number @type b: number @type c: number @type d: number Calculates cubic function a*x^3+b*x^2+c*x+d @rtype: number @return: result of cubic function calculation """ return a * (x ** 3) + b * (x ** 2) + c * x + d
def bfs_visited(node, graph): """BFS: Return visited nodes""" queue = [node] visited = [] while queue: current = queue.pop() # Enqueue unvisited neighbors queue[0:0] = [neighbor for neighbor in graph[current] if neighbor not in visited] visited.append(current) return...
def get_search_params(url_path): """ From the full url path, this prunes it to just the query section, that starts with 'q=' and ends either at the end of the line of the next found '&'. Parameters ---------- url_path : str The full url of the request to chop up Returns -...
def get_nodes_ordered_balance_keys(src, edge_data): """ This functions gets the source node in the route and return which node is it (node1 ot node2 in the channel) :param src: src node in the route :param edge_data: dictionary containing the edge's attributes. :return: the order of the nodes in the...
def get_rate_from_actset(action, actset): """ Returns rate from actset returned from solver """ for act in actset: if act[0] == action: return float(act[1])
def _around_mean(prmsl, i: int, j: int): """_around_mean. Args: prmsl: i: j: """ sum_data = 0 for i in range(-1, 2, 1): for j in range(-1, 2, 1): if i == 0 and j == 0: continue sum_data += prmsl[i+i][j+i] return sum_data / ...
def _cast_none(value: str) -> None: """Cast None""" if value == "": return None raise ValueError(f"Expect `@none`, got `{value}`")
def is_positive(number): """ The is_positive function should return True if the number received is positive and False if it isn't. """ if number > 0: return True else: return False
def _get_node(root, name): """ Find xml child node with given name """ for child in root: if child.get('name') == name: return child raise ValueError(f'{name} not found')
def find_next_tip(remaining_id_lst, s, s_values): """find the next tip on the same contour, encoded in s_values. Supposes remaining_id_lst is a sorted list of spiral tip indices, Example Usage: j_nxt=find_next_tip(remaining_id_lst, s, s_values) """ j_nxt=-9999;k=1 kmax=len(remaining_id_lst) while (j_nxt<0)&(k<=...
def uleb128Encode(num): """ Encode int -> uleb128 num -- int to encode return -- bytearray with encoded number """ arr = bytearray() length = 0 if num == 0: return bytearray(b"\x00") while num > 0: arr.append(num & 127) num = num >> 7 if num != 0: arr[length] = arr[length] | 128 length+=1 re...
def first_not_none(obj, default): """ returns obj if it is not None, otherwise returns default """ return default if obj is None else obj
def word_list_to_long(val_list, big_endian=True): """Word list (16 bits int) to long list (32 bits int) By default word_list2long() use big endian order. For use little endian, set big_endian param to False. :param val_list: list of 16 bits int value :type val_list: list :p...
def is_err(p4filename): """ True if the filename represents a p4 program that should fail. """ return "_errors" in p4filename
def check_is_iterable(py_obj): """ Check whether a python object is a built-in iterable. Note: this treats unicode and string as NON ITERABLE Args: py_obj: python object to test Returns: iter_ok (bool): True if item is iterable, False is item is not """ # Check if py_obj is a...
def recall(overlap_count, gold_count): """Compute the recall in a zero safe way. :param overlap_count: `int` The number of true positives. :param gold_count: `int` The number of gold positives (tp + fn) :returns: `float` The recall. """ if gold_count == 0: return 0.0 return overlap_count /...
def render_svg(pixels): """ Converts a sense hat pixel picture to SVG format. pixels is a list of 64 smaller lists of [R, G, B] pixels. """ svg = '<svg xmlns="http://www.w3.org/2000/svg" width="80" height="80">' for y in range(8): for x in range(8): color = pixels[(y*8)+x] ...
def _assemble_mif(sim_object): """ assemble_mif(sim_object, output) Function to take a simulation instance and return a string which can be used as a MIF file. Parameters ---------- sim_object : instance A simulation instance. Returns ------- string The...
def xor(a, b): """Return the XOR of two byte sequences. The length of the result is the length of the shortest.""" return bytes(x ^ y for (x, y) in zip(a, b))
def dict_to_json_keys(pydict: dict) -> dict: """this converts a dict using the python coding style to a dict where the keys are in JSON format style :pydict dict keys are strings in python style format :returns dict """ d = {} for key in pydict.keys(): new_key = key.title().replace('...
def r_capitalize(l: list) -> list: """Recursively calls str.capitalize on each string in l.""" result = [] if not l: return [] result.append(l[0].capitalize()) return result + r_capitalize(l[1:])
def float_nsf(num, precision=17): """n-Significant Figures""" return ('{0:.%ie}' % (precision - 1)).format(float(num))
def fibonacci(n): """Returns the n th fibonacci number""" if n in [0, 1]: # The special case of n being 0 or 1 return 1 a = 1 b = 0 fib_sequence=[] for i in range(n - 1): temp = b # A temporary variable to remember the value of b b = a + b # New value of b f...
def identify_exclusive_feature_groups(entries): """ Identifies exclusive FASM features and creates groups of them. Returns a dict indexed by group names containing sets of the features. """ groups = {} # Scan entries, form groups for entry in entries: # Get the feature and split i...
def non_exp_repr(x): """Return a floating point representation without exponential notation. Result is a string that satisfies: float(result)==float(x) and 'e' not in result. >>> non_exp_repr(1.234e-025) '0.00000000000000000000000012339999999999999' >>> non_exp_repr(-1.234e+018) '-...
def get_neighbor_pos(pos): """ Helper function to get right sibling -- no guarantee it exists in tree """ neighbor = list(pos) neighbor[-1] += 1 return neighbor
def format_answers(project, form_data): """ """ if project is None: return {} answers = project.answers keys = [k for k, v in form_data.items() if 'answers' in k] if len(keys) == 0: return answers for k in keys: splt = k.split('_') aspect_id = splt[1] ...
def del_elements(ele: int, lst: list) -> list: """Remove an element from a list""" new_lst = lst.copy() new_lst.remove(ele) return new_lst
def csv_safe(obj): """Puts quotes around strings with commas in them. """ string = str(obj) return '"' + string + '"' if "," in string else string
def _KindsListToTuple(get_schema_kinds_list): """Called to return default tuple when no datastore statistics are available. """ results = [] if get_schema_kinds_list: for kind_str in sorted(get_schema_kinds_list): results.append({'kind_name': kind_str}) return '', results
def rgb2cmyk(r, g, b): """ Convert rgb color to cmyk color. """ c = 1 - r m = 1 - g y = 1 - b k = min(c, m, y) c = min(1, max(0, c - k)) m = min(1, max(0, m - k)) y = min(1, max(0, y - k)) k = min(1, max(0, k)) return c, m, y, k
def mac_addr_convert(mac_address=u""): """ Function for providing single format for MAC addresses. :param str mac_address: MAC address to be converted. :return: MAC address in format `XX:XX:XX:XX:XX:XX`. """ try: mac = mac_address.replace(".", "") mac = [mac[i:i + 2].upper() for...
def format_serial(serial_int): """Format the volume serial number as a string. Args: serial_int (long|int): The integer representing the volume serial number Returns: (str): The string representation xxxx-xxxx """ serial_str = None if serial_int == 0: return serial_str ...
def get_hamming_mismatch(genome1, genome2): """returns the number of mismatches between strings""" count = 0 for idx, item in enumerate(genome1): if genome1[idx] != genome2[idx]: count += 1 return count
def get_useful_information(info): """Extracts useful information from video.""" result = {} result['description'] = info['description'] result['id'] = info['id'] result['thumbnail'] = info['thumbnail'] result['title'] = info['title'] result['uploader'] = info['uploader'] return result
def string_to_index(needle, columns): """Given a string, find which column index it corresponds to. :param needle: The string to look for. :param columns: The list of columns to search in. :returns: The index containing that string. :raises ValueError: Value "`needle`" not found in columns "`column...
def instrumentLookup(instrument_df, symbol): """Looks up instrument token for a given script from instrument dump""" try: return instrument_df[instrument_df.tradingsymbol == symbol].instrument_token.values[0] except: return -1
def key(d, key_name): """ Performs a dictionary lookup. """ try: return d[key_name] except KeyError: return 0
def txtToDict(txtfile): """Read vertices from a text file of (Lon, Lat) coords. Input file represents a single polygon with a single line list of comma-separated vertices, e.g.: "<lon>, <lat>, <lon>, <lat>, ...". """ with open(txtfile) as f: polygon = f.readline() if not polygon: ...
def getPrediction(neighbors, weights): """ Computes the weighted vote of each of the k-neighbors Adds up all votes of each entry. And retruns the key of the entry with the highest number of votes. """ import operator votes = {} for x in range(len(neighbors)): respon...
def popget(d, key, default=None): """ Get the key from the dict, returning the default if not found. Parameters ---------- d : dict Dictionary to get key from. key : object Key to get from the dictionary. default : object Default to return if key is not found in dict...
def phone_edit_distance(predicted_str, ref_str): """ Estimate the edit distance between predicted and ref phone sequences. """ predicted_list = predicted_str.split(" ") ref_list = ref_str.split(" ") m, n = len(predicted_list), len(ref_list) dp = [[0] * (m+1) for _ in range(n+1)] dp[0][0] = 0 ...
def filter_by_type(lst, type_of): """Returns a list of elements with given type.""" return [e for e in lst if isinstance(e, type_of)]
def calc_new_dimensions(max_size: int, width, height): """ Calculate new minimum dimensions and corresponding scalar :param max_size: int :param width: int :param height: int :return: tuple - new dimensions and minimum scalar """ width_scalar = max_size / width height_scalar = max_si...
def convert_to_numeric(score): """Convert the score to a float.""" converted_score = float(score) return converted_score
def unpack_tupla(tupla): """unpack_tupla""" (word1, word2) = tupla final = word1 + " " + word2 return final
def get_str_dates_from_dates(dates): """ function takes list of date objects and convert them to string dates :param dates: list of date objects :return str_dates: list of string dates """ str_dates = [] for date in dates: str_dates.append(str(date)) return str_dates
def check_indices(indices_size, index): """Checks indices whether is empty.""" if indices_size < 1: raise IndexError( "The tensor's index is unreasonable. index:{}".format(index)) return indices_size
def revcomp(seq, ttable=str.maketrans('ATCG','TAGC')): """Standard revcomp """ return seq.translate(ttable)[::-1]
def get_macs(leases): """ get list of macs in leases leases is a dict from parse_dhcpd_config return macs as list for each host in leases dict """ return [leases[host]['mac'] for host in leases]
def dbuv_to_uV(dbuv): """ dBuv (dB microvolts) to V (volts) @param dbuv : dB(uV) @type dbuv : float @return: uV (float) """ return (10**(dbuv/20.))
def _get_value(cav, _type): """Get value of custom attribute item""" if _type == 'Map:Person': return cav["attribute_object_id"] if _type == 'Checkbox': return cav["attribute_value"] == '1' return cav["attribute_value"]
def validate_message_prop_value(prop, value): """Check if prop and value is valid.""" if prop not in ["Direction", "Speed", "Status"]: return False if prop == "Direction": if value not in ["E", "W", "N", "S"]: return False if prop == "Speed": if not value.isdigit()...
def mid_point(bboxes): """ Method to find the bottom center of every bbox Input: bboxes: all the boxes containing "person" Returns: Return a list of bottom center of every bbox """ mid_values = list() for i in range(len(bboxes)): #get the coordinates coor =...
def match_asset(asset_name, goos, goarch): """ Compate asset name with GOOS and GOARCH. Return True if matched. """ asset_name = asset_name.lower() goarch = { "386": ["386"], "amd64": ["amd64", "x86_64"] }[goarch] match_goos = goos in asset_name match_goarch = any([wo...
def get_tags_from_string(tags_string): """Return list of tags from given string""" if tags_string: tags = tags_string.split(', ') else: tags = [] return [ tag for tag in tags if tag ]
def b64_validator(*payload): """Checks if base64 string is a multiple of 4 and returns it unchanged if so, otherwise it will trim the tail end by the digits necessary to make the string a multiple of 4 Args: encodedb64: Base64 string. Returns: decoded Base64 string. """ date, e...
def linear_extrap(x1, x2, x3, y1, y2): """ return y3 such that (y2 - y1)/(x2 - x1) = (y3 - y2)/(x3 - x2) """ return (x3-x2)*(y2-y1)/(x2-x1) + y2;
def decode_response(rec): """ Decodes a response from the server """ return rec.decode().split(",")
def class_to_name(class_label): """ This function can be used to map a numeric feature name to a particular class. """ class_dict = { 0: "Hate Speech", 1: "Offensive Language", 2: "Neither", } if class_label in class_dict.keys(): return class_dict[class_label...
def convert_postag(pos): """Convert NLTK POS tags to SentiWordNet's POS tags.""" if pos in ['VB', 'VBD', 'VBG', 'VBN', 'VBP', 'VBZ']: return 'v' elif pos in ['JJ', 'JJR', 'JJS']: return 'a' elif pos in ['RB', 'RBR', 'RBS']: return 'r' elif pos in ['NNS', 'NN', 'NNP', ...
def multy(b: int) -> int: """2**b via naive recursion. >>> multy(17)-1 131071 """ if b == 0: return 1 return 2*multy(b-1)
def path_exists(source, path, separator='/'): """Check a dict for the existence of a value given a path to it. :param source: a dict to read data from :param path: a key or path to a key (path is delimited by `separator`) :keyword separator: the separator used in the path (ex. Could be "." for a ...
def convert_uint16_to_array(value): """ Converts a int to an array of 2 bytes (little endian) :param int value: int value to convert to list :return list[int]: list with 2 bytes """ byte0 = value & 0xFF byte1 = (value >> 8) & 0xFF return [byte0, byte1]
def format_indentation(string): """ Replace indentation (4 spaces) with '\t' Args: string: A string. Returns: string: A string. """ return string.replace(" ", " ~ ")
def c2t(c): """Make a complex number into a tuple""" return c.real, c.imag
def check_word(p, tok = None, dep = None, up_tok = None, up_dep = None, precede = None): """ Returns an indicator and a marker If parameters match any word in the sentence: returns 1, markers for each occurance Else: returns 0, [] """ toks = [] for ind, x in enumerate(p): ...
def lower(word: str) -> str: """ Will convert the entire string to lowecase letters >>> lower("wow") 'wow' >>> lower("HellZo") 'hellzo' >>> lower("WHAT") 'what' >>> lower("wh[]32") 'wh[]32' >>> lower("whAT") 'what' """ # converting to ascii value int value and...
def sum_sequence(sequence): """ What comes in: A sequence of integers. What goes out: Returns the sum of the numbers in the given sequence. Side effects: None. Examples: sum_sequence([8, 13, 7, -5]) returns 23 sum_sequence([48, -10]) returns 38 sum_sequence([]) ...
def Hubble(Om, z): """ LCDM AP parameter auxiliary function (from pybird) """ return ((Om) * (1 + z)**3. + (1 - Om))**0.5
def _cyclic_permutations(lst): """Return the list of cyclic permutations of the list lst""" if lst == []: return [[]] plst = [] for _ in range(len(lst)): plst.append(lst) lst = lst[1:] + [lst[0]] return plst
def asym_peak_L(t, pars): """ Lorentizian function. Parameters ------------- t : 'array' pars : 'array' Parameters used in the decomposition. E.g. heigh, center, width. Returns ------------- function """ a0 = pars[0] # height a1 = pars[1] # center a2 = p...
def limit_ordered_from_domain(domain): """ Testdata: ("3", "2c", "2b", "2a", "1") or ("ORIGIN", "not ok", "LIMIT_VALUE", "ok") yield domain[len(domain) // 2] -> "2b" or "LIMIT_VALUE" in domain -> "LIMIT_VALUE" """ if not domain: return "NULL" if "LIMIT_VALUE" in domain: return "L...
def throw_empty_pairs(src_tgt_pairs): """Filter [src,tgt] tuple from input list of pairs if either element is empty. Args: src_tgt_pairs: list of (src,tgt) pairs Returns: subset of input pair list for which all elements are non-empty """ return [x for x in src_tgt_pairs if x[0] and x[1]]
def sum_digits(n): """Sum the digits of N.""" L = [] for s in str(n): L.append(int(s)) return sum(L)
def indent(lines, amount, ch=" "): """ Indent the lines in a string by padding each one with proper number of pad characters """ padding = amount * ch return padding + ("\n" + padding).join(lines.split("\n"))
def top(list_to_truncate, number): """ Returns top n elements of a list. """ return list_to_truncate[0:number]
def fix_wg_name(wgname): """Check no non-alphanumerics and convert to lowercase.""" wgname = wgname.lower() if wgname.isalnum(): return wgname raise SystemExit('Non-alphanumeric in WG name: "%s"' % (wgname,)) return wgname
def format_seconds(seconds): """ Takes in a number of seconds and returns a string representing the seconds broken into hours, minutes and seconds. For example, format_seconds(3750.4) returns '1 h 2 min 30.40 s'. """ minutes = int(seconds // 60) hours = int(minutes // 60) remainder_sec ...
def _is_domain_2nd_level(hostname): """returns True if hostname is a 2nd level TLD. e.g. the 'elifesciences' in 'journal.elifesciences.org'. '.org' would be the first-level domain name, and 'journal' would be the third-level or 'sub' domain name.""" return hostname.count(".") == 1
def UnicodeEscape(string): """Helper function which escapes unicode characters. Args: string: A string which may contain unicode characters. Returns: An escaped string. """ return ('' + string).encode('unicode-escape')
def and_field_filters(field_name, field_values): """AND filter returns documents that contain fields matching all of the values. Returns a list of "term" filters: one for each of the filter values. """ return [ { "term": { field_name: value, } } ...
def is_valid_int(s: str) -> bool: """ Return true if s can be converted into a valid integer, and false otherwise. :param s: value to check if can be converted into a valid integer :return: true if s can be converted into a valid integer, false otherwise >>> is_valid_int("hello") False >>> ...
def _d4rl_dataset_name(env_name): """Obtains the TFDS D4RL name.""" split_name = env_name.split('-') task = split_name[0] version = split_name[-1] level = '-'.join(split_name[1:-1]) return f'd4rl_adroit_{task}/{version}-{level}'
def format_time(t): """Format time for nice printing. Parameters ---------- t : float Time in seconds Returns ------- format template """ if t > 60 or t == 0: units = 'min' t /= 60 elif t > 1: units = 's' elif t > 1e-3: units = 'ms' ...
def norm_min_max_dict(dict1): """ min-max normalization for dictionary :param dict1: input dictionary :return: min-max normalized dictionary """ for key, value in dict1.items(): dict1[key] = round((dict1[key] - min(dict1.values())) / (max(dict1.values()) - min(dict1.values())), 3) re...
def _msg_prefix_add(msg_prefix, value): """Return msg_prefix with added value.""" msg_prefix = f"{msg_prefix}: " if msg_prefix else "" return f"{msg_prefix}{value}"
def calculateBallRegion(ballCoordinate, robotCoordinate) -> int: """ Ball region is the region of the ball according to robot. We assumed the robot as origin of coordinate system. Args: ballCoordinate (list): x, y, z coordinates of the ball. robotCoordinate (list): x, y coordinates of the robot. ...
def no_space(x) -> str: """ Remove the spaces from the string, then return the resultant string. :param x: :return: """ return x.replace(' ', '')
def add_weights_to_postcode_sector(postcode_sectors, weights): """ Add weights to postcode sector """ output = [] for postcode_sector in postcode_sectors: pcd_id = postcode_sector['properties']['id'].replace(' ', '') for weight in weights: weight_id = weight['id'].repla...
def lazy_set_default(dct, key, lazy_val_func, *args, **kwargs): """ A variant of dict.set_default that requires a function instead of a value. >>> d = dict() >>> lazy_set_default(d, 'a', lambda val: val**2, 5) 25 >>> lazy_set_default(d, 'a', lambda val: val**3, 6) 25 >>> d {'a': 25}...
def parse_refs_json(data): """ Function to parse the json response from the references collection in Solr. It returns the results as a list with the annotation and details. """ # docs contains annotation, fileName, details, id generated by Solr docs = data['response']['docs'] # Create a list obj...
def trapezoidal(f, x_min, x_max, n=1000) -> float: """input fx --> function, x_min, x_max. return hasil integrasi """ h = (x_max - x_min) / n # lebar grid jum = 0.5 * f(x_min) for i in range(1, n): xi = x_min + h * i jum = jum + f(xi) jum = jum + 0.5 * f(x_max) hasil = jum *...
def only_keys(d, *keys): """Returns a new dictionary containing only the given keys. Parameters ---------- d : dict The original dictionary. keys: list of keys The keys to keep. If a key is not found in the dictionary, it is ignored. """ result = dict() for ...
def clean_chars_reverse(command: str) -> str: """ replaces mongodb characters format with standard characters :param command: discord command to be converted :type command: str :return: converted command :return type: str """ clean_freq_data = command if "(Dot)" in clean_f...