content
stringlengths
42
6.51k
def _DiscardUnusedTemplateLabelPrefixes(labels): """Drop any labels that end in '-?'. Args: labels: a list of label strings. Returns: A list of the same labels, but without any that end with '-?'. Those label prefixes in the new issue templates are intended to prompt the user to enter some label with that prefix, but if nothing is entered there, we do not store anything. """ return [lab for lab in labels if not lab.endswith('-?')]
def iobes2iob(iobes): """Converts a list of IOBES tags to IOB scheme.""" dico = {pfx: pfx for pfx in "IOB"} dico.update({"S": "B", "E": "I"}) return [dico[t[0]] + t[1:] if not t == "O" else "O" for t in iobes]
def doc_has_content(doc): """Check if doc has content""" len_title = len(doc['title'].split()) len_content = len(doc['content'].split()) # 50: mean_len_content - 2*mean_len_content*standard_deviation in v1 return len_content - len_title > 50
def matrix(user_item, item_users): """Cria a matrix user (linha) x itens (coluna)""" list_itens = [] #matriz_user_item = numpy.zeros( len( item_users)) matriz_user_item = [] index_itens = dict() cont=0 for item_user in item_users.keys(): index_itens[item_user] = cont cont+=1 print(f'Quantidade de usuarios: {len(user_item)}') for user, itens in user_item.items(): # O(n^2) - no caso de um usuario ter todos os itens, na maior parte dos caso O(n) line_matrix = [0] * len(item_users) for item_nota in itens : # item usuario line_matrix[ index_itens[ item_nota[0] ] ] = item_nota[1] # index item #matriz_user_item = numpy.append(line_matrix, matriz_user_item, axis=0) matriz_user_item.append(line_matrix) return matriz_user_item
def compute_TF_FP_FN_micro(label_dict): """ compute micro FP,FP,FN :param label_dict_accusation: a dict. {label:(TP, FP, FN)} :return:TP_micro,FP_micro,FN_micro """ TP_micro, FP_micro, FN_micro = 0.0, 0.0, 0.0 for label, tuplee in label_dict.items(): TP, FP, FN = tuplee TP_micro = TP_micro + TP FP_micro = FP_micro + FP FN_micro = FN_micro + FN return TP_micro, FP_micro, FN_micro
def modulo_expo(a, b, m): """ compute a^b mod m """ if b == 0: return 1 temp = modulo_expo(a, b >> 2, m) temp *= 2 if b & 1 > 0: temp *= a temp %= m return temp
def get_concordance_string(text, keyword, idx, window): """ For a given keyword (and its position in an article), return the concordance of words (before and after) using a window. :param text: text :type text: string :param keyword: keyword :type keyword: str or unicode :param idx: keyword index (position) in list of article's words :type idx: int :window: number of words to the right and left :type: int :return: concordance :rtype: list(str or unicode) """ text_list= text.split() text_size = len(text_list) if idx >= window: start_idx = idx - window else: start_idx = 0 if idx + window >= text_size: end_idx = text_size else: end_idx = idx + window + 1 concordance_words = '' flag_first = 1 for word in text_list[start_idx:end_idx]: if flag_first == 1: concordance_words += word flag_first = 0 else: concordance_words += ' ' + word return concordance_words
def invert_for_next(current): """ A helper function used to invert the orientation indicator of the next panel based on the current panel i.e. if a parent is horizontal a child panel must be vertical :param current: Current parent orientation :type current: str :return: child panel orientation :rtype: str """ if current == "h": return "v" else: return "h"
def hello(name: str) -> str: """ Say hello :param name: Who to say hello to :return: hello message """ return f"Hello {name}!"
def find_winner_line(line): """Return the winner of the line if one exists. Otherwise return None. A line is a row, a column or a diagonal. """ if len(line) != 3: raise ValueError('invalid line') symbols = set(line) if len(symbols) == 1: # All equal. return line[0] # Could be None. return None
def _upper_first(name): """Return name with first letter uppercased.""" if not name: return '' return name[0].upper() + name[1:]
def check_if_odd(num): """ Checks if number is odd Args: num : (Generated by docly) """ return True if num % 2 != 0 else False
def interval_to_milliseconds(interval): """Convert a Binance interval string to milliseconds :param interval: Binance interval string, e.g.: 1m, 3m, 5m, 15m, 30m, 1h, 2h, 4h, 6h, 8h, 12h, 1d, 3d, 1w :type interval: str :return: int value of interval in milliseconds None if interval prefix is not a decimal integer None if interval suffix is not one of m, h, d, w """ seconds_per_unit = { "m": 60, "h": 60 * 60, "d": 24 * 60 * 60, "w": 7 * 24 * 60 * 60, } try: return int(interval[:-1]) * seconds_per_unit[interval[-1]] * 1000 except (ValueError, KeyError): return None
def encode_str(s): """Returns the hexadecimal representation of ``s``""" return ''.join("%02x" % ord(n) for n in s)
def group_lines(lines): """Split a list of lines using empty lines as separators.""" groups = [] group = [] for line in lines: if line.strip() == "": groups.append(group[:]) group = [] continue group.append(line) if group: groups.append(group[:]) return groups
def distance_km(point1, point2): """ Convert from degrees to km - approximate." Args: point1: Array-like with 2 members (lat/long). point2: Array-like with 2 members (lat/long). Returns: float: distance in kilometres """ return ((point1[0] - point2[0]) ** 2 + (point1[1] - point2[1]) ** 2) ** 0.5 * 111
def json_filename(symbol): """Appends .json to the string SYMBOL""" return "stockJSON/" + symbol + ".json"
def is_power_of_two(number: int) -> bool: """Check if input is a power of 2. Parameters ---------- number: int Returns ------- bool """ return number != 0 and ((number & (number - 1)) == 0)
def incrementing_pattern(size: int) -> bytes: """ Return `size` bytes with a pattern of incrementing byte values. """ ret = bytearray(size) for i in range(0, size): ret[i] = i & 0xff return bytes(ret)
def num_segments(paths): """How many individual line segments are in these paths?""" return sum(len(p)-1 for p in paths)
def local_rank(worker_id): """ use a different account in each xdist worker """ if "gw" in worker_id: return int(worker_id.replace("gw", "")) elif "master" == worker_id: return 0 raise RuntimeError("Can not get rank from worker_id={}".format(worker_id))
def one_hot_encode(integer_encoding, num_classes): """ One hot encode. """ onehot_encoded = [0 for _ in range(num_classes)] onehot_encoded[integer_encoding] = 1 return onehot_encoded
def get_workflow_id(identifier: int) -> str: """Get a hexadecimal string of eight characters length for the given integer. Parameters ---------- identifier: int Workflow indentifier Returns ------- string """ return hex(identifier)[2:].zfill(8).upper()
def compile_continued_fraction_representation(seq): """ Compile an integer sequence (continued fraction representation) into its corresponding fraction. """ from fractions import Fraction # sanity check assert seq # initialize the value to be returned by working backwards from the last number retval = Fraction(1, seq.pop()) # keep going backwords till the start of the sequence while seq: retval = 1 / (seq.pop() + retval) return retval
def _validate_bool(value): """Return parameter value as boolean. :param str value: The raw parameter value. :param dict content: The template parameter definition. :returns: bool """ if value in [True, False]: return value try: if str(value).lower() == 'true': return True if str(value).lower() == 'false': return False raise TypeError("'{}' is not a valid bool".format(value)) except UnicodeEncodeError: raise TypeError("'{}' is not a valid bool".format(value))
def calculateHandlen(hand): """ Returns the length (number of letters) in the current hand. hand: dictionary (string-> int) returns: integer """ length =0 for letter in hand: length += hand[letter] return length
def partitionByFunc(origseq, partfunc): """Partitions a sequence into a number of sequences, based on the `partfunc`. Returns ``(allseqs, indices)``, where: - `allseqs` is a dictionary of output sequences, based on output values of `partfunc(el)`. - `indices` is a dictionary of ``(outval, i) -> orig_i``, which allows mapping results back. So if your `partfunc` returns 'foo' and 'bar', `allseqs` will have ``{'foo': [...], 'bar': [...]}``. You access `indices` using ``(partout, seq_i)``, where `partout` is 'foo' or 'bar' in this case, and `seq_i` is the index number from the ``allseqs[partout]`` sequence. This function is very useful for categorizing a list's entries based on some function. If your function was binary, you would normally do it using 2 list comprehensions:: a = [el for el in seq if partfunc(el)] b = [el for el in seq if not partfunc(el)] But that quickly gets inefficient and bloated if you have more complicated partition functions, which is where this function becomes useful. """ allseqs = {} indices = {} for i, el in enumerate(origseq): partout = partfunc(el) seq = allseqs.setdefault(partout, []) indices[(partout, len(seq))] = i seq.append(el) return allseqs, indices
def _stringify_time_unit(value: int, unit: str): """ Returns a string to represent a value and time unit, ensuring that it uses the right plural form of the unit. >>> _stringify_time_unit(1, "seconds") "1 second" >>> _stringify_time_unit(24, "hours") "24 hours" >>> _stringify_time_unit(0, "minutes") "less than a minute" """ if value == 1: return f"{value} {unit[:-1]}" elif value == 0: return f"less than a {unit[:-1]}" else: return f"{value} {unit}"
def inverse_mod(a, m): """Inverse of a mod m.""" if a < 0 or m <= a: a = a % m # From Ferguson and Schneier, roughly: c, d = a, m uc, vc, ud, vd = 1, 0, 0, 1 while c != 0: q, c, d = divmod(d, c) + (c,) uc, vc, ud, vd = ud - q * uc, vd - q * vc, uc, vc # At this point, d is the GCD, and ud*a+vd*m = d. # If d == 1, this means that ud is a inverse. assert d == 1 if ud > 0: return ud else: return ud + m
def process_predictions(lengths, target, raw_predicted): """ Removes padded positions from the predicted/observed values and calls inverse_transform if available. Args: lengths: Lengths of the entries in the dataset. target: Target feature instance. raw_predicted: Raw predicted/observed values. Returns: List of NumPy arrays: [(length, target_vals), ...]. """ predicted = [] for i, raw_pred in enumerate(raw_predicted): pred = raw_pred[:lengths[i], :] if hasattr(target, 'inverse_transform'): pred = target.inverse_transform(pred) predicted.append(pred) return predicted
def is_user_info_complete(user): """ Returns True if the user has provided all of the required registration info Args: user (django.contrib.auth.models.User): Returns: bool: True if the user has provided all of the required registration info """ return ( hasattr(user, "profile") and user.profile.is_complete and hasattr(user, "legal_address") and user.legal_address.is_complete )
def get_all_context_names(context_num): """Based on the nucleotide base context number, return a list of strings representing each context. Parameters ---------- context_num : int number representing the amount of nucleotide base context to use. Returns ------- a list of strings containing the names of the base contexts """ if context_num == 0: return ['None'] elif context_num == 1: return ['A', 'C', 'T', 'G'] elif context_num == 1.5: return ['C*pG', 'CpG*', 'TpC*', 'G*pA', 'A', 'C', 'T', 'G'] elif context_num == 2: dinucs = list(set( [d1+d2 for d1 in 'ACTG' for d2 in 'ACTG'] )) return dinucs elif context_num == 3: trinucs = list(set( [t1+t2+t3 for t1 in 'ACTG' for t2 in 'ACTG' for t3 in 'ACTG'] )) return trinucs
def pretty_concat(strings, single_suffix='', multi_suffix=''): """Concatenates things in a pretty way""" if len(strings) == 1: return strings[0] + single_suffix elif len(strings) == 2: return '{} and {}{}'.format(*strings, multi_suffix) else: return '{}, and {}{}'.format(', '.join(strings[:-1]), strings[-1], multi_suffix)
def getDim(scale,supercell): """ Helper function for to determine periodicity of a crystal, used in various functions inputs -------- scale (float): The ratio of final and initial network size supercell (int): The supercell size used to generate the new atomic network returns -------- motiif (str): The structural motiif of the crystal """ # Check for standard scaling motiif_dict = {1:'molecular',supercell:'chains',\ supercell**2:'layered', supercell**3:'conventional'} if scale in motiif_dict: return(motiif_dict[scale]) # If the structure is some intermediate, determine # which intermediate else: if scale < 1: motiif = 'shrunk molecular' elif scale < supercell: motiif = "mol-chain" elif scale < supercell**2: motiif = "chain-2D" elif scale < supercell**3: motiif = "2D-conv" else: motiif = 'Network size increased' return(motiif)
def remove_dups(lst): """ return a copy of lst with duplicates of elements eliminated. For example, for lst = [a, a, a, a, b, c, c, a, a, d, e, e, e, e], the returned list is [a, b, c, d, e]. """ s = sorted(lst) return [v for i, v in enumerate(s) if i == 0 or v != s[i-1]]
def bin2sint(data): """Convert a byte-string to a signed integer.""" number = 0 # convert binary bytes into digits arr = list() for byte in data: arr.append(byte) byteslen = len(data) # Now do the processing negative = False if arr[byteslen - 1] >= 128: negative = True for idx, byte in enumerate(arr): if negative: byte = byte ^ 0xFF number += byte * (256 ** idx) if negative: number = (number + 1) * -1 return number
def check_if_param_valid(params): """ Check if the parameters are valid. """ for i in params: if i == "filter_speech_first": if not type(params["filter_speech_first"]) == bool: raise ValueError("Invalid inputs! filter_speech_first should be either True or False!") elif i == "pad_onset": continue elif i == "pad_offset": continue else: for j in params[i]: if not j >= 0: raise ValueError( "Invalid inputs! All float parameters excpet pad_onset and pad_offset should be larger than 0!" ) if not (all(i <= 1 for i in params['onset']) and all(i <= 1 for i in params['offset'])): raise ValueError("Invalid inputs! The onset and offset thresholds should be in range [0, 1]!") return True
def expand_range(val): """Expands the Haskell-like range given as a parameter into Python's `range` object. The range must be finite. Args: val (str): a range to expand. Returns: range: resulting range. Raises: ValueError: if given an invalid Haskell-like range. >>> expand_range("[1..10]") range(1, 11) >>> expand_range("[1,3..10]") range(1, 11, 2) >>> expand_range("[5,4..1]") range(5, 0, -1) """ if not val.startswith("[") or not val.endswith("]"): raise ValueError("Invalid bracket placement") val = val[1:-1] spl = val.split("..") if len(spl) != 2 or not all(spl): raise ValueError("Invalid range") end = int(spl[1]) if "," in spl[0]: begin, bstep = map(int, spl[0].split(",")) step = bstep - begin else: begin = int(spl[0]) step = 1 if step == 0: raise ValueError("Zero step is not allowed") if step > 0: end += 1 else: end -= 1 return range(begin, end, step)
def _get_entity(response): """Returns the entity from an API response. """ path = response['next'].split('?')[0] return path.split('/')[3]
def conform_to_argspec(args,kwargs,argspec): """Attempts to take the arguments in arg and kwargs and return only those which can be used by the argspec given.""" regargs, varargs, varkwargs, defaults = argspec N = len(regargs) # shallow copy arguments newargs = list(args) newkwargs = kwargs.copy() # Fill up as many regarg slots from *args as we can if varargs is None: newargs = newargs[:N] else: pass # Fill up the rest from **kwargs for varname in regargs[len(newargs):]: try: newargs.append(newkwargs[varname]) del newkwargs[varname] except KeyError: # just leave the rest of the kwargs as they are and let Python raise an error later break # Handle remaining kwargs if varkwargs is None: newkwargs = {} else: pass return newargs, newkwargs
def get_page(data, page): """Get nth page of a data, with each page having 20 entries.""" begin = page * 20 end = page * 20 + 20 if begin >= len(data): return [] elif end >= len(data): return data[begin:] else: return data[begin:end]
def color_to_rgb(c): """Convert a 24 bit color to RGB triplets.""" return ((c >> 16) & 0xFF, (c >> 8) & 0xFF, c & 0xFF)
def determine_end_of_role(prev_prefix, prefix): """ determine whether the previous token was the last one of the role :param str prev_prefix: prefix of the previous BIO annotation :param str prefix: current prefix of BIO annotation :rtype: bool :return: True -> previous token was the last one, False -> either not in role or still in annotation """ add_role = False if prefix != 'I': # current BIO annotation is O and previous one is I if prev_prefix == 'I': add_role = True return add_role
def potential_snow_layer(ndsi, green, nir, tirs1): """Spectral test to determine potential snow Uses the 9.85C (283K) threshold defined in Zhu, Woodcock 2015 Parameters ---------- ndsi: ndarray green: ndarray nir: ndarray tirs1: ndarray Output ------ ndarray: boolean, True is potential snow """ return (ndsi > 0.15) & (tirs1 < 9.85) & (nir > 0.11) & (green > 0.1)
def factorial(n: int) -> int: """ Return the factorial of a number. :param n: Number to find the Factorial of. :return: Factorial of n. >>> import math >>> all(factorial(i) == math.factorial(i) for i in range(10)) True >>> factorial(-5) # doctest: +ELLIPSIS Traceback (most recent call last): ... ValueError: factorial() not defined for negative values """ if n < 0: raise ValueError("factorial() not defined for negative values") result = 1 for i in range(1, n + 1): result *= i return result
def check_if_advanced_options_should_be_enabled(advanced_fields) -> bool: """ Checks whether the advanced options box should be enabled by checking if any of the advanced options have existing values. :param advanced_fields: the field group """ return any(item is not None for item in advanced_fields)
def space_space_fix(text): """Replace "space-space" with "space". Args: text (str): The string to work with Returns: The text with the appropriate fix. """ space_space = ' ' space = ' ' while space_space in text: text = text.replace(space_space, space) return text
def triangle_area(base, height): """Returns the area of a triangle""" return base * height / 2
def call_and_return(callee, returnee): """ A helper function to wrap a side effect (callee) in an expression. @param callee: a 0-ary function @param returnee: a value @rtype: type of returnee """ callee() return returnee
def intersection(d1, d2): """Intersection of two dicts. Return data in the first dict for the keys existing in both dicts.""" ret = {} for k in d1: if k in d2: ret[k] = d1[k] return ret
def _convert_wmi_type_to_xsd_type(predicate_type_name): """ This converts a WMI type name to the equivalent XSD type, as a string. Later, the conversion to a 'real' XSD type is straightforward. The point of this conversion is that it does not need rdflib. WMI types: https://powershell.one/wmi/datatypes RDF types: https://rdflib.readthedocs.io/en/stable/rdf_terms.html """ wmi_type_to_xsd = { 'string': "survol_string", # rdflib.namespace.XSD.string 'boolean': 'survol_boolean', 'datetime': 'survol_dateTime', 'sint64': 'survol_integer', 'sint32': 'survol_integer', 'sint16': 'survol_integer', 'sint8': 'survol_integer', 'uint64': 'survol_integer', 'uint32': 'survol_integer', 'uint16': 'survol_integer', 'uint8': 'survol_integer', 'real64': 'survol_double', 'real32': 'survol_double', } try: return wmi_type_to_xsd[predicate_type_name.lower()] except KeyError: return None
def padVersionString(versString, tupleCount): """Normalize the format of a version string""" if versString is None: versString = '0' components = str(versString).split('.') if len(components) > tupleCount: components = components[0:tupleCount] else: while len(components) < tupleCount: components.append('0') return '.'.join(components)
def SplitScmUrl(url): """Given a repository, return a set containing the URL and the revision.""" url_split = url.split('@') scm_url = url_split[0] scm_rev = 'HEAD' if len(url_split) == 2: scm_rev = url_split[1] return (scm_url, scm_rev)
def _generate_action(action_name, commands): """Generate action in imagebuilder components.""" action = {"name": action_name, "action": "ExecuteBash", "inputs": {"commands": [commands]}} return action
def three_sum(a, s): """ Gets pairs of three whose sum is 0 Parameters: a : array s : sum to find equivalent to Returns: 1 : If triplets found 0 : if triplets not found """ a.sort() answer_set = [] for i in range(len(a) - 3): l = i+1 r = len(a) - 1 while r > l: if a[i] + a[r] + a[l] == s and a[r] > a[l] > a[i]: answer_set.append((a[i], a[r], a[l])) l += 1 elif a[i] + a[r] + a[l] < s: l += 1 else: r -= 1 if answer_set: # print(answer_set) return 1 return 0
def replace_key_with_read_id(x): """ now that data is grouped by read properly, let's replace the key with the read ID instead of file line number to make sure joins are correct. """ return x[1][0], x[1]
def rol(int_type, size, offset): """rol(int_type, size, offset) -> int Returns the value of int_type rotated left by (offset mod size) bits. """ mask = (1 << size) - 1 offset %= size left = (int_type << offset) & mask circular = (int_type & mask) >> (size - offset) return left | circular
def round_point(p, n): """round""" return (round(p[0], n), round(p[1], n))
def _filter_for_numa_threads(possible, wantthreads): """Filter to topologies which closest match to NUMA threads :param possible: list of nova.objects.VirtCPUTopology :param wantthreads: ideal number of threads Determine which topologies provide the closest match to the number of threads desired by the NUMA topology of the instance. The possible topologies may not have any entries which match the desired thread count. So this method will find the topologies which have the closest matching count. ie if wantthreads is 4 and the possible topologies has entries with 6, 3, 2 or 1 threads, it will return the topologies which have 3 threads, as this is the closest match not greater than 4. :returns: list of nova.objects.VirtCPUTopology """ # First figure out the largest available thread # count which is not greater than wantthreads mostthreads = 0 for topology in possible: if topology.threads > wantthreads: continue if topology.threads > mostthreads: mostthreads = topology.threads # Now restrict to just those topologies which # match the largest thread count bestthreads = [] for topology in possible: if topology.threads != mostthreads: continue bestthreads.append(topology) return bestthreads
def _until_dh(splited): """ Slice until double hyphen """ i = 0 for i, s in enumerate(splited): if s == "--": return splited[:i], i + 1 elif s.startswith("--"): return splited[:i], i return splited[:], i + 1
def set_authenticated(cookie_string, user_id, prefix='', rconn=None): """Sets cookie into redis, with user_id as value If successfull return True, if not return False.""" if rconn is None: return False if (not user_id) or (not cookie_string): return False cookiekey = prefix+cookie_string try: if rconn.exists(cookiekey): # already authenticated, delete it rconn.delete(cookiekey) # and return False, as this should not happen return False # set the cookie into the database rconn.rpush(cookiekey, str(user_id)) rconn.expire(cookiekey, 600) except: return False return True
def orth(string): """Returns a feature label as a string based on the capitalization and other orthographic characteristics of the string.""" if string.isdigit(): return 'DIGIT' elif string.isalnum(): if string.islower(): return 'LOWER' elif string.istitle(): return 'TITLE' elif string.isupper(): return 'UPPER' else: return 'MIXED' elif string.isspace(): return 'SPACE' else: return 'OTHER'
def transform_cnvtag(cnvtag): """ Rename some cnv tags for downstream processing. """ split_call = cnvtag.split("_") # exon9hyb_star5 and dup_star13 are unlikely to occur together with yet another sv. if cnvtag != "exon9hyb_star5": while "exon9hyb" in split_call and "star5" in split_call: split_call.remove("exon9hyb") split_call.remove("star5") if cnvtag != "dup_star13": while "dup" in split_call and "star13" in split_call: split_call.remove("dup") split_call.remove("star13") if split_call.count("dup") == len(split_call): return "cn" + str(len(split_call) + 2) if cnvtag == "dup_dup_exon9hyb_star13intron1": return "cn4" return "_".join(split_call)
def sort_project_list(in_list): """ Sort and clean up a list of projects. Removes duplicates and sorts alphabetically, case-insensitively. """ # replace spaces with underscores in_list_2 = [i.replace(" ", "_") for i in in_list] # remove duplicate values if we ignore case # http://stackoverflow.com/a/27531275/4276230 unique_projects_dict = {v.lower(): v for v in in_list_2}.values() unique_projects_list = list(unique_projects_dict) # lowercase lowercase_list = [i.lower() for i in unique_projects_list] # sort the list sorted_project_list = sorted(lowercase_list) return sorted_project_list
def try_composite(a, d, n, s): """check composite number for rabin-miller primality test""" if pow(a, d, n) == 1: return False for i in range(s): if pow(a, 2 ** i * d, n) == n - 1: return False """n is definitely composite""" return True
def _format_lineno(lineno): """Just convert the line number into a better form. """ if lineno is None: return "" return ":" + str(lineno)
def down(spiral: list, coordinates: dict) -> bool: """ Move spiral down :param coordinates: starting point :param spiral: NxN spiral 2D array :return: boolean 'done' """ done = True while coordinates['row'] < len(spiral): row = coordinates['row'] col = coordinates['col'] if row == len(spiral) - 1 and spiral[row][col] == 0: spiral[row][col] = 1 done = False break elif row + 2 <= len(spiral) - 1 and \ spiral[row + 2][col] == 0 and \ spiral[row + 1][col] == 0: spiral[row][col] = 1 coordinates['row'] += 1 done = False elif row + 1 == len(spiral) - 1 and \ spiral[row + 1][col] == 0: spiral[row][col] = 1 coordinates['row'] += 1 done = False else: break return done
def extract_file_type(file_location:str) -> str: """ A function to return the type of file -> file_location: str = location of a file in string... ex : "C:\\abc\\abc\\file.xyz" ---- => str: string of the file type, ex : "xyz" """ if not isinstance(file_location,str): raise TypeError("file_location must be a string") try: return file_location.rsplit(".", 1)[1] except IndexError: raise ValueError(f"Invalid File Location : '{file_location}'")
def row_column_translation(row,col): """Converts a coordinate made by a letter/number couple in the index usable with the array that represents the board""" row = int(row) - 1 if row % 2 != 0: cols = range(ord("a"),ord("a")+7,2) else: cols = range(ord("b"),ord("b")+7,2) if ord(col) not in cols: return -1,-1 else: return row,cols.index(ord(col))
def teacher_input(random_numbers): """ Defines the contents of `teacher-input.txt` to which `run.sh` concatenates the student submission as the exercise is posted to MOOC Grader for grading. Generates 3 random numbers and forms a string containing the MathCheck configuration for this exercise. """ return \ u"arithmetic\n" + \ u"f_nodes 3\n" + \ u"{}/3^({}) + {}\n".format(random_numbers[0],random_numbers[1],random_numbers[2],)
def _sort_by_amount(transactions: list) -> list: """ Sort transactions by amount of dollars. """ sorted_transactions = sorted(transactions, key=lambda transaction: transaction["amount"], reverse=True) return sorted_transactions
def coding_problem_21(times): """ Given an array of time intervals (start, end) for classroom lectures (possibly overlapping), find the minimum number of rooms required. Example: >>> coding_problem_21([(30, 75), (0, 50), (60, 150)]) 2 """ start_times = [(t[0], 1) for t in times] # [(30, 1), (0, 1), (60, 1)] end_times = [(t[1], -1) for t in times] # [(75, -1), (50, -1), (150, -1)] room_allocation = [t[1] for t in sorted(start_times + end_times, key=lambda t: t[0])] # [1, 1, -1, 1, -1, -1] rooms, max_rooms = 0, 0 for event in room_allocation: rooms += event # occupied or released max_rooms = max(max_rooms, rooms) assert(rooms == 0) return max_rooms
def parse_unsigned_int(data: bytes, bitlen: int): """Parses an unsigned integer from data that is `bitlen` bits long.""" val = '0b' + ''.join([f'{b:08b}' for b in data]) return int(val[0:2 + bitlen], 2)
def get_schema_short_name(element): """The schema short name reveals is a stand-in for the platform that this element is for and can be derived from the namespace URI @type element: Element @param element: the XML Element @rtype: string @return: the "short name" of the platform schema or None if it could not be determined """ if element is None: return None tag = element.tag if not tag or tag is None: return None # If the oval ID does not contain a namespace, then we can't determine the schema shortname if not '}' in tag: return 'unknown' try: schema = tag.rsplit('}', 1)[0] if not '#' in schema: return "independent" return schema.rsplit('#', 1)[1].strip() except Exception: return None
def parse_xff(header_value): """ Parses out the X-Forwarded-For request header. This handles the bug that blows up when multiple IP addresses are specified in the header. The docs state that the header contains "The originating IP address", but in reality it contains a list of all the intermediate addresses. The first item is the original client, and then any intermediate proxy IPs. We want the original. Returns the first IP in the list, else None. """ try: return header_value.split(',')[0].strip() except (KeyError, AttributeError): return None
def to_devport(pipe, port): """ Convert a (pipe, port) combination into a 9-bit (devport) number NOTE: For now this is a Tofino-specific method """ return pipe << 7 | port
def get_extension(_str): """ Get ".ext" (extension) of string "_str". Args: _str (str) Returns: ext (str) extension of _str Example: | >> get_extension("random_plot.png") | ".png" """ _str = str(_str).rsplit("/", 1)[-1] ext = "."+_str.rsplit(".", 1)[-1] return ext
def global_line_editor(gle=None): """Access the global lineeditor instance. Args: gle: (optional) new global lineeditor instance Returns: Current global lineeditor instance """ global _gle_data if gle is not None: _gle_data = gle return _gle_data
def set_version(ver: str): """ Set the version of the API. This function should really only be used in bot.py. """ global version version = ver return version
def check_ends(astring): """string -> bool Write a function check_ends (astring), which takes in a string astring and returns True if the first character in astring is the same as the last character in astring. It returns False otherwise. The check_ends function does not have to work on the empty string (the string "") >>> check_ends('no match') False >>> check_ends('hah! a match') True """ return astring[0] == astring[-1]
def join_keywords(l): """ join a list of keywords with '+' for BingSearch """ return u'+'.join(l)
def strip_prefix(string, prefix): """Returns a copy of the string from which the multi-character prefix has been stripped. Use strip_prefix() instead of lstrip() to remove a substring (instead of individual characters) from the beginning of a string, if the substring is present. lstrip() does not match substrings but rather treats a substring argument as a set of characters. :param str string: The string from which to strip the specified prefix. :param str prefix: The substring to strip from the left of string, if present. :return: The string with prefix stripped from the left, if present. :rtype: string """ if string.startswith(prefix): return string[len(prefix):] else: return string
def to_pilot_alpha(word): """Returns a list of pilot alpha codes corresponding to the input word >>> to_pilot_alpha('Smrz') ['Sierra', 'Mike', 'Romeo', 'Zulu'] """ pilot_alpha = ['Alfa', 'Bravo', 'Charlie', 'Delta', 'Echo', 'Foxtrot', 'Golf', 'Hotel', 'India', 'Juliett', 'Kilo', 'Lima', 'Mike', 'November', 'Oscar', 'Papa', 'Quebec', 'Romeo', 'Sierra', 'Tango', 'Uniform', 'Victor', 'Whiskey', 'Xray', 'Yankee', 'Zulu'] pilot_alpha_list = [] word = word.upper() for c in word: index = ord(c) - 65 pilot_alpha_list.append(pilot_alpha[index]) return pilot_alpha_list
def normalize_attribute(attr): """ Normalizes the name of an attribute which is spelled in slightly different ways in paizo HTMLs """ attr = attr.strip() if attr.endswith(':'): attr = attr[:-1] # Remove trailing ':' if any if attr == 'Prerequisites': attr = 'Prerequisite' # Normalize if attr == 'Note': attr = 'Prerequisite' # Normalize a very special case (Versatile Channeler) if attr == 'Benefits': attr = 'Benefit' # Normalize if attr == 'Leadership Modifiers': attr = 'Benefit' # Normalize a very special case (Leadership) assert attr in ('Prerequisite', 'Benefit', 'Normal', 'Special') return attr.lower()
def meters_to_feet(meters: float) -> float: """ This function takes a float representing a measurement in meters and returns the corresponding value converted to feet. The result is rounded to 2 decimal places. :param meters: A float representing a measurement in meters. :return: A float representing the input measurement converted to feet. """ return round(meters*3.28084,2)
def B3V_eq(x): """ :param x: abcsisse du point de la ligne B3V dont on veut obtenir l'ordonnee :return: ordonnee du point de la ligne B3V correspondant a l'abscisse x (dans un graphique u-g vs g-r) """ return 0.9909 * x - 0.8901
def get_locale_parts(locale): """Split a locale into three parts, for langauge, script, and region.""" parts = locale.split('_') if len(parts) == 1: return (parts[0], None, None) elif len(parts) == 2: if len(parts[1]) == 4: # parts[1] is a script return (parts[0], parts[1], None) else: return (parts[0], None, parts[1]) else: assert len(parts) == 3 return tuple(parts)
def Re_reflux(w_liq_real_enter_reflux, rho_reflux, d_enter_reflux_real, mu_reflux): """ Calculates the Re criterion . Parameters ---------- w_liq_real_enter_reflux : float The real speed of liquid at the tube, [m/s] rho_reflux : float The density of reflux, [kg/m**3] d_enter_reflux_real : float The real tube's diameter, [m] mu_reflux : float The viscosity of Reflux, [Pa * s] Returns ------- Re_reflux : float The Re criterion, [dimensionless] References ---------- ????? """ return w_liq_real_enter_reflux * rho_reflux * d_enter_reflux_real / mu_reflux
def list_product(combination): """ Calculates the product of all elements from the list. Remark: deprecated, use geometric mean instead. """ score = 1 for tanimoto in combination: score = score * tanimoto return(score)
def get_or_none(l, n): """Get value or return 'None'""" try: return l[n] except (TypeError, IndexError): return 'None'
def count_matches(array1, array2, admissible_proximity=40): """Finds the matches between two count process. Returns ------- tuple of lists (M, U, M) where M is the list of indices of array2 where matched with array 1 happened and U contains a list of indices of array2 where no match with array1 happened. """ # In time samples m, n = len(array1), len(array2) i, j = 0, 0 count = 0 matched_idx = [] unmatched_idx = [] while i < m and j < n: if abs(array1[i] - array2[j]) < admissible_proximity: matched_idx.append(j) i += 1 j += 1 count += 1 elif array1[i] < array2[j]: i += 1 else: unmatched_idx.append(j) j += 1 return matched_idx, unmatched_idx
def make_damage_list(find_list, damage): """make damage list from result, make damage date to list Args find_list (list): score data, as raw data Returns ret (boolean): damage found or not found """ ret = False temp_list = [] list_num = len(find_list) # from result, delete same position for i in range(list_num): if find_list[i][0] != 0: if not temp_list: temp_list = find_list[i] ret = True if find_list[i][0] > temp_list[0] + 5: # different position damage.append(str(temp_list[1])) temp_list = find_list[i] else: # difference 5 pixels to classify as the same position if find_list[i][2] > temp_list[2]: # better match damage found, update value temp_list = find_list[i] if ret is True: damage.append(str(temp_list[1])) return ret
def _allowed_char(char: str) -> bool: """Return true if the character is part of a valid policy ID.""" return char.isalnum() or char in {' ', '-', '.'}
def compute_iou(box_1, box_2): """ This function takes a pair of bounding boxes and returns intersection-over- union (IoU) of two bounding boxes. """ tl_row_1, tl_col_1, br_row_1, br_col_1 = box_1 tl_row_2, tl_col_2, br_row_2, br_col_2 = box_2 assert tl_row_1 < br_row_1 assert tl_col_1 < br_col_1 assert tl_row_2 < br_row_2 assert tl_col_2 < br_col_2 # Compute area of each respective box area_1 = (br_row_1 - tl_row_1) * (br_col_1 - tl_col_1) area_2 = (br_row_2 - tl_row_2) * (br_col_2 - tl_col_2) # Compute area of intersection tl_row_i = max(tl_row_1, tl_row_2) tl_col_i = max(tl_col_1, tl_col_2) br_row_i = min(br_row_1, br_row_2) br_col_i = min(br_col_1, br_col_2) if (br_row_i < tl_row_i) or (br_col_i < tl_col_i): intersection_area = 0 else: intersection_area = (br_row_i - tl_row_i) * (br_col_i - tl_col_i) # Compute area of union union_area = area_1 + area_2 - intersection_area iou = intersection_area / union_area assert (iou >= 0) and (iou <= 1.0) return iou
def links_as_text(code): """ ersetzt alle Vorkommen von '<a href="xxxxxxxx" ... >yyyy</a>' durch '(xxxxxxxx : yyyy)' """ def link_as_text(code): ret = code i = code.rfind('<a href="') if i>-1: j = code.find('"', i+9) k = code.find('>', j) l = code.find('<', k) ret = code[:i] + '(' + code[i+9:j] + ' : ' + code[k+1:l] + ')' + code[l+4:] return i, ret i=1 ret = code while i>-1: i, ret = link_as_text(ret) return ret
def s2t(x): """ Convert 'sigmoid' encoding (aka range [0, 1]) to 'tanh' encoding """ return x * 2 - 1
def get_predictions_without_annotations_query(label: str): """ Expects a label. Returns query dict for images with predictions but not annotations for this label. Additionally filters images out if they are already marked as "in_progress". !!! Only works for binary classification !!! """ return { "$match": { f"labels.predictions.{label}": {"$exists": True}, f"labels.annotation.{label}": {"$exists": False}, } }
def wpm(typed, elapsed): """Return the words-per-minute (WPM) of the TYPED string. Arguments: typed: an entered string elapsed: an amount of time in seconds >>> wpm('hello friend hello buddy hello', 15) 24.0 >>> wpm('0123456789',60) 2.0 """ assert elapsed > 0, 'Elapsed time must be positive' # BEGIN PROBLEM 4 "*** YOUR CODE HERE ***" return len(typed) / 5 / elapsed * 60 # END PROBLEM 4
def _clean_up_git_link(git_link: str) -> str: """Clean up git link, delete .git extension, make https url.""" if "@" in git_link: git_link.replace(":", "/").replace("git@", "https://") if git_link.endswith(".git"): git_link = git_link[:-4] return git_link
def exclude_bracket(enabled, filter_type, language_list, language): """ Exclude or include brackets based on filter lists. """ exclude = True if enabled: # Black list languages if filter_type == 'blacklist': exclude = False if language != None: for item in language_list: if language == item.lower(): exclude = True break #White list languages elif filter_type == 'whitelist': if language != None: for item in language_list: if language == item.lower(): exclude = False break return exclude