content
stringlengths
42
6.51k
def get_aspects(labels): """ Get aspect expressions from a label sequence Parameters ---------- labels: ATE labels (list). Returns ------- List of aspect expression """ aspects = [] curr_aspect = [] prev_label = '' for i in range(len(labels)...
def add_it_up(num1: int, num2: int) -> int: """Example callable. Delete this function if copy/pasting this module for use as a template. """ if not isinstance(num1, int): raise TypeError('num1 must be an int') if not isinstance(num2, int): raise TypeError('num2 must be an int') ...
def sanitize_string(output): """Removes unwanted characters from output string.""" return output.replace("\t", " ")
def _env_to_bool(val): """ Convert *val* to a bool if it's not a bool in the first place. """ if isinstance(val, bool): return val val = val.strip().lower() if val in ("1", "true", "yes", "on"): return True return False
def _caller_name_and_arg(frame): """Extract information about name and arguments of a function call from a *frame* object""" if frame is None: return None, None caller_name = frame.f_code.co_name caller_varnames = frame.f_code.co_varnames caller_arg = None if len(caller_varnames) > 0: ...
def range2d(n, m): """ Returns a list of values in a 2d range Arguments: n: The number of rows in the 2d range m: The number of columns in the 2d range Returns: A list of values in a 2d range """ return [(i, j) for i in range(n) for j in range(m)]
def parse_USEARCH_cigar(cigar, seq_len): """Parses usearch specific cigar and return appropriate tuple output USEARCH uses an alternative output format option in which I and D are interchanged 0123456 MDINSHP """ DECODE = 'MDINSHP' _ENCODE = dict( (c,i) for (i, c) in enume...
def make_html(info, tag='h3'): """write infos in simple html tag, return string""" html = '' for key, value in info.items(): line = f"<{tag}>{key} : {value}</{tag}>\n" html += line return html
def seq_strip(seq, stripper=lambda x: x.strip()): """ Strip a sequence of strings. """ if isinstance(seq, list): return map(stripper, seq) if isinstance(seq, tuple): return tuple(map(stripper, seq)) raise ValueError("%s of unsupported sequencetype %s" % (seq, type(seq)))
def _spec_attachment(name_or_type): """ Returns a query item matching messages that have attachments with a certain name or file type. Args: name_or_type (str): The specific name of file type to match. Returns: The query string. """ return f"filename:{name_or_type}"
def expand_qgrams_word_list(wlist, qsize, output, sep='~'): """Expands a list of words into a list of q-grams. It uses `sep` to join words :param wlist: List of words computed by :py:func:`microtc.textmodel.get_word_list`. :type wlist: list :param qsize: q-gram size of words :type qsize: int :p...
def update_line(line): """ Takes a string line representing a single line of code and returns a string with print updated """ # Strip left white space using built-in string method lstrip() # If line is print statement, use the format() method to add insert parentheses # Note that solutio...
def additionner_deux_nombres(premier_nombre, second_nombre): """ Additionne deux nombres inputs: Deux nombres outputs: Un nombre """ total = premier_nombre + second_nombre return total
def solution(X, A): """ For this task, we simply need to record where the leaves have fallen. As soon as we have a bridge, we cross. """ # initialise variables to keep track of the leaves leaves = [False] * X leaves_count = 0 for idx, val in enumerate(A): # leaf has fallen on ...
def bspline_cython(p, j, x): """Return the value at x in [0,1[ of the B-spline with integer nodes of degree p with support starting at j. Implemented recursively using the de Boor's recursion formula""" assert (x >= 0.0) & (x <= 1.0) assert (type(p) == int) & (type(j) == int) ...
def filter_words(words, skip_words): """This function takes a list of words and returns a copy of the list from which all words provided in the list skip_words have been removed. For example: >>> filter_words(["help", "me", "please"], ["me", "please"]) ['help'] >>> filter_words(["go", "south"]...
def row_check_conflict(row1, row2): """Returns False if row1 and row2 have any conflicts. A conflict is where one position in a row is True while the other is False.""" assert len(row1) == len(row2) for i, v1 in enumerate(row1): v2 = row2[i] # The solution can't conflict if either r...
def parse_int(text: str) -> int: """ Small postprocessing task to parse a string to an int. """ return int(text.strip())
def color_RGB_to_xy(R, G, B): """Convert from RGB color to XY color.""" if R + G + B == 0: return 0, 0 var_R = (R / 255.) var_G = (G / 255.) var_B = (B / 255.) if var_R > 0.04045: var_R = ((var_R + 0.055) / 1.055) ** 2.4 else: var_R /= 12.92 if var_G > 0.04045:...
def efficientnet_params(model_name): """Get efficientnet params based on model name.""" params_dict = { # (width_coefficient, depth_coefficient, resolution, dropout_rate) 'efficientnet-b0': (1.0, 1.0, 224, 0.2), 'efficientnet-b1': (1.0, 1.1, 240, 0.2), 'efficientnet-b2': (1.1, 1....
def verify_newimage(filename, files): """ Checks existence of filename Args: filename: Image name ID: Username Returns: x: Boolean value. If x is true, image does not exist in database """ x = True cursor = files if cursor == []: x = True els...
def validate_team(all_boards, calender, team, glob=False): """ Helper function to validate if a team should be synced or not. :param Dict all_boards: All boards :param Dict calender: Calender created for the team :param String team: Team name :param Bool glob: Are we checking for the global boa...
def unescape(s): """ replace Tumblr's escaped characters with ones that make sense for saving in an HTML file """ if s is None: return "" # html entities s = s.replace("&#13;", "\r") # standard html s = s.replace("&lt;", "<") s = s.replace("&gt;", ">") s = s.replace("&amp;", "...
def to_bool(s: str) -> bool: """Return bool converted from string. bool() from the standard library convert all non-empty strings to True. """ return s.lower() in ['true', 't', 'y', 'yes'] if s is not None else False
def flatten_dict(d, parent_key=''): """ Return array of flattened dict keys """ keys = [] for k in d: combined_key = k if parent_key: combined_key = "{}.{}".format(parent_key, k) if type(d[k]) == dict: keys.extend(flatten_dict(d[k], parent_key=combin...
def _sort_orders(orders): """Sort a list of possible orders that are to be tried so that the simplest ones are at the beginning. """ def weight(p, d, q, P, D, Q): """Assigns a weight to a given model order which accroding to which orders are sorted. It is only a simple heuristic that mak...
def is_stopword(morpheme, trie): """ Returns the presence or absence of stopword in stopword dictionary. - input : morpheme string, trie instance - output : boolean (Ture, False) """ if morpheme in trie: return True return False
def trianglePoints(x, z, h, w): """ Takes the geometric parameters of the triangle and returns the position of the 3 points of the triagles. Format : [[x1, y1, z1], [x2, y2, z2], [x3, y3, z3]] """ P1 = [x, 0, z+h] P2 = [x, w/2, z] P3 = [x, -w/2, z] return [P1, P2, P3]
def simple_square_brackets(s, fmt_spec): """ Surrounds the string with [ ] characters. Useful when verifying string truncation i.e. when checking the UI these characters should be visible. :param s: String to surround :param fmt_spec: Regex for placeholders. :returns: String surrounded with [ ...
def lremove(s, prefix): """Remove prefix from string s""" return s[len(prefix):] if s.startswith(prefix) else s
def hex_to_long(hex_string: str): """Convert hex to long.""" return int(hex_string, 16)
def taputil_find_header(headers, key): """Searches for the specified keyword Parameters ---------- headers : HTTP(s) headers object, mandatory HTTP(s) response headers key : str, mandatory header key to be searched for Returns ------- The requested header value or None ...
def powerOfN(x=2,n=3): """this function is completely useless, it just calculates x^n)""" y = x**n return y
def selection_sort_dec(array): """ it looks for largest value for each pass, after completing the pass, it places it in the proper position it has O(n2) time complexity larger numbers are sorted first """ for i in range(len(array)): # print(array) large = i for j in range(i+1,len(array)): if array[lar...
def _get_app_domain(project_id): """ Return String App Engine Domain to send data to """ app_domain = "https://{project_id}.appspot.com".format(project_id=project_id) return app_domain
def chunks(list_, num_items): """break list_ into n-sized chunks...""" results = [] for i in range(0, len(list_), num_items): results.append(list_[i:i+num_items]) return results
def insertion_sort(my_list): """ Performs an insertion sort. Args: my_list: a list to be sorted. Returns: A sorted list Raises: TypeError: There are mixed types in the list which are not orderable """ for location in range(1, len(my_list)): # Skip the first item -...
def get_capability(capabilities, capability_name): """Search a set of capabilities for a specific one.""" for capability in capabilities: if capability["interface"] == capability_name: return capability return None
def find_all(srcstr, substr): """ to find all desired substring in the source string and return their starting indices as a list Args: srcstr(str): the parent string substr(str): substr Returns: list: a list of the indices of the substrings found """ ...
def pairT_impairF(x): """renvoit Vrai si pair Faux si impair""" assert type(x) is int if x%2 == 0 : return True else : return False
def _get_browser(buildername): """Gets the browser type to be used in the run benchmark command.""" if 'android' in buildername: return 'android-chromium' # pragma: no cover elif 'x64' in buildername: return 'release_x64' # pragma: no cover return 'release'
def get_train_test_modifiers(modifier=None): """Append the modifier to 'train' and 'test'""" modifier_train = 'train' modifier_test = 'test' if modifier is not None: modifier_train = modifier_train + '_' + modifier modifier_test = modifier_test + '_' + modifier return modifier_train,...
def extract_history_ztf(alert: dict, key: str) -> list: """Extract data field from alert candidate and previous linked alerts. Parameters ---------- candidate: dict Correspond to the key "candidate" in the alert dictionary. previous: list of dicts Correspond to the key "prv_candidat...
def len_eq(value, other): """Length Equal""" return len(value) == other
def fibonacci(number): """Calculate Fibonacci numbers fib_n The Fibonacci numbers are 1, 2, 3, 5 ,8, 12, 21, ... fib_n = fib_n-1 + fib_n-2 """ if number < 2: return 1 return fibonacci(number-1) + fibonacci(number-2)
def to_red(string): """ Converts a string to bright red color (16bit) Returns: str: the string in bright red color """ return f"\u001b[31;1m{string}\u001b[0m"
def line_width( segs ): """ Return the screen column width of one line of a text layout structure. This function ignores any existing shift applied to the line, represended by an (amount, None) tuple at the start of the line. """ sc = 0 seglist = segs if segs and len(segs[0])==2 and segs[0][1]==None: seglist...
def get_hourly_rate(target_count, cycle_minutes): """Get hourly rate of emails sent.""" cycle_hours = cycle_minutes / 60 return target_count / cycle_hours
def rounddown_20(x): """ Project: 'ICOS Carbon Portal' Created: Tue May 07 09:00:00 2019 Last Changed: Tue May 07 09:00:00 2019 Version: 1.0.0 Author(s): Karolina Description: Function that takes a number as input and ...
def optional(flag=True): """When this flag is True, an exception should be issued if the related keyword/element is defined and the constraint fails. If the keyword/element is not defined or `flag` is False, the constraint should be ignored. Returns "O" or False >>> optional(True) 'O' >>>...
def singularize(name): """ This is a total hack that will only work with ESP resources. Don't use this for anything else. """ n = str(name) if n[-1:] == 's': return n[:-1] return n
def is_number(s): """ Determine if a string is a number :param s: :return: """ try: float(s) return True except ValueError: pass return False
def parse_vid(proto_vid): """Turn rm0 into RM000 etc""" letters = proto_vid[:2].upper() numbers = proto_vid[2:] numbers = "0" * (3 - len(numbers)) + numbers return letters + numbers
def part2(input): """ >>> part2([199, 200, 208, 210, 200, 207, 240, 269, 260, 263]) 5 """ window = lambda i, list : list[i] + list[i+1] + list[i+2] return sum(1 if window(i, input) < window(i+1, input) else 0 for i in range(len(input)-3))
def split_compound(compound): """Split a possibly compound format string into segments. >>> split_compound('bold_underline_bright_blue_on_red') ['bold', 'underline', 'bright_blue', 'on_red'] """ merged_segs = [] # These occur only as prefixes, so they can always be merged: mergeable_prefix...
def compare_versions(old_version, new_version): """ Compare specified version and return True if new version is strictly greater than old one Args: old_version (string): old version new_version (string): new version Returns: bool: True if new version available """ #che...
def get_tenant_headers(webhook_api_key: str) -> dict: """Return HTTP headers required for tenant lob webhook call.""" headers = {"accept": "application/json", "Content-Type": "application/json"} if webhook_api_key: headers["X-API-Key"] = webhook_api_key return headers
def removeAdjacentsInArray(contourArray): """ removeAdjacentsInArray. remove adjacents in array :param contourArray: (Array) all contours :returns noAdjacentsArray: (Array) adjacents removed and with last array value """ noAdjacentsArray = [] if(len(contourArray)> 0): #r = [...
def _LookupKind(kinds, spec, scope): """Tries to find which Kind a spec refers to, given the scope in which its referenced. Starts checking from the narrowest scope to most general. For example, given a struct field like Foo.Bar x; Foo.Bar could refer to the type 'Bar' in the 'Foo' namespace, or an inner ...
def helper_parse_UniProt_dump_other_functions(list_of_string): """ e.g. input [['EMBL; AY548484; AAT09660.1; -; Genomic_DNA.'], ['RefSeq; YP_031579.1; NC_005946.1.'], ['ProteinModelPortal; Q6GZX4; -.'], ['SwissPalm; Q6GZX4; -.'], ['GeneID; 2947773; -.'], ['KEGG; vg:2947773; -.'], ...
def factorial2(num): """ return factorial without recursion :param num: the number :return: factorial """ product = 1 for n in range(2, num + 1): product *= n return product
def reverse_boolean(boolean): """Invert boolean.""" if boolean == True: return False else: return True
def ret_class(beta, p, pthre=0.05): """ tp = 0 : prediction 1, real 1 fp = 1 : prediction 1 ,real 0 fn = 2 : prediction 0 , real 1 tn = 3 : prediction 0, real 0 """ pred = 1 if p < pthre else 0 real = 1 if beta != 0 else 0 if pred == 1 and real == 1: return 0 elif pred ==...
def reformat_text(text: str) -> str: """Replace shadowverse-portal's formatting markup with markdown.""" return ( text.replace("<br>", "\n") .replace("[/b][b]", "") .replace("[b]", "**") .replace("[/b]", "**") )
def display_list(l): """Returns a comma-punctuated string for the input list with a trailing ('Oxford') comma.""" length = len(l) if length <= 2: return " and ".join(l) else: # oxford comma return ", ".join(l[:-1]) + ", and " + l[-1]
def is_function(s: str) -> bool: """Checks if the given string is a function name. Parameters: s: string to check. Returns: ``True`` if the given string is a function name, ``False`` otherwise. """ return 'f' <= s[0] <= 't' and s.isalnum()
def gnomad_link(variant_obj, build=37): """Compose link to gnomAD website.""" if build == 38: url_template = ( "http://gnomad.broadinstitute.org/variant/{this[chromosome]}-" "{this[position]}-{this[reference]}-{this[alternative]}?dataset=gnomad_r3" ) else: ur...
def byte_literal(b): """ If b is already a byte literal, return it. Otherwise, b is an integer which should be converted to a byte literal. This function is for compatibility with Python 2.6 and 3.x """ if isinstance(b, int): return bytes([b]) else: return b
def getAttributes(tag): """Convert non-nested key/vals in dict into dict on their own """ return dict([(k,v) for k,v in tag.items() if type(v) == type("") and '__' not in k ])
def questionize_label(word): """Convert a word to a true/false style question format. If a user follows the convention of using `is_something`, or `has_something`, for a boolean value, the *property* text will automatically be converted into a more human-readable format, e.g. 'Something?' for is_ a...
def IsIntString(string): """ Return whether the supplied string contains pure integer data. """ try: intVal = int(string) except ValueError: return False strip = string.strip().lstrip("0") return len(strip) == 0 or str(intVal) == strip
def join_tkn_func(x: tuple, idx1: int, idx2: int): """ idx1: token(0) or lemma token(1) idx2: pos(2) or tag(3) - pos: coarse-grained tags, https://universaldependencies.org/docs/u/pos/ - tag: fine-grained part-of-speech tags """ return f"{x[idx1]}__{x[idx2]}"
def tokenize(list_nd: list) -> list: """Tokenize a list. :param list_nd: :return: """ if not list_nd: return [] if isinstance(list_nd, list): return ['('] + [tokenize(s) for s in list_nd] + [')'] return list_nd
def compute_middle(low: float, high: float): """"Returns the middle point of the interval [low, high].""" return low + (high - low) / 2
def make_profit(actions): """Calculate profit""" total_profit = 0 for action in actions: action_profit = action[2] total_profit += action_profit return total_profit
def sigfig(number, places): """ Round `number` to `places` significant digits. Parameters: number (int or float): A number to round. places (int): The number of places to round to. Returns: A number """ # Passing a negative int to round() gives us a sigfig determinatio...
def ish(s): """based on func reverse""" def reverse(m): if len(m) == 0: return '' return reverse(m[1:]) + m[0] return reverse(s) == s
def filter_positive_even_numbers(numbers): """Receives a list of numbers, and returns a filtered list of only the numbers that are both positive and even (divisible by 2), try to use a list comprehension.""" return [i for i in numbers if (int(i) % 2 == 0 and int(i)>0)]
def un_div(text): """Remove wrapping <div...>text</div> leaving just text.""" if text.strip().startswith("<div ") and text.strip().endswith("</div>"): text = text.strip()[:-6] text = text[text.index(">") + 1:].strip() return text
def tuples_to_geojson(bounds): """ Given bounding box in tuple format, returns GeoJSON polygon Input bounds: (lat(y) min, lat(y) max, long(x) min, long(x) max) """ lat_min = bounds[0] lat_max = bounds[1] long_min = bounds[2] long_max = bounds[3] bounding_box = {} bounding_box["...
def identify_block_children(block: dict) -> list: """Extract the blocks IDs of the given block's children. Presumably, order matters here, and the order needs to be maintained through text concatenation to get the full key text. """ child_ids = [] if "Relationships" in block.keys(): c...
def matches_only(entry, only) -> bool: """Return True if all variables are matched""" ret = False for val in only: if val["key"] in entry and entry[val["key"]] == val["value"]: ret = True else: ret = False break return ret
def create_loss_map(model_config: dict) -> dict: """ Creates a dictionary mapping loss names to loss functions. Args: model_config: The configuration dictionary. Returns: A dictionary mapping loss names to emtpy lists. """ losses = {'loss': []} if model_config['single_chann...
def uniquify(seq, idfun=None): """ Order-preserving uniquify of a list. Lifted directly from http://www.peterbe.com/plog/uniqifiers-benchmark """ if idfun is None: idfun = lambda x: x seen = {} result = [] for item in seq: marker = idfun(item) if marker in seen...
def djb2(key): """ Classic hashing function by Bernstein. This algorithm (k=33) was first reported by dan bernstein many years ago in comp.lang.c. """ hash = 5381 for letter in str(key): hash = ((hash << 5) + hash) + ord(letter) return hash
def getMonthNumber(month): """ Change the months from string to int. """ months = { "Jan":1, "Feb":2, "Mar":3, "Apr":4, "May":5, "Jun":6, "Jul":7, "Aug":8, "Sep":9, "Oct":10, "Nov":11, "Dec":12 } retu...
def denormalized_age(age): """ :param age: age in range [-1, 1] :return: age in range [0, 240] (months) """ return (age + 1) * 120
def norm_spaces(s): """Normalize spaces, splits on all kinds of whitespace and rejoins""" return s # return " ".join((x for x in re.split(r"\s+", s) if x))
def __highlight_function__(feature): """ Function to define the layer highlight style """ return {"fillColor": "#ffaf00", "color": "green", "weight": 3, "dashArray": "1, 1"}
def exception_to_message(ex): """Get the message from an exception.""" return ex.args[0]
def isNumber(string): """ check if a string can be converted to a number """ try: number = float(string) return True except: return False
def cheating_matrix(seating_chart): """ Calculate and return the probabilities of cheating for each position in a rxc grid :param seating_chart: A nested list representing a rxc grid :return: A nested list, the same size as seating_chart, with each element representing that position's cheati...
def ispowerof2(num): """ Is this number a power of 2?""" # see http://code.activestate.com/recipes/577514-chek-if-a-number-is-a-power-of-two/ return (num & (num-1) == 0)
def _plus(left: str, right: str) -> str: """Convenience function Takes two string representations of regular expressions, where the empty string is considered as matching the empty langage, and returns a string representation of their sum. """ if len(left) > 0 and len(right) > 0: return...
def normalize(value): """ Simple method to always have the same kind of value """ if value and isinstance(value, bytes): value = value.decode('utf-8') return value
def _find_all_meta_group_vars(ncvars, meta_group_name): """ Return a list of all variables which are in a given meta_group. """ return [k for k, v in ncvars.items() if 'meta_group' in v.ncattrs() and v.meta_group == meta_group_name]
def _retrieve_links(link_data): """Auxiliary function to collect data on links. Returns list of lists in the form of [linkname, link]. """ out = [] for l in link_data: try: out.append([l['@ref'], l.get('@href')]) except KeyError: continue return out or No...
def _remove_titles(text, ignore): """ Old Implementation This function just removes wrappers tags in the beginning of the XML text. Parameters: text - The XML text as string. ignore - List of tag to remove (ignore). This list has to be of only wrappers tags and in the order they appear in the XML text. ...
def spherical_index_k(degree: int, order: int = 0) -> int: """returns the mode `k` from the degree `degree` and order `order` Args: degree (int): Degree of the spherical harmonics order (int): Order of the spherical harmonics Raises: ValueError: if `order < -degree` or `order > deg...
def format_text(text): """Formata o texto relativo ao nome das promotorias. Arguments: text {string} -- Texto a ser formatado. Returns: string -- Texto formatado. """ return ' '.join( [ t.capitalize() if len(t) > 3 or t == "rio" else t for t in text....