content
stringlengths
42
6.51k
def lag_to_suffix(lag: int) -> str: """ Return the suffix for a column, given its lag. """ if lag < 0: str_lag = "f" + str(abs(lag)) else: str_lag = "l" + str(abs(lag)) return str_lag
def set2bytes(s, delimiter=b'\x00', encoding='utf-8'): """Serialize a set of unicode strings into bytes. >>> set2byte({u'a', u'b', u'c') b'a\x00b\x00c' """ list_ = [] for uword in sorted(s): bword = uword.encode(encoding) list_.append(bword) return delimiter.join(list_)
def set_dict_value(context, dt, key_name): """Sets value in the context object equal to the dictionary dt[key_name]""" context['value'] = dt[key_name] return ''
def combine(operator, operands): """ There is odoo.osv.expression.combine function. But it crop expressions on TRUE and FALSE domains. """ return [operator] * (len(operands) - 1) + operands
def access_author(author): """ Access function for author field. """ try: return author[0]['family'] except: pass
def normalize_func(get_iter): """ normalize_func :param get_iter: :return: """ # new iterator total = sum(get_iter()) result = [] # new iterator for value in get_iter(): percent = 100 * value / total result.append(percent) return result
def celsius_to_fahrenheit(celsius): """ convert celsius to fahrenheit """ fahrenheit = (celsius * (9.0/5.0)) + 32.0 return fahrenheit
def set_flag(bits, bit, value): """ Sets the flag value. :param bits: The bits :type bits: int :param bit: The bit index :type bit: int :param value: The bit value :type value: bool :returns: The bits :rtype: int """ mask = 1 << bit return bits | mask if value else bits & ~mask
def format_num(x, ndecimals=2, plus_sym=False): """Return a nicely formatted number in .f or .e format.""" fmt = '%.' + str(ndecimals) if abs(x) < 10**(-ndecimals): fmt = fmt + 'e' else: fmt = fmt + 'f' if plus_sym and x > 0: fmt = '+' + fmt return fmt % x
def roundplus(number): """ given an number, this fuction rounds the number as the following examples: 87 -> 87, 100 -> 100+, 188 -> 100+, 999 -> 900+, 1001 -> 1000+, ...etc """ num = str(number) if not num.isdigit(): return num num = str(number) digits = len(num) rounded = '100+' if digits < 3: rounded = num elif digits == 3: rounded = num[0]+'00+' elif digits == 4: rounded = num[0]+'K+' elif digits == 5: rounded = num[:1]+'K+' else: rounded = '100K+' return rounded
def some(seq): """ Return some element of seq that is true. """ for e in seq: if e: return e return False
def to_latlon(coords): """Flip coordinates from (lon, lat) to (lat, lon)""" return (coords[1], coords[0])
def cummin(x): """A python implementation of the cummin function in R""" for i in range(1, len(x)): if x[i-1] < x[i]: x[i] = x[i-1] return x
def create_rst(items): """Create rst from items""" table = '' if items: for item in items: table += item.rst() return table
def get_dot(dic, key, default=None): """ Similar to dict.get(), but key is given with dot (eg. foo.bar) and result is evaluated in generous way. That is, get_dot(dic, 'foo.bar.vaz') will return dic['foo']['bar'] if both dic['foo'] and dic['foo']['baz'] exists, but return default if any of them does not exists. """ keys = key.split('.') res = dic for k in keys: if not isinstance(res, dict): return default elif k in res: res = res[k] else: return default return res
def is_nlloc_hyp(filename): """ Checks that a file is actually a NonLinLoc Hypocenter-Phase file. """ try: with open(filename, 'rb') as fh: temp = fh.read(6) except Exception: return False if temp != b'NLLOC ': return False return True
def kth_root_int(n, k): """Return the k-th root of the given integer n, rounded down to the nearest integer. """ u = n s = n + 1 while u < s: s = u t = (k - 1) * s + n // pow(s, k - 1) u = t // k return s
def list_to_str(l, dl='_', quote=False): """Convert a list to string for the given delimeter.""" if quote: r = dl.join(["'"+str(i).lower()+"'" for i in l if i is not None and str(i).strip()]) else: r = dl.join([str(i).lower() for i in l if i is not None and str(i).strip()]) return r
def policy_name(policy_index): """Returns the name of the policy associated to policy_index""" if policy_index == -1: name = "neural network" elif policy_index == 0: name = "infotaxis" elif policy_index == 1: name = "space-aware infotaxis" elif policy_index == 2: name = "custom policy" elif policy_index == 5: name = "random walk" elif policy_index == 6: name = "greedy" elif policy_index == 7: name = "mean distance" elif policy_index == 8: name = "voting" elif policy_index == 9: name = "most likely state" else: raise Exception("The policy " + str(policy_index) + " does not exist (yet)!") return name
def make_query_string(query, params): """ Substitute parameters into the query :param query: input query with params :param params: values used to substitute :return: """ query_string = query index = 1 for param in params: if param: to_replace = "%%param%d%%" % index query_string = query_string.replace(to_replace, param) index += 1 return query_string
def _get_resource_group_name_by_resource_id(resource_id): """Returns the resource group name from parsing the resource id. :param str resource_id: The resource id """ resource_id = resource_id.lower() resource_group_keyword = '/resourcegroups/' return resource_id[resource_id.index(resource_group_keyword) + len( resource_group_keyword): resource_id.index('/providers/')]
def p_length_unit(units): """Returns length units string as expected by pagoda weights and measures module.""" # NB: other length units are supported by resqml if units.lower() in ['m', 'metre', 'metres']: return 'metres' if units.lower() in ['ft', 'foot', 'feet', 'ft[us]']: return 'feet' assert(False)
def bottom_up_staircase_problem(n): """ Parameters ---------- n : int number of steps Returns ------- int number of ways a child can run a stairs >>> bottom_up_staircase_problem(4) 7 >>> bottom_up_staircase_problem(0) 1 """ cache = [0 for _ in range(n + 1)] cache[0] = 1 strides = [1, 2, 3] i = 1 while i <= n: for stride in strides: if stride <= i: cache[i] += cache[i - stride] i += 1 return cache[n]
def hex2rgb(str_rgb): """A function that takes hex values and converts them to rgb""" #https://github.com/vaab/colour/blob/master/colour.py try: rgb = str_rgb[1:] if len(rgb) == 6: r, g, b = rgb[0:2], rgb[2:4], rgb[4:6] elif len(rgb) == 3: r, g, b = rgb[0] * 2, rgb[1] * 2, rgb[2] * 2 else: raise ValueError() except: raise ValueError("Invalid value %r provided for rgb color."% str_rgb) return tuple(int(v, 16) for v in (r, g, b))
def binary_search(element, array, start, end): """ Search element within array using binary search (if the element is found return index otherwise -1) :param element: :param array: :param start: :param end: :return: """ if start <= end: middle = int((start + end) / 2) if array[middle] == element: return middle else: if element < array[middle]: return binary_search(element, array, start, middle - 1) else: return binary_search(element, array, middle + 1, end) else: return -1
def get_device_profile_group_requester_id(dp_group_id): """Return the value to use in objects.RequestGroup.requester_id. The requester_id is used to match device profile groups from Cyborg to the request groups in request spec. :param dp_group_id: The index of the request group in the device profile. """ req_id = "device_profile_" + str(dp_group_id) return req_id
def override_class(overriden_class, overrider_class): """Override class definition with a MixIn class If overriden_class is not a subclass of overrider_class then it creates a new class that has as bases overrider_class and overriden_class. """ if not issubclass(overriden_class, overrider_class): name = overriden_class.__name__ bases = (overrider_class, overriden_class) overriden_class = type(name, bases, {}) return overriden_class
def get_and_transform(dict: dict, key: str, fn, default=None): """Get a value from a dictionary and transform it or return None if the key isn't present""" try: value = dict[key] if value is None: return value else: return fn(value) except KeyError: return default
def Main(a: int, b: int) -> int: """ :param a: :param b: :return: """ j = 0 return b
def welcome(name="Ale"): """Example function with PEP 484 type annotations. Args: name: The first parameter. Returns: The return a message. """ if name is None: return {"message": "Welcome to API Star!"} return {"message": "Welcome to API Star, %s!" % name}
def issubdict(d1, d2): """All keys in `d1` are in `d2`, and corresponding values are equal.""" return all((k in d2 and d1[k] == d2[k]) for k in d1)
def isPowerOfThree(n): """ :type n: int :rtype: bool """ return n > 0 and 3**19 % n==0
def should_retry_http_code(status_code): """ :param status_code: (int) http status code to check for retry eligibility :return: (bool) whether or not responses with the status_code should be retried """ return status_code not in range(200, 500)
def deep_get(dictionary, keys, default=None): """ a safe get function for multi level dictionary """ if dictionary is None: return default if not keys: return dictionary return deep_get(dictionary.get(keys[0]), keys[1:])
def isiterable(obj): """Return True if obj is an iterable, False otherwise.""" try: _ = iter(obj) # noqa F841 except TypeError: return False else: return True
def remove_key_dict(mydict, keys): """Return new dict sem as keys""" new_dict = dict() for key in mydict: if key not in keys: new_dict[key] = mydict[key] return new_dict
def delta_t(soil_type): """ Displacement at Tu """ delta_ts = { "dense sand": 0.003, "loose sand": 0.005, "stiff clay": 0.008, "soft clay": 0.01, } return delta_ts.get(soil_type, ValueError("Unknown soil type."))
def worst_range(A, target): """ Given a sorted list, find the range A[lo:hi] such that all values in the range equal to target. """ if not target in A: return None lo = A.index(target) if lo == len(A)-1: return (lo, lo) hi = lo + 1 while hi < len(A): if A[hi] != target: return (lo, hi-1) hi += 1 return (lo, hi-1)
def format_list(to_format): """pleasing output for dc name and node count""" if not to_format: return "N/A" return "{ %s }" % ", ".join(to_format)
def escape(text): """ Returns the given text with ampersands, quotes and angle brackets encoded for use in HTML. This function always escapes its input, even if it's already escaped and marked as such. This may result in double-escaping. If this is a concern, use conditional_escape() instead. """ return text.replace('&', '&amp;'). \ replace('<', '&lt;'). \ replace('>', '&gt;').replace('"', '&quot;'). \ replace("'", '&#39;')
def find_all_indexes(text, pattern): """Return a list of starting indexes of all occurrences of pattern in text, or an empty list if not found.""" assert isinstance(text, str), 'text is not a string: {}'.format(text) assert isinstance(pattern, str), 'pattern is not a string: {}'.format(text) indexes = [] # keep track of all starting indexes text_index = 0 # if pattern empty, append indexes for length of text if pattern == "": for i in range(len(text)): indexes.append(i) # as long as there are still letters to look thru... while text_index != len(text): for i in range(len(pattern)): if text_index + i < len(text): # check letter from text again letter from pattern if text[text_index + i] != pattern[i]: break # stop if no match if i == len(pattern) - 1: # return index where pattern starts indexes.append(text_index) text_index += 1 # move on to next letter in text return indexes
def dot_v3(v, w): """Return the dotproduct of two vectors.""" return sum([x * y for x, y in zip(v, w)])
def enwidget(a, b): """ Provide some values for the L{element} template. """ return {"a": a, "b": b}
def is_placeholder(x): """Returns whether `x` is a placeholder. # Arguments x: A candidate placeholder. # Returns Boolean. """ return getattr(x, '_is_placeholder', False)
def quick_sort(A, start = None, end = None): """ Sorts elements of a list in ascending order """ start = 0 if start == None else start end = len(A) if end == None else end def partition(A, start, end): """ Puts an element(last element) of a list in place (its ordered) position """ pivot = A[end - 1] pIndex = start for i in range(start, end): if A[i] <= pivot: temp = A[i] A[i] = A[pIndex] A[pIndex] = temp pIndex += 1 return pIndex if (start >= end): return partitionIndex = partition(A, start, end) quick_sort(A, start, partitionIndex - 1) quick_sort(A, partitionIndex, end) return A
def same_text(s1, s2): """True if both strings are the same, ignoring case.""" # note, unicodedata.normalize is a good idea to get this to work all the time, # but this is only used here to compare against our simple directive names return s1.casefold() == s2.casefold()
def clamp(n, minn, maxn): """Make sure n is between minn and maxn Args: n (number): Number to clamp minn (number): minimum number allowed maxn (number): maximum number allowed """ return max(min(maxn, n), minn)
def format_metrics(d: dict) -> dict: """ Format the floats in a dict with nested dicts, for display. :param d: dict containing floats to format :return: new dict matching the original, except with formatted floats """ new = {} for key in d: if isinstance(d[key], dict): new[key] = format_metrics(d[key]) elif isinstance(d[key], float): new[key] = float("{:.8f}".format(d[key])) else: new[key] = d[key] return new
def is_sequence(arg): """ Checks to see if something is a sequence (list) Parameters ---------- arg : str The string to be examined. Returns ------- sequence : bool Is True if `arg` is a list. """ sequence = (not hasattr(arg, "strip") and hasattr(arg, "__getitem__") or hasattr(arg, "__iter__")) return sequence
def intersect(list1, list2): """ Compute the intersection of two sorted lists. Returns a new sorted list containing only elements that are in both list1 and list2. This function can be iterative. """ idx1 = 0 idx2 = 0 ans = [] while ((idx1 <= len(list1) - 1) and (idx2 <= len(list2) - 1)): if list1[idx1] < list2[idx2]: idx1 += 1 elif list1[idx1] > list2[idx2]: idx2 += 1 else: ans.append(list1[idx1]) idx1 += 1 idx2 += 1 return ans
def decode_utf8(raw): """ Returns a Unicode object on success, or None on failure """ try: return raw.decode('utf-8-sig', errors='replace') except BaseException: return None
def is_unsupported_size_mechanism_type(size_mechanism: str) -> bool: """Whether the given size mechanism is unknown/unsupported.""" return size_mechanism not in { "fixed", "len", "len-in-bytes", "ivi-dance", "passed-in", "passed-in-by-ptr", "ivi-dance-with-a-twist", "two-dimension", "custom-code", }
def write_output(final, invcf): """ Make tsv format output file. """ with open('{}'.format(invcf.replace('.vcf', '.tsv')), 'w') as wt_fianl: wt_fianl.write(final) return True
def fetchImage(code): """ Returns file path to logo of league as string Parameters: ----------- code : str The ID of the league for which fixtures are required Returns: -------- str Contains file path if valid code is supplied, else 'None' """ if code in ['PL', 'FL1', 'BL', 'SPA', 'SA']: return f"source/logos/{code}.jpg" else: return None
def generate_bigrams(x): """Docstring """ n_grams = set(zip(*[x[i:] for i in range(2)])) for n_gram in n_grams: x.append(' '.join(n_gram)) return x
def get_view_content_info(view): """ Determines if the view has an empty center, and looks for 2d chromosome grids. Args: view(dict): The view to analyze. Returns: A dictionary with these keys: has_top_tracks(bool) : True if the view has top side tracks has_left_tracks(bool) : True if the view has left side tracks has_center_content(bool) : True if there is any content in the center tracks. center_chromsize_index(int) : If there is a 2d chromosome grid in the center, get the index in the list to find it. """ view_has_left_tracks = len(view["tracks"].get("left", [])) > 0 view_has_top_tracks = len(view["tracks"].get("top", [])) > 0 # See if there is any center content (including chromsize grids) view_has_any_center_content = len(view["tracks"].get("center", [])) > 0 \ and len(view["tracks"]["center"][0].get("contents", [])) > 0 # See if there is any non-chromosome grid content. view_has_center_content = view_has_any_center_content and \ any([t for t in view["tracks"]["center"][0]["contents"] if "type" != "2d-chromosome-grid"]) # Determine the index of the chromosome grid (we assume there is only 1) view_center_chromsize_indecies = [] if view_has_any_center_content: view_center_chromsize_indecies = [i for i, t in enumerate(view["tracks"]["center"][0]["contents"]) if "type" == "2d-chromosome-grid"] view_center_chromsize_index = None if len(view_center_chromsize_indecies) > 0: view_center_chromsize_index = view_center_chromsize_indecies[0] return { "has_top_tracks" : view_has_top_tracks, "has_left_tracks" : view_has_left_tracks, "has_center_content" : view_has_center_content, "center_chromsize_index" : view_center_chromsize_index, }
def escape(keyword): """ Escape the backtick for keyword when generating an actual SQL. """ return keyword.replace('`', '``')
def topic_render(topic, num_words, vocabulary): """ Convert a topic result to a list of words :param topic: topic data, first element is list of length num_words, which contains indices which are used to extract words from vocabulary to form the list that is returned :type topic: tuple(list(int), list(float)) :param num_words: number of words, equal to "topic_words" specified in query configuration file :type num_words: int :param vocabulary: vocabulary :type vocabulary: list(unicode) :return: list of num_words words from vocabulary :rtype: list(unicode) """ indices = topic[0] terms = [] for i in range(num_words): term = vocabulary[indices[i]] terms.append(term) return terms
def process_precisions(precisions): """ Processes precisions to ensure that precision and recall don't both get worse. Assumes the list precision is sorted in order of recalls """ precision_best = precisions[::-1] for i in range(1, len(precision_best)): precision_best[i] = max(precision_best[i - 1], precision_best[i]) precisions = precision_best[::-1] return precisions
def get_available_executors(config): """ Returns list of all executors available in the config file """ return list(config['executors'])
def things_by(by_what, things): """Convert list of dictionaries to dictionary of dictionaries. Positional arguments: things -- a list of dictionaries by_what -- key that must exist in all dictionaries in things. The value of this key is used as the key in the returned dictionary and so should be unique. """ things_by = {} for thing in things: things_by[thing[by_what]] = thing return things_by
def transform_array(array, f): """Args; 2D array e.g. [[2,2],[2,2]], f = function e.g lambda x: x*2 return [[4,4], [4,4]]""" height = len(array) width = len(array[0]) for col in range(width): for row in range(height): val = array[row][col] array[row][col] = f(val) return array
def istag(line): """ :param str line: Input line to check :retrun: True if input line is a tag, i.e. starts with `@@`; otherwise returns False. :rtype: bool """ return line.startswith('@@') and len(line) > 2
def get_file_extension(url): """Return file extension""" file_extension = ''.join(('.', url.split('.')[-1:][0])) return file_extension
def get_big_binomial(n, k, fdict): """returns the natural log of the binomial coefficent n choose k""" if n > 0 and k > 0: nFact = fdict[n] kFact = fdict[k] nkFact = fdict[n - k] return nFact - kFact - nkFact else: return 0
def binary_search(a, x): """Locate the value exactly equal to x""" low, high = 0, len(a) - 1 while low <= high: mid = (low + high) // 2 if a[mid] > x: high = mid - 1 elif a[mid] < x: low = mid + 1 else: return mid return -1
def get_content_table ( name_table: str = None, keysvalues: dict = None ) -> str : """Retorna sql 'GetContentTable'""" sql = "SELECT * FROM" sql += " " + f"`{name_table}`" if keysvalues: keysvaluesDictStr = factory.keysvaluesToDictStr ( keysvalues = keysvalues, sep = " AND " ) sql += " " + "WHERE" sql += " " + f"{keysvaluesDictStr}" return sql
def extract_sha256_hash(hash): """Extrach SHA256 hash or return None """ prefix = 'sha256:' if hash and hash.startswith(prefix): return hash.replace(prefix, '') return None
def getValue (segment, tagName): """ get an xml element text value """ try: value = segment.find(tagName).text.strip() except: value = '' else: if len(value) == 0: value = '' return value
def watson_crick(x_nt, y_nt, alphabet=None): """ fun assigns 1 if input string is in alphabet, otherwise it returns 0. parameters: x_nt = nucleotide on x axis y_nt = nucleotide on y axis alphabet = dict of nt_pair:score """ if not alphabet: alphabet = {"AT": 1.0, "TA": 1.0, "GC": 1.0, "CG": 1.0} pair = x_nt + y_nt return alphabet.get(pair, 0)
def is_even(i: int) -> bool: """ :param i: An integer :return: Whether that number is even """ return i % 2 == 0
def find_standard_output_styles(labels): """ Function to find some standardised colours for the outputs we'll typically be reporting on - here only incidence and prevalence, but can easily be extended to accommodate more. Args: labels: List containing strings for the outputs that colours are needed for. Returns: yaxis_label: Unit of measurement for outcome title: Title for subplot """ yaxis_label = {} title = {} if 'incidence' in labels: yaxis_label['incidence'] = 'Per 100,000 per year' title['incidence'] = 'Incidence' if 'prevalence' in labels: yaxis_label['prevalence'] = 'Per 100,000' title['prevalence'] = 'Prevalence' return yaxis_label, title
def int_or_none(value): """ Try to make `value` an int. If the string is not a number, or empty, return None. """ try: return int(value) except ValueError: return None
def NW(N, tp='U'): """function to compute number of edges or number of feasible vertex-pair Args: N (int): number of nodes tp (str, optional): Can be either 'U' for undirected and 'D' for directed graphs. Defaults to 'U'. Returns: int: number of edges or number of feasible vertex-pair between N nodes """ assert tp=='U' or tp=='D', "Invalid type in NW, it shall be either 'U' or 'D'" if tp=='U': return N*(N-1)//2 else: return N*(N-1)
def _parse_request(section): """ This function takes a CTCP-tagged section of a message and breaks it in to a two-part tuple in the form of ``(command, parameters)`` where ``command`` is a string and ``parameters`` is a tuple. """ sections = section.split(" ") if len(sections) > 1: command, params = (sections[0], tuple(sections[1:])) else: command, params = (sections[0], tuple()) return command, params
def check(grad_honests, f_real, defense, factor=-16, negative=False, **kwargs): """ Check parameter validity for this attack template. Args: grad_honests Non-empty list of honest gradients f_real Number of Byzantine gradients to generate defense Aggregation rule in use to defeat ... Ignored keyword-arguments Returns: Whether the given parameters are valid for this attack """ if not isinstance(grad_honests, list) or len(grad_honests) == 0: return "Expected a non-empty list of honest gradients, got %r" % (grad_honests,) if not isinstance(f_real, int) or f_real < 0: return "Expected a non-negative number of Byzantine gradients to generate, got %r" % (f_real,) if not callable(defense): return "Expected a callable for the aggregation rule, got %r" % (defense,) if not ((isinstance(factor, float) and factor > 0) or (isinstance(factor, int) and factor != 0)): return "Expected a positive number or a negative integer for the attack factor, got %r" % (factor,) if not isinstance(negative, bool): return "Expected a boolean for optional parameter 'negative', got %r" % (negative,)
def is_df( df): """is_df Test if ``df`` is a valid ``pandas.DataFrame`` :param df: ``pandas.DataFrame`` """ return ( hasattr(df, 'to_json'))
def classify_triangle(a, b, c): """ Method that Classifies the triangle based on the sides given """ intersection = {a, b, c} & {a, b, c} is_right_triangle = a ** 2 + b ** 2 == c ** 2 triangle_class = 'Invalid Triangle' if a <= 0 or b <= 0 or c <= 0: return triangle_class if is_right_triangle: triangle_classification = 'Right Angle Triangle' elif len(intersection) == 1: triangle_classification = 'Equilateral Triangle' elif len(intersection) == 2: triangle_classification = 'Isosceles Triangle' else: triangle_classification = 'Scalene Triangle' return triangle_classification
def all_same(seq): """ Determines whether all the elements in a sequence are the same. seq: list """ # Compare all the elements to the first in the sequence, # then do a logical and (min) to see if they all matched. return min([elem == seq[0] for elem in seq]+[True])
def build_response(session_attributes, speech_response): """Build the full response JSON from the speech response.""" return { 'version': '1.0', 'sessionAttributes': session_attributes, 'response': speech_response }
def escapeXml(obj): """ Performs XML escape processing, replacing <, >, and & with their XML entities. """ return str(obj).replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
def node_neighbours(v, edges): """Returns a list of neighbours of vertex v""" return (v, [e[1] for e in edges if e[0] == v])
def dcinputs(DCNominal=110): """Enter the substation nominal voltage eg DCNominal = 48 Return the required setting for the MiCOM Px4x platform output is a dictionary with the suggested setting """ result = 'Not Valid' if DCNominal >= 220: result = '220/250V' elif DCNominal >= 110: result = '110/125V' elif DCNominal >= 48: result ='48/54V' elif DCNominal >= 30: result = '30/34V' elif DCNominal >= 24: result = '24/27V' else: result = 'Check' return {'Global Nominal DC':result}
def load_cands(path): """Load global fixed set of candidate labels that the teacher provides every example (the true labels for a specific example are also added to this set, so that it's possible to get the right answer). """ if path is None: return None cands = [] lines_have_ids = False cands_are_replies = False cnt = 0 with open(path) as read: for line in read: line = line.strip().replace('\\n', '\n') if len(line) > 0: cnt = cnt + 1 # If lines are numbered we strip them of numbers. if cnt == 1 and line[0:2] == '1 ': lines_have_ids = True # If tabs then the label_candidates are all the replies. if '\t' in line and not cands_are_replies: cands_are_replies = True cands = [] if lines_have_ids: space_idx = line.find(' ') line = line[space_idx + 1:] if cands_are_replies: sp = line.split('\t') if len(sp) > 1 and sp[1] != '': cands.append(sp[1]) else: cands.append(line) else: cands.append(line) return cands
def mergeTwoLists(l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ if not l1: return l2 if not l2: return l1 start = None if l1.val < l2.val: start = l1; start.next = mergeTwoLists(l1.next, l2) else: start = l2; start.next = mergeTwoLists(l1, l2.next) return start
def TweetValid(tweet, CharNumber=140): """ Function to check if a string "tweet" is valid, i.e., the #char is equal or less than CharNumber. CharNumber can be 140 at maximum. :type tweet: str :type CharNumber: int :rtype: boolean """ if CharNumber > 140: CharNumber = 140 return len(tweet) <= CharNumber
def isPointInBox(p, b): """ category: General Utility Functions Return whether a given point is within a given box. For use with standard def boxes (position|rotate|scale). """ return ((abs(p[0]-b[0]) <= b[6]*0.5) and (abs(p[1]-b[1]) <= b[7]*0.5) and (abs(p[2]-b[2]) <= b[8]*0.5))
def _remove_nesting(ref): """Remove the outer layer of nesting if ref is a nested reference. Return the original reference if it's not nested""" return (ref['reference'] if isinstance(ref, dict) and 'reference' in ref else ref)
def reynolds_number(v: float, d_hyd: float, kin_visco: float) -> float: """ Calculate Reynolds number. **Parameters:** - `v`: (*float*) = flow velocity [m/s] - `d_hyd`: (*float*) = hydraulic diameter [m] - `kin_visco`: (*float*) = kinematic viscosity [m^2/s] **Returns:** (*float*) """ return v * d_hyd / kin_visco
def nop(inputs): """ This function does nothing but may be useful for debugging """ print(list(inputs)) return []
def largest_priority(dictionary): """Template filter to return the largest priority +1""" if dictionary: keys = [int(k) for k in dictionary if k] if keys: return max(keys) + 1 return 1
def remove_duplicates_from_list(params_list): """ Common function to remove duplicates from a list Author: Chaitanya-vella.kumar@broadcom.com :param params_list: :return: """ if params_list: return list(dict.fromkeys(params_list)) return list()
def mp_wrap_fn(args): """ Wrapper for multi-processing functions with more than one argument. :type args: tuple :param args: the function name and its arguments """ function_to_call = args[0] args = args[1:] return function_to_call(*args)
def add_certificate_subject(subject, spec): """ Utility method to build a subject data structure along k8s Certificate resources. This method supports addition of Organization (O), OrganizationalUnits (OU), Country (C) and State/Province (ST). :param subject: a dictionary with keys respective to the subject fields mentioned above. :param spec: a dicitionary specifying the Certificate.spec that is going to be used on the resource creation. """ certificate_subject = {} # the template we're using to build Certificate resource doesn't # accept fields with None or empty values. We just add fields below # if they are specified by the user, otherwise we simply ignore them. if subject.get('O'): spec['organization'] = [subject.get('O')] if subject.get('CN'): spec['commonName'] = subject.get('CN') if subject.get('OU'): certificate_subject['organizationalUnits'] = [subject.get('OU')] if subject.get('C'): certificate_subject['countries'] = [subject.get('C')] if subject.get('ST'): certificate_subject['provinces'] = [subject.get('ST')] if subject.get('L'): certificate_subject['localities'] = [subject.get('L')] spec['subject'] = certificate_subject return spec
def charencode(string): """String.CharCode""" encoded = '' for char in string: encoded = encoded + "," + str(ord(char)) return encoded[1:]
def is_outlier(x, p25, p75): """Check if value is an outlier.""" lower = p25 - 1.5 * (p75 - p25) upper = p75 + 1.5 * (p75 - p25) return x <= lower or x >= upper
def asciibytes(data): """For Python 2/3 compatibility: If it is 'bytes' already, do nothing, otherwise convert to ASCII Bytes""" if isinstance(data, bytes): return data else: return data.encode('ASCII')
def list_to_string(the_list): """Converts list into one string.""" strings_of_list_items = [str(i) + ", " for i in the_list] the_string = "".join(strings_of_list_items) return the_string
def double_quote(txt: str) -> str: """Double quote strings safely for attributes. Usage: >>> double_quote('abc"xyz') '"abc\\"xyz"' """ return '"{}"'.format(txt.replace('"', '\\"'))
def is_true(value): """ Check wether value contains the string 'true' in a variety of capitalizations (e.g. "True" or "TRUE"). """ return value.lower() == 'true'