content
stringlengths
42
6.51k
def convert_from_alphabet(a): """Encode a character :param a: one character :return: the encoded value """ if a == 9: return 1 if a == 10: return 127 - 30 # LF elif 32 <= a <= 126: return a - 30 else: return 0
def duplicate(N, Elem): """ N = integer() >= 0 Elem = T List = [T] T = term() Returns a list which contains N copies of the term Elem. For example: > lists:duplicate(5, xx). [xx,xx,xx,xx,xx] Note: Function taken from Erlang - http://erldocs.com/17.3/stdlib/lists.html#duplicat...
def split_query_into_tokens(query): """ Splits query string into tokens for parsing by 'tokenize_query'. Returns list of strigs Rules: Split on whitespace Unless - inside enclosing quotes -> 'user:"foo bar"' - end of last word is a ':' -> 'user: foo' Example: >>>...
def is_sudoku_complete(output_grid): """ Checks if every square of the output grid is non-zero :param output_grid: Grid of the found squares, len(9) list of len(9) lists of ints :return: True if complete, False if not """ if any([any([square == 0 for square in row]) for row in output_g...
def pack_parameter_id(domain_id: int, unique_id: int, linear_index: int) -> bytearray: """Packs the Parameter ID (bytearray with 4 bytes) which is part of the service 20 packets. The first byte of the parameter ID is the domain ID, the second byte is a unique ID and the last two bytes are a linear index if ...
def _urldecode(input): """URL-decode metadata""" output = bytearray() nibbles = 0 value = 0 # Each input character for char in input: if char == '%': # Begin a percent-encoded hex pair nibbles = 2 value = 0 elif nibbles > 0: # Parse...
def lines_from_geometry(geo): """Convert an iterable of geometry to lines. Suitable for passing directly to `matplotlib.collections.LineCollection`. :param geo: An iterable of geometry items. If cannot be coverted to a line, then ignored. :return: A list of coordinates. """ ...
def get_hashtags(tokens): """Extract hashtags from a set of tokens""" hashtags = [x for x in tokens if x.startswith("#")] return hashtags
def hex_str_to_bytes_str(hex_str): """Converts the hex string to bytes string. :type hex_str: str :param hex_str: The hex tring representing trace_id or span_id. :rtype: str :returns: string representing byte array """ return bytes(bytearray.fromhex(hex_str))
def map_atoms(indices, nres_atoms=1): """ Map the indices of a sub-system to indices of the full system :param indices: indices of atoms to map with respect to full system :param nres_atoms: number of atoms per residue :type indices: list :type nres_atoms: int :return: dictionary of mapped in...
def copy_state_dict(state_dict_1, state_dict_2): """Manual copy of state dict. Why ? Because when copying a state dict to another with load_state_dict, the values of weight are copied only when keys are the same in both state_dict, even if strict=False. """ state1_keys = list(state_dict_1.keys()) ...
def autodocument_from_superclasses(cls): """Fill in missing documentation on overridden methods. Can be used as a class decorator. """ undocumented = [] for name, attribute in cls.__dict__.items(): # is it a method on the class that is locally undocumented? if hasattr(attribute, '__...
def is_url(url: str) -> bool: """Return True if a string is a URL. >>> is_url("") False >>> is_url(" ") False >>> is_url("http://example.com") True """ return url.startswith("http")
def format_limit(lim): """Format the 'LIMIT' keyword line for SPARQL queries. """ if lim is None: return "" return "\nLIMIT %d" % lim
def repeatName(name, times): """Repeat a name a number of times.""" name_repeated = name * times return name_repeated
def get_excluded_params(schema): """ Get all params excluded in this schema, if "only" is provided in schema instance, consider all not included params as excluded. :param schema: instance or cls schema :return: set of excluded params """ if isinstance(schema, type): return set()...
def steps_f12(j=None, Xs=None): """Stepsize for f update given current state of Xs""" # Lipschitz const is always 2 L = 2 slack = 0.1# 1. return slack / L
def insertion(l): """"Insertion Sort. takes input as a list by reference.""" m = len(l) for i in range(1, m): k = l[i] j = i - 1 while j >= 0 and k < l[j]: l[j + 1] = l[j] j -= 1 l[j + 1] = k return l
def supportInterval(thing): """Lower and upper bounds on this value, if known.""" if hasattr(thing, 'supportInterval'): return thing.supportInterval() elif isinstance(thing, (int, float)): return thing, thing else: return None, None
def actionColor(status): """ Get a action color based on the workflow status. """ if status == 'success': return 'good' elif status == 'failure': return 'danger' return 'warning'
def estimate_sparse_size(num_rows, topK): """ :param num_rows: rows or colum of square matrix :param topK: number of elements for each row :return: size in Byte """ num_cells = num_rows*topK sparse_size = 4*num_cells*2 + 8*num_cells return sparse_size
def radix_sort(arr, radix=10): """ Sorts an array of integers inplace using radix sort method. A type of bucket sort method which sorts keys by their binary representation. Algorithms: sequencially select the least significant digit (for radix=10) and collect all keys with equal digit in the same bucke...
def get_name_spaces(words): """Check number of spaces for a given set of words. Args: words (list): A list of words Returns: dict: The data and summary results. """ results = [{'word': word, 'spaces': len(word.split(r' '))} for word in words] return { 'da...
def make_board(N): """ Utility function that returns a new N x N empty board (empty spaces represented by '*') Arg N: integer - board dimensions - must be greater than or equal to 1 """ assert N >= 1, "Invalid board dimension"; assert type(N) == int, "N must be an integer"; return [["*" for ...
def render_hunspell_word_error( data, fields=["filename", "word", "line_number", "word_line_index"], sep=":", ): """Renders a mispelled word data dictionary. This function allows a convenient way to render each mispelled word data dictionary as a string, that could be useful to print in the con...
def f_path_rename(text): """Function to rename path columns - aux function""" list_columns = [] for properties_name in text: properties_name = properties_name.lower() properties_name = properties_name.replace(' ', '_') properties_name = 'path_' + properti...
def _slice_required_len(slice_obj): """ Calculate how many items must be in the collection to satisfy this slice returns `None` for slices may vary based on the length of the underlying collection such as `lst[-1]` or `lst[::]` """ if slice_obj.step and slice_obj.step != 1: return None ...
def getRelevantInfoDict (dataDict): """Returns a dictionary of the relevant/useful information from JSON object string returned from API call given in the form of a dictionary.""" return { 'locationName' : dataDict['name'], 'country' : dataDict['sys']['country'], 'temp' : da...
def count(context, tag, needle): """ *musicpd.org, music database section:* ``count {TAG} {NEEDLE}`` Counts the number of songs and their total playtime in the db matching ``TAG`` exactly. """ return [('songs', 0), ('playtime', 0)]
def is_inverse(a, b) -> bool: """Checks if two provided directions are the opposites of each other. """ if (a == 2 and b == 3) or (a == 3 and b == 2): return True if (a == 0 and b == 1) or (a == 1 and b == 0): return True return False
def remove_empty(dictionary): """Removes empty entries from a dictionary.""" for key in list(dictionary.keys()): if dictionary.get(key) is None: del dictionary[key] return dictionary
def distinct_words(corpus): """ Determine a list of distinct words for the corpus. Params: corpus (list of list of strings): corpus of documents Return: corpus_words (list of strings): list of distinct words across the corpus, sorted (using python 'sorted' function) ...
def orient(mag_azimuth, field_dip, or_con): """ uses specified orientation convention to convert user supplied orientations to laboratory azimuth and plunge Parameters: ________________ mag_azimuth: float orientation of the field orientation arrow with respect to north fi...
def convert_to_azimuth(angle): """Converts Near 180 to -180 angles to Azimuth Angles. Will also normalize any number to 0-360 . @param: angle - angle denoted in terms of 180 to -180 degrees @returns angle - angle 0 to 360""" if angle <= 180 and angle > 90: azimuth_angles = 360.0 - (angle - 90) ...
def roll_by_one( cups ): """ This functions rolls the cups by one unit. The new current cup is the next cup in the clockwise direction. """ return cups[1:] + cups[:1]
def get_events_by_ref_des(data, ref_des): """ """ result = [] return result
def duplicatesRemoval(checked, node, path_penalty): """ IF A collaborated with B, B is also connected to A so when checking B we do not need to add A however since we have multi path this is not as straightforward, we are only not required to add the node if we found a previous path to the node that present...
def xmatch_score(a, b): """ Simple scoring function: 1 for same value, else 0 """ if a == b: return 1 else: return 0
def var_lower_length(tabu_lenght, tabu_var): """ Validation function that assert that tabu_var isn't higher number than tabu_lenght Parameters: ----------- tabu_lenght: int tabu_var: int """ if tabu_var <= tabu_lenght: return tabu_var else: raise ValueError("tabu_var can't be highe...
def gcContent(seq): """calculate G/C content of sequence""" gc = seq.count("C") + seq.count("G") gcPercent = 100 * (float(gc) / len(seq)) return int(round(gcPercent))
def make_filter_gff_cmd(gff, baddies, newgff): """ given a gff file and a file of unwanted locus tags, run inverse grep Note 2019-04-25 this is a ticking time bomb """ # -f means get pattern from file # -v means return inverse match return "grep {0} -f {1} -v > {2}".format(gff, baddies, newgff)
def sigmoid_5params(x, a, b, c, d, g): """ :return: """ return d + ((a - d) / (1 + (x / c) ** b) ** g)
def decode_textfield_base64(content): """ Decodes the contents for CIF textfield from Base64. :param content: a string with contents :return: decoded string """ import base64 return base64.standard_b64decode(content)
def get_schemaloc_string(ns_set): """Build a "schemaLocation" string for every namespace in ns_set. Args: ns_set (iterable): set of Namespace objects """ schemaloc_format = '{0.name} {0.schema_location}' # Only include schemas that have a schema_location defined (for instance, # 'xsi' d...
def mock_install_repository(path: str): """ Does not actually perform anything, but still returns a result dict like the other install functions. This result dict contains the following fields: - success: True - path: The path passed as parameter - git: Github URL :return: dict """ ...
def parse_pct(value): """ Parse percentage """ return float(value)/100
def dict_to_boto3_tags(tag_dict): """ Convenience function for converting a dictionary to boto3 tags :param tag_dict: A dictionary of str to str. :return: A list of boto3 tags. """ return [ {"Key": key, "Value": value} for key, value in tag_dict.items() ]
def ppmv2pa(x, p): """Convert ppmv to Pa Parameters ---------- x Gas pressure [ppmv] p total air pressure [Pa] Returns ------- pressure [Pa] """ return x * p / (1e6 + x)
def dot(a, b): """Dot product of two TT-matrices or two TT-vectors""" if hasattr(a, '__dot__'): return a.__dot__(b) if a is None: return b else: raise ValueError( 'Dot is waiting for two TT-vectors or two TT- matrices')
def are_vulnerabilities_equivalent(vulnerability_1, vulnerability_2): """ Check if two vulnerability JSON objects are equivalent :param vulnerability_1: dict JSON object consisting of information about the vulnerability in the format presented by the ECR Scan Tool :param vul...
def direction(a, b): """ 3, 5 => +1 5, 3 => -1 5, 5 => 0 """ return 1 if b > a else -1 if a > b else 0
def list2dict(lst): """Convert the list from RedisAI to a dict.""" if len(lst) % 2 != 0: raise RuntimeError("Can't unpack the list: {}".format(lst)) out = {} for i in range(0, len(lst), 2): key = lst[i].decode().lower() val = lst[i + 1] if key != "blob" and isinstance(val...
def get_vpo(values): """ This function shifts values one index backwards. Day_1: m11, m12, *m13 Day_2: m21, m22, *m23 Day_3: m31, m32, *m33 We want to predict values with *, so If we want to train our network to predict Day_1 we don't have any data from the previous day, so we can't ...
def _cohort_cache_key(user_id, course_key): """ Returns the cache key for the given user_id and course_key. """ return f"{user_id}.{course_key}"
def even(n): """ Counts the number of EVEN digits in a given integer/float """ try: if type(n) in [int, float]: return sum([True for d in str(n) if d.isdigit() and int(d) % 2 == 0]) else: raise TypeError("Given input is not a supported type") except TypeError as ...
def get_url(year_of_study, session): """ :param year_of_study: 1, 2, 3 or 4. :param session: Examples: 20199 is fall 2019. 20195 is summer 2019. :return: """ return "https://student.utm.utoronto.ca/timetable/timetable?yos={0}&subjectarea=&session={1}&courseCode=&sname=&delivery=&courseTitle="....
def webotsToScenicPosition(pos): """Convert Webots positions to Scenic positions.""" x, y, z = pos return (x, -z)
def update_residual_model(residual_model, coefficients_to_add, delta, delta_old): """Update linear and square terms of the residual model. Args: residual_model (dict): Dictionary containing the parameters of the residual model, i.e. "intercepts", "linear_terms", and "square terms". ...
def capitalize_word(string): """capitalize_word Title case the word without .title Args: string (str): The string Returns: str: The capitalized string """ final_word = str() # #1 - Split the string split_str = string.split() # #2 - For each word, captialise ...
def numRollsToTarget(d, f, target): """ throw d dice with faces numbered 1 to f. how many combinations of faces showing sum to target say on the nth die, we see face value j, then numWays(n, f, target) = numWays(n-1, f, target-j) """ dp = [[0]*(target+1) for _ in range(d+1)] dp[0][0] = 0 for...
def fibbs(n): """ Input: the nth number. Output: the number of the Fibonacci sequence via iteration. """ sequence = [] for i in range(n+1): if i == 0: sequence.append(0) elif i == 1: sequence.append(1) else: total = sequence[i - 2] + se...
def inverse_interleave(a, b): """ Given a coordinate where `a` has been interleaved and `b` hasn't, return the value that `a` would have at `b=0`. """ if a % 2 == 0: return a + b % 2 else: return a - (b+1) % 2
def getLine(x1, y1, x2, y2): """Returns a list of (x, y) tuples of every point on a line between (x1, y1) and (x2, y2). The x and y values inside the tuple are integers. Line generated with the Bresenham algorithm. Args: x1 (int, float): The x coordinate of the line's start point. y1 (int,...
def get_util(maximize, p_dog, p_other, payoffs): """ >>> get_util(True, 1.0, 1.0, [1,2,3,4]) 1.0 >>> get_util(True, 1.0, 0.5, [1,2,3,4]) 1.5 >>> get_util(True, 0.5, 0.5, [1,2,3,4]) 2.25 >>> get_util(True, 0.0, 1.0, [1,2,3,4]) 4.0 >>> get_util(True, 1.0, 0.0, [1,2,3,4]) 2.0 ...
def replace_domain_terms(text, domain_terms, replacement): """ Replace domain terms within text :param text: the text to process :param domain_terms: the list of domain terms :param replacement: the replacement for the domain terms :return: the processed string """ for word in domain_ter...
def str2num(string): """ -------------------------------------------------- Tries to see if 'string' is a number If 'string' is a string, returns: int(string) for integers float(string) for floats 'string' otherwise If 'string' is a float or an integer, returns: str...
def parse_float(float_str, default=0): """Parses the float_str and returns the value if valid. Args: float_str: String to parse as float. default: Value to return if float_str is not valid. Returns: Parsed float value if valid or default. """ try: return float(float...
def render_bytes(source, *args): """Peform ``%`` formating using bytes in a uniform manner across Python 2/3. This function is motivated by the fact that :class:`bytes` instances do not support ``%`` or ``{}`` formatting under Python 3. This function is an attempt to provide a replacement: it conve...
def should_import(managedcluster): """ should_import returns True if the input managedCluster should be imported, and False if otherwise. :param managedcluster: name of managedCluster to import :return: bool """ conditions = managedcluster['status'].get('conditions', []) for condition in...
def parse_path(path): """ http://www.w3.org/TR/2014/WD-html-json-forms-20140529/#dfn-steps-to-parse-a-json-encoding-path """ original = path failure = [(original, {'last': True, 'type': object})] steps = [] try: first_key = path[:path.index("[")] if not first_key: ...
def calc_x(f, t): """Calc x from t. :param f: the param of interp :type f: dict :param t: step of interp :type t: int :return: x corrdinate :rtype: float """ return f['a_x'] + f['b_x'] * t + f['c_x'] * t * t + f['d_x'] * t * t * t
def falling(n, k): """Compute the falling factorial of n to depth k. >>> falling(6, 3) # 6 * 5 * 4 120 >>> falling(4, 3) # 4 * 3 * 2 24 >>> falling(4, 1) # 4 4 >>> falling(4, 0) 1 """ "*** YOUR CODE HERE ***" res = 1 while k > 0: res = res * n n -=...
def is_classifier(estimator): """ Returns True if the given estimator is (probably) a classifier. From: https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/base.py#L526 """ return getattr(estimator, "_estimator_type", None) == "classifier"
def max_precision(term2rank, total_terms): """Computes the MAP (max average precision) over the whole candidate list Args: result2rank: A dict of source to ranks of good translation candidates. total_terms: The expected term count. Returns: A dict containing a precision value for e...
def checksums2dict(checksums: list) -> dict: """ Converts a list of checksums to a dict for easier look up of a block :param checksums: tuple of checksums :return: dictionary of {checksum: index} """ result = {} for index, checksum in enumerate(checksums): if checksum not in result:...
def logistic_rhs(t, x, r=2., k=2.): """ RHS evaluation of logistic ODE, returns f(t, x) = r * x * (1 - x/k) """ return r * x * (1. - x / k)
def is_callable(value, **kwargs): """Indicate whether ``value`` is callable (like a function, method, or class). :param value: The value to evaluate. :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains d...
def parse_comma_separated_list(value): """Parse a comma-separated list. :param value: String or list of strings to be parsed and normalized. :returns: List of values with whitespace stripped. :rtype: list """ if not value: return [] if not isinstance(value, ...
def dt2str (dt): """ Convert a datetime object to a string for display, without microseconds :param dt: datetime.datetime object, or None :return: str, or None """ if dt is None: return None dt = dt.replace(microsecond = 0) return str(dt)
def boyer_moore_majority_vote(arr): """ My Python implementation of the Boyer-Moore majority vote algorithm Finds the majority (more than half) element of an input sequence, if it exists Time complexity: O(n), n = Length of input sequence Space complexity: O(1) """ majority, counter...
def human_list(l, separator="and"): """ Formats a list for human readability. Parameters ---------- l : sequence A sequence of strings separator : string, optional The word to use between the last two entries. Default: ``"and"``. Returns ------- formatted_...
def decode_extra_length(bits, length): """Decode extra bits for a match length symbol.""" if length == 285: return 258 extra = (length - 257) / 4 - 1 length = length - 254 if extra > 0: ebits = bits.read(extra) length = 2**(extra+2) + 3 + (((length + 1) % 4) * (2**extra)) + e...
def calc_categ_accur(g_truth, predicts): """two lists must be same in size, one for ground:truth and another for model predictions, we keep the function works over lists even if it is a many to one prediction, that is for reusability on many to many sequence models""" true_counter = 0 false_c...
def conv_if_neg(x): """Returns abs of x if it's negative""" if x < 0: return abs(x), True return x, False
def rectangles_intersect(r1, r2, shift1=(0, 0), shift2=(0, 0), extraSize=3): """ gets two 4-tuples of integers representing a rectangle in min, max coord-s optional params. @shifts can be used to move boxes on a larger canvas (2d plane) @extraSize, forces the rectangles ...
def bound(value, bound1, bound2): """ returns value if value is between bound1 and bound2 otherwise returns bound that is closer to value """ if bound1 > bound2: return min(max(value, bound2), bound1) else: return min(max(value, bound1), bound2)
def eps(i, d, N): """ Dispersion; the spacing between levels is d. This is used to compute the energy for the singly occupied levels. """ return d*(i - ((N-1)/2))
def Hubble_convert(H_0): """ Converts the Hubble parameter from km/s/Mpc to Myr^-1 Parameters ---------- H_0 : float The Hubble parameter in km/s/Mpc. Returns ------- result : float The Hubble parameter in Myr^-1. """ result = H_0*1000.0*3.1536*1...
def get_column(data, index=0): """Get a column from a dataset Parameters: data: Could be a list of list or a list of dict, etc Given a = [{"k1":1, "k2":5},{"k1":3, "k2":5},{"k1":2, "k2":5}] get_column(a, "k1") will get the values of k1 Returns: list: of values that be...
def genRunEntryStr(queryId, docId, rank, score, runId): """A simple function to generate one run entry. :param queryId: query id :param docId: document id :param rank: entry rank :param score: entry score :param runId: run id """ return f'{queryId} Q0 {docId} {rank} {score} {r...
def _one_or_both(a, b): """Returns f"{a}\n{b}" if a is truthy, else returns str(b). """ if not a: return str(b) return f"{a}\n{b}"
def add(num1: int,num2: int): """ Add 2 numbers and provide the result """ print("Good Day, World!") return num1+num2
def normalizeCUAddr(addr): """ Normalize a cuaddr string by lower()ing it if it's a mailto:, or removing trailing slash if it's a URL. @param addr: a cuaddr string to normalize @return: normalized string """ lower = addr.lower() if lower.startswith("mailto:"): addr = lower if...
def get_author_name(author_id, users, original=False): """get the name of the author from the includes Arguments: - author_id: the author_id - users: the users part of the includes - original: """ for user in users: if ('id' in user and 'username' in user) and ( ...
def edges_to_adj_list(edges): """ Transforms a set of edges in an adjacency list (represented as a dictiornary) For UNDIRECTED graphs, i.e. if v2 in adj_list[v1], then v1 in adj_list[v2] INPUT: - edges : a set or list of edges OUTPUT: - adj_list: a dictionary with the vertices as ...
def find_duplicate_number(array): """ We know that we will be given a series of numbers [0, n-2] with one extra number (the duplicate number) so if we take the total sum of series [0, n-2] (arithmetic series sum = n((a1 + an)/2) ) and extract it from actual sum of the array we we will get the extra numb...
def is_sorted(arr): """ Check if each comparison returns 1 (True) If any comparison is 0 (False), it should not pass. """ # Check if arr isn't None if arr: if all(arr[i] <= arr[i + 1] for i in range(len(arr) - 1)): return True return False
def position_shuffle(objs, saved=False): """ :param list objs: objects need to be ordered :param bool saved: True / False code sample:: position_shuffle( HomeBox.objects.all(), True) """ if objs: for index, obj in enumerate(objs): if obj.position != index: ...
def make_numbers_form_list(lis): """changes list to number""" num = "" i = 0 while i < len(lis): num += str(lis[i]) i += 1 return int(num)
def getFibonacciRecursive(n: int) -> int: """ Calculate the fibonacci number at position n recursively """ a = 0 b = 1 def step(n: int) -> int: nonlocal a, b if n <= 0: return a a, b = b, a + b return step(n - 1) return step(n)