content
stringlengths
42
6.51k
def create_video_string(videoId): """ Function which accepts a videoId arg and returns sql string param: videoId = '342z248z' returns: " AND video_id in (342, 248)" """ video_list = videoId.split('z') video_string = " AND video_id in (" for video_id in video_list: ...
def is_int_like(value): """Returns whether the value can be used as a standard integer. >>> is_int_like(4) True >>> is_int_like(4.0) False >>> is_int_like("4") False >>> is_int_like("abc") False """ try: if isinstance(value, int): ret...
def prepare_string(string): """ Prepare string of command output as a list for parsing results """ args = None try: string = string.decode("utf-8") args = string.split(",") except Exception: raise return args
def multikeysort(dictlist, columns): """Sorts on arbitrary multiple columns of a dictionary. `columns` is a list of column names. Any names prefixed with '-' are sorted in descending order Inspired by: https://stackoverflow.com/questions/1143671/python-sorting-list-of-dictionaries-by-multiple-keys ...
def printIt(p): """ Input is decimal list. Returns character list corresponding to that decimal list """ s="" for byte in p: s=s+chr(byte) return s
def add(a, b): """ Returns the sum of two numbers.""" a, b = int(a), int(b) c = str(a + b) print("a = {} and b = {} and a + b = {}".format(a, b, c)) return c
def union(set1, set2): """ set1 and set2 are collections of objects, each of which might be empty. Each set has no duplicates within itself, but there may be objects that are in both sets. Objects are assumed to be of the same type. This function returns one set containing all elements from both inpu...
def mils(value): """Returns number in millions of dollars""" try: value = float(value) / 1000000 except (ValueError, TypeError, UnicodeEncodeError): return '' return '${0:,}M'.format(value)
def email( message_type, plaintext_body, reply_to, sender_address, sender_name, subject, html_body=None, variable_defaults=None, ): """ Required platform override when email in ua.device_types. Specifies content of the email being sent. All other notification fields are n...
def cgiFieldStorageToDict( fieldStorage ): """Get a plain dictionary, rather than the '.value' system used by the cgi module.""" params = {} for key in fieldStorage.keys(): params[ key ] = fieldStorage[ key ].value return params
def _bin(n): """ >>> _bin(0), _bin(1), _bin(63), _bin(4096) ('0', '1', '111111', '1000000000000') """ return str(n) if n <= 1 else _bin(n >> 1) + str(n & 1)
def required_preamble(title: str, author: str, date: str): """ Every output must contain this in the preamble """ return [r"\documentclass{article}", r"\usepackage[utf8]{inputenc}", r"\usepackage{amsthm}", r"\usepackage{breqn}", r"\usepackage{enumitem}", r"\usepackage{tcolorbox}", ...
def find_by_key(data: dict, target): """Find a key value in a nested dict""" for k, v in data.items(): if k == target: return v elif isinstance(v, dict): return find_by_key(v, target) elif isinstance(v, list): for i in v: if isinstance(...
def first_true(iterable, default=False, pred=None): """Returns the first true value in the iterable. If no true value is found, returns *default* http://docs.python.org/3.4/library/itertools.html#itertools-recipes """ return next(filter(pred, iterable), default)
def convert_price(price, use_float): """ Converts price to an integer representing a mil. 1 mil = 0.0001 Smallest representable size is 0.0001 """ if use_float: # Use floats to approximate prices instead of exact representation return int(float(price) * float(10000)) else: ...
def is_valid_combination(values, names): """ Should return True if combination is valid and False otherwise. Dictionary that is passed here can be incomplete. To prevent search for unnecessary items filtering function is executed with found subset of data to validate it. """ dictionary = d...
def _message_no_is_in_list(message_no, main_messages): """Returns True if the main message in Norwegian is in the list of main messages. :param message_no: :param main_messages: :return: """ is_in_list = False for m in main_messages: if message_no == m.main_message_no: ...
def show_pagination_panel(page_obj, search=''): """Shows pagination panel.""" return {'page_obj': page_obj, 'search': search}
def policy_list(context, request, policies_url=None, policy_url=None, remove_url=None, update_url=None, add_url=None): """ User list panel. Usage example (in Chameleon template): ${panel('policy_list')} """ return dict(policies_url=policies_url, policy_url=policy_url, remove_url=remo...
def interleaved_sum(n, odd_term, even_term): """Compute the sum odd_term(1) + even_term(2) + odd_term(3) + ..., up to n. >>> # 1 + 2^2 + 3 + 4^2 + 5 ... interleaved_sum(5, lambda x: x, lambda x: x*x) 29 >>> from construct_check import check >>> check(SOURCE_FILE, 'interleaved_sum', ['While'...
def check_rule(rule, email, group_ids): """ Check if a rule matches and email and group See create_rule() for an example of what a rule looks like. """ for match in rule["remote"]: if match.get("type") == "Email" and email in match.get("any_one_of"): break else: ret...
def readn(f, n): """Read n lines from a file iterator f.""" return "".join(f.readline() for _ in range(n))
def is_testable(reqs): """Filters dict requirements to only those which are testable""" for key, values in reqs.items(): if ("MUST" in values.get("keyword", "").upper()) and ( "none" not in values.get("validation_mode", "").lower() ): reqs[key]["testable"] = True ...
def _checkFore(r, c, linko): """Checks if (r,c) lies on a forelink for a node.""" initialNode = (r-c)//4 if initialNode < 0: return False forelinks = linko[initialNode][2] if len(forelinks) == 0: return False maxForelink = max(forelinks) return 2*maxForelink > 2*initi...
def _alpha_sorted_keys(length, range_from, range_to): """Test util which returns sorted alphabetically numbers range as strings """ return list(sorted(str(x) for x in range(length)))[range_from:range_to]
def create_previous_shift_vars(num_days, model, shifts, staff, shift_days): """Shift variables for previous roster period.""" prev_shift_vars = { (staff_member, role, day - num_days, shift): model.NewBoolVar( f"staff:{staff_member}" f"_role:{role}" f"_day:{day - num_d...
def intfmt(maxval, fill=" "): """ returns the appropriate format string for integers that can go up to maximum value maxvalue, inclusive. """ vallen = len(str(maxval)) return "{:" + fill + str(vallen) + "d}"
def formatSentence(variableList, finalSeparator="and"): """Turn a list of variables into a string, like 'Bill, John, and Jeff.'""" # Thanks to StackOverflow user Shashank: https://stackoverflow.com/a/30084397 n = len(variableList) # Creates a variable for the number of objects being formatted if n > 1:...
def back_to_clean_sent(token_ls): """ In order to perform sentiment analysis, here we put the words back into sentences. """ clean_sent_ls = [] for word_ls in token_ls: clean_sent = "" for word in word_ls: clean_sent += (word + " ") clean_sent_ls.append(clean_...
def oneHotEncode_EventType_exact(x, r_vals=None): """ This function one hot encodes the input for the event types cascade, tracks, doubel-bang """ # define universe of possible input values onehot_encoded = [] # universe has to defined depending on the problem, # in this implementation i...
def half_adder(a, b): """ ha_carry_out, ha_sum = a + b """ ha_sum = a ^ b ha_carry_out = a & b return ha_sum, ha_carry_out
def conv_curr(curr): """conv_curr(Access currency-typed field) -> float Return a float from MS Access currency datatype, which is a fixed-point integer scaled by 10,000""" return float(curr[1])/10000
def turn(fen): """ Return side to move of the given fen. """ side = fen.split()[1].strip() if side == 'w': return True return False
def selection_sort(arr): """Refresher implementation of selection sort - in-place & stable. :param arr: List of integers to sort :return: Sorted list """ for i in range(len(arr)): min = i # selecting index of smallest number for j in range(i, len(arr)): if arr[j]...
def deep_update(dct: dict, merge_dct: dict, copy=True) -> dict: """Merge possibly nested dicts""" from copy import deepcopy _dct = deepcopy(dct) if copy else dct for k, v in merge_dct.items(): if k in _dct and isinstance(dct[k], dict) and isinstance(v, dict): deep_update(_dct[k], v,...
def get_field_name(field_name): """handle type at end, plus embedded objets.""" field = field_name.replace('*', '') field = field.split(':')[0] return field.split(".")[0]
def compute_antenna_gain(phi): """Computes the antenna gain given the horizontal angle between user and basestation (3GPP spec)! Args: phi: (float) horizontal angle between user and basestation in degrees! Returns: (float) horizontal angle gain! ...
def input_new_values(formed_text, sample_list): """ formed_text: formatted text with {} sample_list: list of new user values formats text with user values :@return(String) Re-formatted version of """ return formed_text.format(*sample_list)
def is_property(attribute): """ Check if a class attribute is of type property. :ref: https://stackoverflow.com/questions/17735520/determine-if-given-class-attribute-is-a-property-or-not-python-object :param attribute: The class's attribute that will be checked. :rtype: bool """ return isins...
def min_insurance(replacement_cost): """ >>> min_insurance(100000) 80000.0 >>> min_insurance(123456789) 98765431.2 >>> min_insurance(0) 0.0 >>> min_insurance(-54317890) -43454312.0 """ return (replacement_cost * .8)
def as_snake_case(text: str) -> str: """ Converts CamelCase to snake_case. As a special case, this function converts `ID` to `_id` instead of `_i_d`. """ output = "" for i, char in enumerate(text): if char.isupper() and i != 0: # preserve _id if not (char == 'D' ...
def _any(oper, left, right): """Short circuit any for ndarray.""" return any(oper(ai, bi) for ai, bi in zip(left, right))
def num_frames(length, fsize, fshift): """Compute number of time frames of spectrogram """ pad = (fsize - fshift) if length % fshift == 0: M = (length + pad * 2 - fsize) // fshift + 1 else: M = (length + pad * 2 - fsize) // fshift + 2 return M
def shiny_gold_in(bag: str, rules: dict) -> bool: """Recursively check for shiny gold bags.""" if "shiny gold" in rules[bag].keys(): return True elif not rules[bag]: # bag holds no others return False else: for inner in rules[bag]: if shiny_gold_in(inner, rules): ...
def shift_vocab(all_letters, key): """ performs rot-key encipherment of plaintext given the key. essentially performs a char shift. key == 1 turns a=b, b=c, .. z=a; key == 3 turns a=c, b=e, .. z=c. returns a dict with orig chars as keys and new chars as values key = 1 returns d{'a':'b', 'b'...
def longest_row_number(array): """Find the length of the longest row in the array :param list in_array: a list of arrays """ if len(array) > 0: # map runs len() against each member of the array return max(map(len, array)) else: return 0
def my_squares(iters): """squaring loop function""" out=[] for i in range(iters): out.append(i**2) return out
def PassN(s,substring,iFrom,iN): """Find index after passing substring N times. """ while iN>0: iIndex= s.find(substring,iFrom) if iIndex==-1: return -1 else: iFrom=iIndex+1 iN-=1 return iFrom
def Chorda(func, a: float, b: float, epsilon: float, digitRound: int, showIteration: bool): """ Calculates solution of equation f(x) = 0 by using chorda iterative approximations. Parameters ---------- func : Callable Some function (method) returning by calling with input parameter x (float)...
def list_to_str(lst): """Convert a list of items into an underscore separated string. For Example: [1,2,3] -> _1_2_3 Args: lst: The list to convert into a string. Returns: The stringified list. """ s = '' for item in lst: s += '_%s' % (str(item)) return s
def make_foldername(name): """Returns a valid folder name by replacing problematic characters.""" result = "" for c in name: if c.isdigit() or c.isalpha() or c == "," or c == " ": result += c elif c == ':': result += "." elif c == '-': result += '-...
def to_camel_case(snake_str): """ Converts snake case and title case to camelCase. :param snake_str: :return: """ components = snake_str.split('_') # We capitalize the first letter of each component except the first one # with the 'title' method and join them together. # We ...
def get_key_for_grouping(item): """ Returns the key for grouping params during update of SqE. Parameters ---------- item : tuple (key, value) as given by dict.items() """ try: return item[0].split("_")[1] # This should be the name of the line except IndexError: ...
def count_possibilities(board_repr): """Count total number of possibilities remaining on sudoku board""" total = 0 for row in board_repr: for col in row: if isinstance(col, set) and len(col) > 1: total += len(col) return total
def is_valid_index (wordsearch, line_num, col_num): """Checks if the provided line number and column number are valid""" if ((line_num >= 0) and (line_num < len(wordsearch))): if ((col_num >= 0) and (col_num < len(wordsearch[line_num]))): return True retur...
def get_max_value_from_pop(neuron_data_array): """ Get maximum value from variable of population :param neuron_data_array: :return: """ max_val = -1000000 for neuron_data in neuron_data_array: neuron_data = map(float, neuron_data) if max(neuron_data) > max_val: ma...
def usb_lib_tx_data(device, data_8bit, timeout): """ Send data (64 bits per 8 bits) over USB interface :param device: device description, witch programmer get when use function usb_open_device :param data_8bit: Data to TX (8 bytes -> 64 bits) :type data_8bit: List of 8 bit data values :par...
def obj_spec_to_uri(obj_spec, job_to_uri, service_to_uri): """Convert a string of the form job_name[.run_number[.action]] to its corresponding URL """ obj_name_elements = obj_spec.split('.') obj_name = obj_name_elements[0] obj_rel_path = "/".join(obj_name_elements[1:]) obj_uri = None if...
def homo_degree_dist_filename(filestem): """Return the name of the homology degree distribution file.""" return f"{filestem}-degreedist.tsv"
def remove_postfix(text: str, postfix: str) -> str: """Removes a postfix from a string, if present at its end. Args: text: string potentially containing a postfix. postfix: string to remove at the end of text. """ if text.endswith(postfix): return text[:-len(postfix)] return...
def split_ngrams(seq, n): """ 'AGAMQSASM' => [['AGA', 'MQS', 'ASM'], ['GAM','QSA'], ['AMQ', 'SAS']] """ all_ngrams=[] for x in range(n): all_ngrams.append(zip(*[iter(seq[x:])]*n)) str_ngrams = [] for ngrams in all_ngrams: x = [] for ngram in ngrams: x.appe...
def get_status_summary(dictionary, certname, state): """ :param dictionary: dictionary holding the statuses :param state: state you want to retrieve :param certname: name of the node you want to find :return: int """ try: return dictionary[certname][state] except: return ...
def fmt_addr(socket): """(host, int(port)) --> "host:port" """ return "{}:{}".format(*socket)
def union(a, b): """ union of two lists """ return list(set(a) & set(b))
def toggleYears2(click): """ When syncing years, there should only be one time slider """ if not click: click = 0 if click % 2 == 0: style = {"display": "none", "margin-top": "0", "margin-bottom": "80"} else: style = {"margin-top": "0", "margin-bottom": "80"} return s...
def _value_of_point(point): """Extracts the actual numeric value of a point. Only supports int64 and double point values. Strings, booleans, distribution and money are not supported. See cloud.google.com/monitoring/api/ref_v3/rest/v3/projects.metricDescriptors#ValueType """ pval = point['value'...
def _scale(x, lb, ub): """Scales the values to be normalized to [lb, ub].""" return (x - lb) / (ub - lb)
def join_name(name_parts: list, separator: str = "__", ignore_none: bool = True) -> str: """ joins individual parts of a name (i.e., file name consisting of different elements) :param name_parts: the elements to join :param separator: the separator to be used to join :param ignore_none: if True, Non...
def get_area_raster(raster: str) -> str: """Determine the path of the area raster for a given backscatter raster based on naming conventions for HyP3 RTC products Args: raster: path of the backscatter raster, e.g. S1A_IW_20181102T155531_DVP_RTC30_G_gpuned_5685_VV.tif Returns: area_rast...
def calc_euclid_distance_2d_sq(p1: tuple, p2: tuple): """ Returns the square of the euclidian distance between p1 and p2 Useful as it's much cheaper than calculating the actual distance (as it save a call to sqrt()) and if checking a < b, then a^2 < b^2 will also give the correct va...
def hammingDistance(s1, s2): """Return the Hamming distance between equal-length sequences""" if len(s1) != len(s2): raise ValueError("Undefined for sequences of unequal length") return sum(el1 != el2 for el1, el2 in zip(s1, s2))
def get_uniq(my_list): """ Get the unique elements of a list while preserving the order (order preserving) """ target_list = [] [target_list.append(i) for i in my_list if not target_list.count(i)] return target_list
def to_terminal(group): """Create a terminal node value""" outcomes = [row[-1] for row in group] return max(set(outcomes), key=outcomes.count)
def hyperlink(text: str, link: str): """Turns text into a hyperlink. Parameters ---------- text : str The text that turns `blue`. link : str The link Returns ------- str The hyperlink. """ ret = "[{}]({})".format(text, link) return ret
def list_to_dict(config): """ Convert list based beacon configuration into a dictionary. """ _config = {} list(map(_config.update, config)) return _config
def valid_str_only(item, allow_bool: bool = False) -> bool: """ Removes empty strings and other invalid values passed that aren't valid strings. :param item: Check if valid str :param allow_bool: Allow the use of bool only if True :return: bool """ if isinstance(item, str)...
def other_reverse_invert(lst): """Best practice solution from codewars.""" from math import copysign as sign return [-int(sign(int(str(abs(x))[::-1]), x)) for x in lst if isinstance(x, int)]
def _toVersionTuple(versionString): """Split a version string like "10.5.0.2345" into a tuple (10, 5, 0, 2345). """ return tuple((int(part) if part.isdigit() else part) for part in versionString.split("."))
def cleaner_unicode(string): """ Objective : This method is used to clean the special characters from the report string and place ascii characters in place of them """ if string is not None: return string.encode('ascii', errors='backslashreplace') else: return string
def decode_alt_info(cigar_count, ref_base, depth, minimum_allele_gap): """ Decode the input read-level alternative information cigar_count: each alternative base including snp, insertion and deletion of each position pileup_bases: pileup bases list of each read in specific candidate position from samtoo...
def getSequenceDifference(lst): """ Returns an array of the subtracted value from each nth + 1 element and the nth element. :param lst: A list of numerics from which the differences between following elements will be retrieved. \t :type lst: [numerics] \n :returns: The subtracted values from each nt...
def _get_coordinator(hostname, port=9001): """ Generates the coordinator section of a Myria deployment file """ return '[master]\n' \ '0 = {}:{}\n\n'.format(hostname, port)
def _join_lists(obj): """ Return *obj* with list-like dictionary objects converted to actual lists. :param obj: Arbitrary object Example:: {'0': 'apple', '1': 'pear', '2': 'orange'} ... returns ... ['apple', 'pear', 'orange'] """ # If it's not a dict, it's definitel...
def is_service_named(service_name: str, service: dict) -> bool: """Handles a case where DC/OS service names sometimes don't contain the first slash. e.g.: | SDK service name | DC/OS service name | |--------------------------+-------------------------| | /data-services/cassandra ...
def niceGetter(thing, *args): """ Given a nested dictionary "thing", Get any nested field by the path described: eg niceGetter(thing, 'cars', 'mustang', 'cobra') will return thing['cars']['mustang']['cobra'] or None if such item doesn't exist. """ if thing == None: return None subthing =...
def get_greater(children: list): """Return greater value among the children node""" if len(children) == 0: return None, float('inf') if len(children) == 1: return children[0] else: return children[0] if children[0][1] > children[1][1] else children[1]
def elk_index(hashDict): """ Index setup for ELK Stack bulk install """ index_tag_full = {} index_tag_inner = {} index_tag_inner['_index'] = "hash-data" index_tag_inner['_id'] = hashDict['hashvalue'] index_tag_full['index'] = index_tag_inner return index_tag_full
def parseData(txt): """Auxiliary function. Takes plain text description of binary data from protocol specification and returns binary data""" import re result = "" for a in re.split('\s+', txt): if re.match('x[0-9a-f]{2}', a, re.IGNORECASE): result += chr(int(a[1...
def br_to_us_number_format(numb_str: str) -> str: """ Removes dot as thousand separator and replaces comma decimal separator with dot >>> br_to_us_number_format('10.000,00') '10000.00' """ return numb_str.replace(".", "").replace(",", ".")
def parse_project_version(version): """ Parse project version to a tuple of integer. That can be used for a lexicographical comparison of values. Arguments: version (str): project version code as a string. Returns: Parsed project version as a tuple with integer values. """ ...
def coding_problem_23(matrix, start, end): """ You are given an M by N matrix consisting of booleans that represents a board. Each True boolean represents a wall. Each False boolean represents a tile you can walk on. Given this matrix, a start coordinate, and an end coordinate, return the minimum number...
def get_descr_full(tables,description): """List descriptors, with unit and name/description""" desc_text = [] for d in description: d = int(d) if d > 0 and d < 100000: desc_text.append(str(tables.tab_b[d])) elif d >= 100000 and d < 200000: lm...
def get_delta_of_fedmd_nfdp(n, k, replacement=True): """Return delta of FedMD-NFDP Args: n (int): training set size k (int): sampling size replacement (bool, optional): sampling w/o replacement. Defaults to True. Returns: float: delta of FedMD-NFDP """ if replacemen...
def RelogOptionsSet(options): """ Are any of the 'relog_*' options set to True? If new relog_* options are added, then make sure and add them to this method. """ return options.relog_code_exclude != '' or options.relog_focus or \ options.relog_name != '' or options.relog_no_cleanup or ...
def encode_string_link(text): """Replace special symbols with its codes.""" text = text.replace("<", "%3C") text = text.replace(">", "%3E") text = text.replace("[", "%5B") text = text.replace("]", "%5D") text = text.replace("{", "%7B") text = text.replace("}", "%7D") text = text.replace(...
def dmse(f_x, y): """ dMSE(f_x,y) = 2* (f_x-y) """ return 2 * (f_x - y)
def third(n) -> int: """Calculates one-third of a given value. Args: n: the integer to calculate one-third of Returns: int: one-third of n, rounded down """ return int(n / 3)
def separate(text): """ Process a text to get its parts. :param text: :return: [head,body,end] """ right = text.rstrip() left = text.lstrip() return (text[0:-len(left)], text[-len(left):len(right)], text[len(right):])
def replace_values_in_dict_by_value(replace_values, target_dict): """ Takes a dict with value-replacement pairs and replaces all values in the target dict with the replacement. Returns the resulting dict. """ ret_dict = target_dict.copy() for val, replacement in replace_values.items(): for key, dict_val in targ...
def is_mt_str(my_str) -> bool: """Check to see if the given input is an empty string Function that checks the given parameter my_str to see if it is an empty string. Uses the innate identity __eq__ to check. :param my_str: String to check if it is empty :type my_str: str :return: Boolean indic...