content
stringlengths
42
6.51k
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 """ "*** YOUR CODE HERE ***" def allodd(n): if n == 1: return od...
def eps_compare(f1, f2, eps): """Return true if |f1-f2| <= eps.""" res = f1 - f2 if abs(res) <= eps: # '<=',so eps == 0 works as expected return 0 elif res < 0: return -1 return 1
def text_key(toks): """Key for sentence comparison (punctuation/casing differences are taken into account).""" return ' '.join(toks)
def is_single_line_docstring(line: str) -> bool: """Returns True if the line starts with 0 or more spaces and begins and ends with \"\"\" """ line = line.strip() return line.startswith('"""') and line.endswith('"""') and line.count('"""') == 2
def find_index_from_time(time, sampling_rate): """ Gives the index corresponding to an input time. This relies on the sampling rate Arguments: time - time needed to convert to index sampling_rate - sampling rate of the list """ index = int(round(time*sampling_rate)) return index
def unquote(s): """ Strips matching single and double quotes from the start and end of the given string. """ if len(s) > 1 and ((s[0] == '"' and s[-1] == '"') or (s[0] == "'" and s[-1] == "'")): return s[1:-1] else: return s
def generate_mapping(length, positions): """generate mapping""" start_mapping = [0] * length end_mapping = [0] * length for _, (start, end) in enumerate(positions): start_mapping[start] = 1 end_mapping[end] = 1 return start_mapping, end_mapping
def remove_speed(video_file): """some of my files are suffixed with datarate, e.g. myfile_3200.mp4; this trims the speed from the name since it's irrelevant to my sprite names (which apply regardless of speed); you won't need this if it's not relevant to your filenames""" video_file = video_file.strip...
def get_name_query_cond(type: str, val: str, query_params: dict): """ Returns the entered string as part of an SQL condition on the AHJ table of the form: AHJ.`type` = 'val' AND if val is not None, otherwise it returns the empty string to represent no condition on type. """ if va...
def buy_sell_hold(*args, pct_change = 0.035): """ :param args: The columns we're evaluating for pct change in price :param pct_change: the percentage change of the price of the stock to trigger a buy or sell action. The default is 0.02 (2%) :return: 1 for a buy signal, -1 for a sell signal, and 0 f...
def comp_pos_ends(pos1, pos2): """Compare sequence data end positions""" if not pos1 or not pos2: return 0 if pos1['chrom'] < pos2['chrom']: return -1 elif pos1['chrom'] > pos2['chrom']: return 1 else: if pos1['end'] < pos2['end']: return -1 elif p...
def has_children_of_marriage(responses, derived): """ Returns whether or not the their are children of marriage for claim""" return responses.get('children_of_marriage', '') == 'YES'
def list_to_dict_entry(input): """ Take a list of strings and parse through looking for a string ending with a ':', if found, join the previous entries into one string and remove the ':' and leave remaining entries alone. If no ':' is found just return the list of strings unmodified. """ output = in...
def matmul_legalize(attrs, inputs, types): """Legalizes matmul op. Parameters ---------- attrs : tvm.ir.Attrs Attributes of current matmul inputs : list of tvm.relay.Expr The args of the Relay expr to be legalized types : list of types List of input and output types ...
def compress_switch_to_file_type(gz=False, bz2=False, xz=False): """Return compressed target file_type based on supplied switches. """ return (gz and 'gzip') or (bz2 and 'bzip2') or (xz and 'xz') or 'text'
def contains_an_even_digit(n: int) -> bool: """ Return True if n contains an even digit. >>> contains_an_even_digit(0) True >>> contains_an_even_digit(975317933) False >>> contains_an_even_digit(-245679) True """ return any(digit in "02468" for digit in str(n))
def to_bytes(value) : """ Decodes value to bytes. Args: value : Value to decode to bytes Returns: :obj:`bytes` : Return the value as bytes: if type(value) is :obj:`bytes`, return value; if type(value) is :obj:`str`, return the string encoded with UTF-8; ...
def reverse(values): """ REVERSE - WITH NO SIDE EFFECTS! """ output = list(values) output.reverse() return output
def which(program): """Function to check for presence of executable/installed program Used for checking presense of ffmpeg/avconv""" import os def is_exe(fpath): return os.path.isfile(fpath) and os.access(fpath, os.X_OK) fpath, fname = os.path.split(program) if fpath: if is_e...
def split_string_on_spaces(s, line_length=100): """Split a string into lines based on whitespace.""" line_buff = [] str_buff = "" for token in s.split(): # Can we put this token on this line without going over? if str_buff: if len(str_buff) + len(token) > line_length: ...
def create_actions_file_msg(second_run: bool): """Actions File Message""" article = "another" if second_run else "an" return "Do you want to create %s action file?" % article
def font_family(font: str): """ Returns an SVG font family attribute using the given font name. :param font: `str` font name :return: font-family="<font>" """ return f'font-family="{font}"'
def countNum(num, elem): """Return the occurance of a given number in the specified list of numbers""" countNum = 0 for i in range(len(num)): if elem == num[i]: countNum += 1 return countNum
def html_escape(text): """ Removes HTML chars from the given text and replace them with HTML entities. """ html_escape_table = { '"': "&quot;", "'": "&apos;", ">": "&gt;", "<": "&lt;"} return "".join(html_escape_table.get(c, c) for c in text)
def _transform(s): """Convert input to a numerical type if possible. Parameters ---------- s : str Input variable Returns ------- A non-string object is returned as it is. A string object is converted to int, float, str in that order """ if not type(s) is str: ...
def check_bit(val, n): """ Returns the value of the n-th (0 index) bit in given number """ try: if val & 2**n: return 1 else: return 0 except TypeError: return -1
def printable_characters_rank(plaintexts): """Return a list of (plaintext, rank) tuples where the higher the rank, the less non-printable characters are in the plaintext """ ranked_plaintexts = [] for key, plaintext in plaintexts: printable_chars_count = 0 for byte in plaintext: ...
def get_sb_date(date_type, sb_json): """Get start of end date of a project. Arguments: date_type -- (string) "start", "end", or "publication" will cause the function to search for either the start, end, or publication date, respectively, of the project. ...
def traditional_basal_equation(tdd): """ Traditional basal equation with constants fit to Jaeb dataset """ a = 0.5086 return a * tdd
def GateBranches(x, **unused_kwargs): """Implements a gating function on a (memory, gate, candidate) tuple. Final update is memory * gate + (1-gate) * candidate This gating equation may also be referred to as Highway Network. Highway Networks: https://arxiv.org/abs/1505.00387 Args: x: A tuple of (memor...
def tf(tokens): """ Compute TF Args: tokens (list of str): input list of tokens from tokenize Returns: dictionary: a dictionary of tokens to its TF values """ return dict( [ (i, float(tokens.count(i))/len(tokens)) for i in set(tokens) ] )
def text_progress(current, total): """Opens the photo_import_settings.json file in a text editor Parameters: current (String): The currently completed progress total (String): The total amount Returns: progress (String): A formatted string with the current progress [current/total]...
def encrypt(plaintext, key): """ :param plaintext: string :param key: int :return: """ ciphertext = "" for char in plaintext: oNum = ord(char) if oNum > 127: # not a ASCII character new_char = char else: if(oNum + key > 127): # If value is t...
def object_to_bytes(object, encoding='utf-8'): """ Translate an object into its string form and then convert that string into its raw bytes form. :param object: An object to convert into a bytes literal. :param encoding: A string value indicating the encoding to use. Defaults to...
def PMT(n,r,pv,fv): """ Objective: estimate period payment (like Excel function) n : number of periods r : discount rate pv : present value fv : period payment e.g., >>>PMT(10,0.08,100000,0) 14902.948869707534 """ return (pv-fv/(1+r)**n)*r/...
def rendu_temps(temps): """ Affiche l'ordre de grandeur du temps restant :param temps: Le temps restant en secondes :return: Un texte donnant son ordre de grandeur en jour/heures/minutes """ minutes = temps // 60 % 60 heures = temps // 3600 % 24 jours = temps // 86400 if jours != 0: ...
def name_predicate(name_dict): """Only include names that pass this predicate.""" professions = name_dict["primaryProfession"] return ( professions and ("actor" in professions or "actress" in professions or "director" in professions))
def getFlag(flagbyte, pos): """ Returns the bit at 'pos' in 'flagbyte' """ mask = 2 ** pos result = flagbyte & mask return (result == mask)
def tuple1(lst): """ Converts list to tuple or single value. If argument `lst` is a list (or other enumerable) holding more than one item, then this function returns a tuple with the same values with their original order preserved. If argument hold only single value, that value itself is returned. ...
def get_source_max(source="V"): """units for source/measure elements""" if source == "V": # we source voltage and measure current return 20 elif source == "I": # we source current and measure voltage return 100
def convert_quality_to_dbm(quality): """ converts quality (percent) to dbm. conversion between quality (percentage) and dBm is as follows: `quality = 2 * (dbm + 100) where dBm: [-100 to -50]` `dbm = (quality / 2) - 100 where quality: [0 to 100]` https://docs.microsoft.com/en-us/windows/deskto...
def insertionSort(lst): """ Start from index 1 we are going to start comparing with previous values and starting from index 0 wouldn't have any previous value. Hold value at index 1 (current index) Iterate through all previous values one by one Compare each value with current hold...
def _loc(name, size=(0, 0), title_space=0, frame=.01): """Convert loc argument to ``(x, y)`` of bottom left edge""" if isinstance(name, str): y, x = name.split() # interpret x elif len(name) == 2: x, y = name else: raise NotImplementedError("loc needs to be string or len=2 tu...
def order_data(date, code, course, teacher): """ Put data in order of cell occurance """ return [ date, course["name"], code, course["part_name"], course["points"], teacher["name"], teacher["phone"], teacher["section"] ]
def get_split(text): """ Split each news text to subtexts no longer than 150 words. """ l_total = [] l_parcial = [] if len(text.split())//120 > 0: n = len(text.split())//120 else: n = 1 for w in range(n): if w == 0: l_parcial = text.split()[:150] ...
def sort_numbers(nums): """ Sorts an array of numbers. :param nums: array of integers. :return: sorted array. """ if nums: return sorted(nums) return []
def cal_max_len(ids, curdepth, maxdepth): """calculate max sequence length""" assert curdepth <= maxdepth if isinstance(ids[0], list): res = max([cal_max_len(k, curdepth + 1, maxdepth) for k in ids]) else: res = len(ids) return res
def validateInterpolations(cmodel, layers): """Validate logistic model interpolation. Args: cmodel (dict): Sub-dictionary from config for specific model. layers (dict): Dictionary of file names for all input layers. Returns: dict: Model interpolation methods. """ interpolat...
def pretty_node(node): """Helper to convert node to string""" return '(%s, %s)' % node
def default_objective(k, p): """ Default objective function. """ delta = 0 if k < 1.1 : delta = k - 1.1 return 1.0 * (1.5 - p) + 50.0 * delta
def restrict_keys(d: dict, domain) -> dict: """Remove from d all items whose key is not in domain; return d. >>> d = {'a': 1, 'b': 2} >>> dr = restrict_keys(d, {'a', 'c'}) >>> dr {'a': 1} >>> d == dr True """ for k in set(d): if k not in domain: del d[k] retur...
def is_valid_input(letter_guessed): """ letter_guessed checks if the argument passed is a valid English letter or not. :param letter_guessed: player's char :type letter_guessed: string :return: True or False, if the player's char is in English :rtype: boolean """ is_valid = ((len(letter_...
def timestamps2frame_durations(timestamps: list, last_frame_duration=None) -> list: """ Produces frame durations list to make gifs produced with write_pc2gif() more accurate temporally, Parameters ---------- timestamps : list List of timestamps of corresponding array frames. last_f...
def html(text: str) -> str: """Helper function to escape html symbols""" return text.replace(u'&', u'&amp;').replace(u'<', u'&lt;').replace(u'>', u'&gt;')
def dotv3(a,b): """dot product of 3-vectors a and b""" return a[0]*b[0] + a[1]*b[1] + a[2]*b[2];
def format_report_class(row): """ This filter returns a css class based on the score's type. Parameters: row - A single score row """ try: if row['type'] in ['integer', 'float', 'percent']: return 'right' if row['type'] == 'list': return 'left' ...
def dict_to_form(obj: dict): """Encode a form to dict""" return '&'.join('{0}={1}'.format(k, v) for k, v in obj.items())
def get_children(node): """ Return the children of the node. The children are all the elements of the except the first :param node: The node :type node: list :return: The children of the node :rtype: list """ # Take a slice of the list except the head return node[1:]
def VecDot(a, b): """Return the dot product of two vectors. Args: a: n-tuple of floats b: n-tuple of floats Returns: n-tuple of floats - dot product of a and b """ n = len(a) assert(n == len(b)) sum = 0.0 for i in range(n): sum += a[i] * b[i] return sum
def min_list(lst): """ A helper function for finding the minimum of a list of integers where some of the entries might be None. """ if len(lst) == 0: return None elif len(lst) == 1: return lst[0] elif all([entry is None for entry in lst]): return None return min([entr...
def parse_class_namespace_string(class_string): """ Parses the dotted namespace out of an object's __mro__. Returns a string """ class_string = str(class_string) class_string = class_string.replace("'>", "") class_string = class_string.replace("<class '", "") return str(class_string)
def valence(atm): """ valence of an atom """ vlnc_dct = {'H': 1, 'C': 4, 'N': 3, 'O': 2, 'S': 2, 'Cl': 1} return vlnc_dct[atm]
def is_diff_one_char(source: str, target: str) -> bool: """ :param source: :param target: :return: >>> is_diff_one_char('hot', 'hit') True >>> is_diff_one_char('hot', 'hto') False """ flag = 0 for i, s in enumerate(source): if s != target[i]: flag += 1 ...
def onlyinA(listA, listB): """ return element that's only in list A but not in B""" setA = set(listA) setB = set(listB) return list(setA.difference(setB))
def longest_valid_parentheses2(s): """ Solution 2 """ max_len = 0 start = 0 stack = [] for i in range(len(s)): if s[i] == "(": stack.append(i) else: if len(stack) == 0: start = i + 1 else: stack.pop() ...
def transpose(obj, i, j, numrows, numcols, section, more, custom): """Transpose the rows and columns of a table Warning: once this function has changed the structure, it would be unwise to do anything else to the table on the same invocation of MODIFY TABLES! Therefore, it returns False in ord...
def ordinal(num: int) -> str: """ Returns the ordinal representation of a number Examples: 11: 11th 13: 13th 14: 14th 3: 3rd 5: 5th :param num: :return: """ return ( f"{num}th" if 11 <= (num % 100) <= 13 else f"...
def med_min_2darray(a): """Takes in a list of lists of integers and returns the minimum value.""" return min(min(inner) for inner in a)
def squote(s): """ Return s as a single-quoted quoted string """ return u"'" + s.replace(u"'", u"''").replace(u'\0', '') + u"'"
def is_prime(number): """Check if a number is a prime number. Args: number (int): Number. Returns: bool: Return True if number is a prime number and False if not. """ if number <= 1: return False for x in range(2, number): if not number % x: return ...
def uppercase_to_camelcase(key): """ :param key: :type key str :return: """ _list = key.lower().split('_') _key = _list[0] for i in _list[1:]: _key += i.capitalize() return _key
def _merge_module_maps(maps): """ Given a collection of module maps (dictionaries), returns a module map consisting of the entries of each of the maps. """ result = {} for m in maps: for k, v in m.items(): result[k] = v return result
def boiler_state_bit_english(raw_table, base_index): """ Convert derog bit flag to English """ value = raw_table[base_index] stringvalue = "" if value & (1 << 1): stringvalue += "[Direct Circuit OFF] " if value & (1 << 2): stringvalue += "[3WV Circuit OFF] " if value & (1 << 3): ...
def file_has_content(file, content, encoding="utf-8"): """ Check and return if a file has a content inside. Arguments: file : str content : str Returns: bool """ with open(file, encoding=encoding) as f: if content in f.read(): return True retu...
def _serializer(obj): """ Render particular types in an appropriate way for logging. Allow the json module to handle the rest as usual. """ # Datetime-like objects if isinstance(obj, bytes): return obj.decode('utf-8') if hasattr(obj, 'isoformat'): return obj.isoformat().deco...
def object_name(x): """Get a human readable name for an object.""" if hasattr(x, "__name__"): return x.__name__ elif hasattr(x, "__func__"): return object_name(x.__func__) else: return str(x)
def build_flex_args_keys(components): """ Helper function to build a list of options. Some tools require require variations of the same options (e.g., cflags for debug vs release builds), but manually creating those options is cumbersome and error-prone. This function handles that work by combinin...
def pymote_equal_objects(obj1, obj2): """ Compare two objects and their attributes, but allow for non immutable attributes to be equal up to their class. """ classes = obj1.__class__ == obj2.__class__ attr_names = attr_values = True if isinstance(obj1, object) and isinstance(obj2, object): ...
def merge(left, right): """Merge two sorted list to one sorted list""" res = [] p1, p2 = 0, 0 while True: if p1 == len(left): res.extend(right[p2:]) break elif p2 == len(right): res.extend(left[p1:]) break elif left[p1] < right[p2...
def firstCyclicNode(head): """ :type head: Node :rtype: Node """ runner = walker = head while runner and runner.next: runner = runner.next.next walker = walker.next if runner is walker: break if runner is None or runner.next is None: return None ...
def is_latlon_valid(location): """Checks whether a pair of coordinates is valid. Args: location (str): A pair of latlon coordinates separated by comma or space. Returns: bool: Returns True if valid. """ latlon = [] if ',' in location: latlon = [float(x) for x in locatio...
def reMapAnnotation(oldAnnotation, oldToNewMapping): """ Maps an annotation list to a new according to the given mapping. :param oldAnnotation: the original annotation :param oldToNewMapping: the mapping :return: the new annotation list """ if oldAnnotation == None or oldToNewMapping ...
def steamIdFormula(z, v=0x0110000100000000, y=1): """Formula for converting Steam ID to Steam Community ID From https://developer.valvesoftware.com/wiki/SteamID Args: v (int, optional) : account type, defaults to user: 0x0110000100000000 y (int, optional) : account universe, defaults to publ...
def rsplit_longest_suffix(uname, suffixes): """Split-out longest matching suffix from uniform name string. **Usage**:: prefix, suffix = rsplit_longest_suffix(uname,suffixes) **Description** The ``uname`` argument is assumed to be a uniform name string (not necessary full) in form ``"foo...
def do_xor(string_a, string_b): """ <Purpose> Produce the XOR of two equal length strings <Arguments> string_a, string_b: the strings to XOR <Side Effects> None <Exceptions> ValueError if the strings are of unequal lengths TypeError if the strings are not strings <Returns> ...
def training_parameters(blob_model_info): """ Define json training parameters for single structure predictor :param blob_model_info: model info :type blob_model_info: dict :return: training parameters :rtype: dict """ return { 'method': blob_model_info['ModelCode'], 'fi...
def sec_deriv_lorentzian(x, x0, gamma, I): """ Function to evaluate the second derivative of a Lorentzian lineshape function. This was evaluated analytically with SymPy by differentiation of the Lorentzian expression used for the `lorentzian` function in this module. Parameters ---------- ...
def maxes(iterable, key=lambda x: x): """ Analogous to ``max``, but returns a list of all maxima. >>> all(key(elem) == max(iterable, key=key) for elem in iterable) True Parameters ---------- iterable: collections.abc.Iterable The iterable for which to find all maxima. key: coll...
def compare_rules(x,y): """ Compares parser rules and sees which has more tokens or conditions (prev, next) """ diff = len(y['tokens'])-len(x['tokens']) if diff != 0: return diff (x_conds, y_conds) = (0,0) for cond in ('prev','next'): if cond in x: x_conds +=len(cond) ...
def sigma_top(sigma_lc_top, sigma_hc_top, x_aver_top_mass): """ Calculates the surface tension at the top of column. Parameters ---------- sigma_lc_top : float The surface tension of low-boilling component at the top of column, [N / m] sigma_hc_top : float The surface tension of ...
def yubikey_public_id(otp): """ Returns the yubikey identity given a token. """ return otp[:12]
def get_labels_json(panel_json, column, row): """Return dict of labels data for figure JSON.""" labels = [] channels = panel_json['channels'] imagename = panel_json['name'] if row == 0: labels.append({"text": channels[column]['label'], "size": 8, ...
def _boto_tags_to_dict(tags): """Convert the Tags in boto format into a usable dict [{'Key': 'foo', 'Value': 'bar'}, {'Key': 'ham', 'Value': 'spam'}] is translated to {'foo': 'bar', 'ham': 'spam'} """ return {item['Key']: item['Value'] for item in tags}
def is_isogram(string): """ Check if the text passed in is an isogram. :param string string - Text to check :return bool - Isogram, or not. - Filter for alpha filter + list will convert the string to a list - Count occurences of each charater if theres more than 1 then it's not...
def _assign_zero_one_to_split(zero_one_value, split_percents, split_names): """ Assign a value between 0 and 1 to a split according to a percentage distribution """ split_props_cum = [sum(split_percents[0:(i+1)]) for i in range(0, len(split_percents))] for sn, sp in zip(sp...
def systemctl_show_pid_cmd(cmd, shell="bash"): """ Returns the output that systemctl show <service> would return This is a stub function. The expected usage of this function is to replace a Node object which is able to run CLI commands. The command being run is: systemctl show {service} -...
def parse_tint(tint): """Parse tint string, returns tuple.""" if len(tint) == 0: return None return tuple(int(n) for n in tint.split(','))
def _to_integers(lst): """ Coerce all members of a list to integers. """ return list(map(int, lst))
def canWin2(s): """ :type s: str :rtype: bool """ if not s or len(s)<2: return False for i in range(len(s)-1): if s[i]=='+' and s[i+1]=='+': temp=s s=s[:i]+'--'+s[i+2:] if not canWin2(s): return True s=temp retur...
def get_release_version(version): """ If version ends with "-SNAPSHOT", removes that, otherwise returns the version without modifications. """ if version is None: return None if version.endswith("-SNAPSHOT"): return version[0:-len("-SNAPSHOT")] return version