content
stringlengths
42
6.51k
def remove_model_class_name_field(fields): """ When reconstituting the models, they dont know how to deal with this extra field we added. We need to get rid of it. """ del fields['model_class_name'] return fields
def xor(bytearray_0, bytearray_1): """Exclusive ORs (XOR) the values of two bytearrays. Parameters ---------- bytearray_0 : bytearray bytearray_1 : bytearray Returns ------- output : bytearray XOR value of two bytearrays """ length = min(len(bytearray_0), len(bytearray_1)) output = bytearray(length) for i in range(length): output[i] = bytearray_0[i] ^ bytearray_1[i] return output
def case_insensitive(x): """creating a function for interchanging key and value""" return x.lower()
def semver(major_component, minor_component, patch_component): """Construct an SemVer-format version number. Args: major_component (int): The major component of the version number. minor_component (int): The minor component of the version number. patch_component (int): The patch component of the version number. Returns: str: A SemVer-format version number with the specified Major, Minor and Patch Components. """ return '.'.join([str(major_component), str(minor_component), str(patch_component)])
def read_nodes(data): """Reads the input data as nodes""" nodes = [] for line in data.splitlines(): words = line.split(" -> ") first_index = words[0].index("(") + 1 second_index = words[0].index(")") children = None if len(words) > 1: # Has children children = words[1].split(", ") nodes.append((words[0][:first_index - 2], int(words[0][first_index:second_index]), children)) return nodes
def distribute_tasks(n, memlim): """Util function for distribute tasks in matrix computation in order to save memory or to parallelize computations. Parameters ---------- n: int the number of rows. memlim: int the limit of rows we are able to compute at the same time. Returns ------- lims: list the list of limits for each interval. """ lims = [] inflim = 0 while True: if inflim + memlim >= n: lims.append([inflim, n]) break else: lims.append([inflim, inflim+memlim]) inflim = inflim+memlim return lims
def n_to_c(n_dict): """ Calculates concentrations (c) from normalized peak areas (n) """ n_tot = 0 for element in n_dict: n_tot += n_dict[element] return {element: n_dict[element]/n_tot for element in n_dict}
def check_img_ext(filename): """Check that file upload is an allowable image filetype""" allowed_image_ext = ['PNG', 'JPG', 'JPEG', 'GIF'] if not '.' in filename: return False ext = filename.split('.')[-1] if ext.upper() in allowed_image_ext: return True else: return False
def dice(data, axis, i, like_shape=None): """like_shape means you want to embed the plane in larger plane of zeros in the position bbox """ if data==None: return None if axis==0: plane = data[i,:,:] elif axis==1: plane = data[:,i,:] elif axis==2: plane = data[:,:,i] else: raise Exception('BUG!') ret = plane return ret
def get_inheritance_map(classes): """Return a dict where values are strict subclasses of the key.""" return {scls: [p for p in classes if p != scls and p.issubclass(scls)] for scls in classes}
def arrayManipulation(n, queries): """ Args: n (int): len of zero arr. queries (list): 2d list with queries Returns: int: max element""" arr = [0] * (n + 1) # increase first el by query amount and decrease last of query amount for i in queries: arr[i[0] - 1] += i[2] arr[i[1]] -= i[2] # this way it's easy compute each el resulting value in one run ans = 0 current = 0 for i in arr: current += i if current > ans: ans = current return ans
def percents(x,y): """ What percentage of x is y? """ one_percent = x/100 result = y / one_percent return result
def map_ores_code_to_int(code): """ Takes a 1-2 letter code from OREs and turns in into an int ORES Score map Stub - 0 Start - 1 C - 2 B - 3 GA - 4 FA - 5 """ return { 'Stub': 0, 'Start': 1, 'C': 2, 'B': 3, 'GA': 4, 'FA': 5, }[code]
def parse_vertex(text): """Parse text chunk specifying single vertex. Possible formats: * vertex index * vertex index / texture index * vertex index / texture index / normal index * vertex index / / normal index """ v = 0 t = 0 n = 0 chunks = text.split("/") v = int(chunks[0]) if len(chunks) > 1: if chunks[1]: t = int(chunks[1]) if len(chunks) > 2: if chunks[2]: n = int(chunks[2]) return { 'v':v, 't':t, 'n':n }
def shareFavLangCost(criterion, frRow, exRow): """Returns 0 if the two share a favorite language, else 1""" fluentQ = criterion['fluentQ'] learningQ = criterion['learningQ'] favT = criterion['favTable'] favQ = criterion['favQ'] frLangs = [set(frRow[fluentQ].split(',')), set(frRow[learningQ].split(','))] exLangs = [set(exRow[fluentQ].split(',')), set(exRow[learningQ].split(','))] fav = {'fr': favT[frRow[favQ]], 'ex': favT[exRow[favQ]]} # Do they have no preferred language in common ? return int(len(frLangs[fav['fr']].intersection(exLangs[fav['ex']])) == 0)
def _get_acl_from_row(row): """ Given a row from the manifest, return the field representing file's expected acls. Args: row (dict): column_name:row_value Returns: List[str]: acls for the indexd record """ return [item for item in row.get("acl", "").strip().split(" ") if item]
def purge_dup(names): """temporary way of making sure values are unique""" unique_names = {k: [] for k in names} for k in names.keys(): hash = set() for v in names[k]: if v['name'] not in hash: hash.add(v['name']) unique_names[k].append(v) return unique_names
def _is_literal(s): """ >>> _is_literal("http://example.org/bar") False >>> _is_literal('"my text"') True >>> _is_literal('"my text"@en-gb') True >>> _is_literal('"42"^^http://www.w3.org/2001/XMLSchema#integer') True >>> _is_literal('?var') False """ return s.startswith('"')
def null_data_cleaner(original_data: dict, data: dict) -> dict: """ this is to remove all null parameters from data that are added during option flow """ for key in data.keys(): if data[key] == "null": original_data[key] = "" else: original_data[key]=data[key] return original_data
def hack_ncbi_fasta_name(pipe_name): """Turn 'gi|445210138|gb|CP003959.1|' into 'CP003959.1' etc. For use with NCBI provided FASTA and GenBank files to ensure contig names match up. Or Prokka's *.fna and *.gbk files, turning 'gnl|Prokka|contig000001' into 'contig000001' """ if pipe_name.startswith("gi|") and pipe_name.endswith("|"): return pipe_name.split("|")[3] elif pipe_name.startswith("gnl|") and pipe_name.count("|")==2: return pipe_name.split("|")[2] else: return pipe_name
def quick_sort(vals): """Return sorted list as copy.""" if len(vals) <= 1: return vals[:] axis = vals[0] left = [] right = [] for val in vals[1:]: if val <= axis: left.append(val) else: right.append(val) return quick_sort(left) + [axis] + quick_sort(right)
def merge_bbox(bbox1, bbox2): """Merge two pdf blocks' bounding boxes.""" return ( min(bbox1[0], bbox2[0]), # x0 min(bbox1[1], bbox2[1]), # y0 max(bbox1[2], bbox2[2]), # x1 max(bbox1[3], bbox2[3]), # y1 )
def get_user_names(L): """ for each line in twitter data slice out username if its not in username list add it :param L - list of twitter data: :return user_names - list of user names: """ user_names = list() for item in L: user_name = item[0] if user_name not in user_names: user_names.append(user_name) user_names = sorted(user_names) return user_names
def obfuscate_API_key(API_key): """ Return a mostly obfuscated version of the API Key :param API_key: input string :return: str """ if API_key is not None: return (len(API_key)-8)*'*'+API_key[-8:]
def gcd_euclid(a, b): """ 10) 15 (1 10 -------- 5) 10 (2 10 -------- 0 GCD = 5 """ if b == 0: return a else: return gcd_euclid(b, a % b)
def readbuffer(data): """ Reads an arbitary data objects and returns the byte representation :param data: :type data: :return: :rtype: """ if not data: return b'' if str(type(data)) == "<type 'buffer'>": return str(data) elif str(type(data)) == "<class 'memoryview'>": return data.tobytes().decode() else: return str(data).encode("utf-8")
def _format(_string, format_s='{}', style = None): """Add color formatting to string for printing in a terminal.""" styles = { 'green' : '\033[37m\033[42m', 'yellow' : '\033[37m\033[43m', 'red' : '\033[37m\033[41m', None : '' } if not style in styles.keys(): raise Exception('Unknown style "%s"'%style) if style: return styles[style] + format_s.format(_string) + '\033[00m' else: return format_s.format(_string)
def parse_field_configured(obj, config): """ Parses an object to a Telegram Type based on the configuration given :param obj: The object to parse :param config: The configuration: - is array? - is array in array? - type of the class to be loaded to :return: the parsed object """ foreign_type = config if type(config) != dict else config['class'] if type(config) == dict: if 'array' in config and config['array'] is True: return [foreign_type(x) for x in obj] elif 'array_of_array' in config and config['array_of_array'] is True: res = [] for inner_obj in obj: res.append([foreign_type(x) for x in inner_obj]) return res return foreign_type(obj)
def rows_to_columns(matrix): #hammer """Takes a two dimensional array and returns an new one where rows in the first become columns in the second.""" num_rows = len(matrix) num_cols = len(matrix[0]) data = [] for i in range(0, num_cols): data.append([matrix[j][i] for j in range(0, num_rows)]) return data
def get_scene_index(glTF, name): """ Return the scene index in the glTF array. """ if glTF.get('scenes') is None: return -1 index = 0 for scene in glTF['scenes']: if scene['name'] == name: return index index += 1 return -1
def valid_content_type(content_type): """returns if content type is what we are looking for""" return "text/html" in content_type
def content_by_name_substring(content, name): """ :type content: dict :param content: The python dict form of the content that has been returned from a query to KairosDB :type name: string :param name: This is the string that will be used to match, as a lowercase substring, the things that we want to return. :rtype: list :returns: The list of pairs of [timestamp, value] that matched When you've got content, but only want to look at a piece of it, specifically the values that are provided for a particular name, then use this function. and this will be turned into a python struct. This function will return a list of dicts that matched the provided name. """ r_list = list() for q in content["queries"]: for r in q["results"]: if name.lower() in r["name"].lower(): r_list.append(r) return r_list
def divide_channels(old_pixel: tuple, denominator: int) -> tuple: """Return a new pixel that has colour channels set to the quotient from dividing the corresponding colour channel in old_pixel by denominator. * Assumed that denominators are positive integers. >>> example_pixel = (100, 12, 155) >>> divide_channels(example_pixel, 2) (50, 6, 77) """ return tuple([chan // denominator for chan in old_pixel])
def shift(char: str, key: int) -> str: """Shift the character by the given key.""" if char == "-": return " " else: return chr(97 + (ord(char) - 97 + key % 26) % 26)
def get_complement(sequence): """Get the complement of `sequence`. Returns a string with the complementary sequence of `sequence`. If `sequence` is empty, an empty string is returned. """ #Convert all rna_sequence to upper case: sequence=sequence.upper() # Conver RNA sequence into a list rna_list=list(sequence) #Create an empty list to store complement sequence: comlement_sequence=[] #Complement code corresponsing for all RNA bases complement= {'A' : 'U', 'C' : 'G', 'G': 'C', 'U': 'A'} # Looping through all the bases in RNA seq. to convert to its complement seq using dictionary values. for i in rna_list: comlement_sequence.append(complement[i]) return ''.join(comlement_sequence)
def usd(value): """ Format value as USD """ return f"${value:,.2f}"
def gauss_sum(n): """Calculate sum(x for x in range(1, n+1)) by formula.""" return n * (n + 1) // 2
def find_end_paren(function_code: str, start: int): """ Find the end location given a starting parenthesis location :param function_code: :param start: :return: """ parentheses = [] for i, character in enumerate(function_code[start:]): if character == "(": parentheses.append(character) elif character == ")": parentheses.pop() if not parentheses: return i + start
def _get_level(path): """Determine the number of sub directories `path` is contained in Args: path (string): The target path Returns: int: The directory depth of `path` """ normalized = path # This for loop ensures there are no double `//` substrings. # A for loop is used because there's not currently a `while` # or a better mechanism for guaranteeing all `//` have been # cleaned up. for i in range(len(path)): new_normalized = normalized.replace("//", "/") if len(new_normalized) == len(normalized): break normalized = new_normalized return normalized.count("/")
def inverted_index_add(inverted, doc_id, doc_index): """ create a WORD LEVEL DOCUMENT UNSPECIFIC Inverted-Index {word:{doc_id:[locations]}} """ for word, locations in doc_index.items(): indices = inverted.setdefault(word, {}) indices[doc_id] = locations return inverted
def updatemany_data_handler(args): """ Handler to override the api action taken for updatemany """ _, path, data = args return "PATCH", path, data
def hash_str(f): """ Return sha256 of input string """ import hashlib return hashlib.sha256(str(f).encode()).hexdigest()
def y_from_m_b_x(m, b, x): """ get y from y=mx+b :param m: slope (m) :param b: b :param x: x :return: y from y=mx+b """ return m * x + b
def _CheckBarcode(barcode): """Check weather the UPC-A barcode was decoded correctly. This function calculates the check digit of the provided barcode and compares it to the check digit that was decoded. Args: barcode(string): The barcode (12-digit). Return: (bool): True if the barcode was decoded correctly. """ if len(barcode) != 12: return False r1 = range(0, 11, 2) # Odd digits r2 = range(1, 10, 2) # Even digits except last dsum = 0 # Sum all the even digits for i in r1: dsum += int(barcode[i]) # Multiply the sum by 3 dsum *= 3 # Add all the even digits except the check digit (12th digit) for i in r2: dsum += int(barcode[i]) # Get the modulo 10 dsum = dsum % 10 # If not 0 substract from 10 if dsum != 0: dsum = 10 - dsum # Compare result and check digit return dsum == int(barcode[11])
def make_query(columns, filter): """ columns is a string from args.columns filter is a string from args.filter this will build the main query using input from columns and filter """ if columns is not None: # the user only wants to report a subset of the columns query = "SELECT " + columns + " FROM variants" # elif cancers != 'none': # query = "SELECT " + columns + ",civic_gene_abbreviations,cgi_gene_abbreviations FROM variants" else: # report the kitchen sink query = "SELECT * FROM variants" if filter is not None: # add any non-genotype column limits to the where clause query += " WHERE " + filter return query
def convert_seconds(seconds: float) -> str: """ Convert time in seconds to days:hours:minutes:seconds.milliseconds with leading 0s removed. Parameters ---------- seconds : float Number of seconds to be converted. Returns ------- str Converted time. """ mS = int((seconds) * 1000) D, mS = divmod(mS, 86400000) H, mS = divmod(mS, 3600000) M, mS = divmod(mS, 60000) S, mS = divmod(mS, 1000) H = str(H).zfill(2) M = str(M).zfill(2) S = str(S).zfill(2) mS = str(mS).zfill(3) time = f'{D}:{H}:{M}:{S}.{mS}'.lstrip('0:') if time.startswith('.'): time = '0' + time return time
def lookup(index, event_ref_list): """ Get the unserialized event_ref in an list of them and return it. """ if index < 0: return None else: count = 0 for event_ref in event_ref_list: (private, note_list, attribute_list, ref, role) = event_ref if index == count: return ref count += 1 return None
def analytic_convolution_gaussian(mu1,covar1,mu2,covar2): """ The analytic vconvolution of two Gaussians is simply the sum of the two mean vectors and the two convariance matrixes --- INPUT --- mu1 The mean of the first gaussian covar1 The covariance matrix of of the first gaussian mu2 The mean of the second gaussian covar2 The covariance matrix of of the second gaussian """ muconv = mu1+mu2 covarconv = covar1+covar2 return muconv, covarconv
def _query(data, predicate=None, key=None, reverse=False): """Query data and return results as a list of items. Args: data: list of lists or list of tuples predicate: custom function for filtering results. key: custom comparison key function for sorting results. Set to get_identity method to sort on identity. reverse: If set to True, then the list elements are sorted as if each comparison were reversed. Returns: list: list of items """ if predicate: result = list(filter(predicate, data)) else: result = data[:] if key or reverse: result = sorted(result, key=key, reverse=reverse) return result
def service_fully_started(dut, service): """ @summary: Check whether the specified service is fully started on DUT. According to the SONiC design, the last instruction in service starting script is to run "docker wait <service_name>". This function take advantage of this design to check whether a service has been fully started. The trick is to check whether "docker wait <service_name>" exists in current running processes. @param dut: The AnsibleHost object of DUT. For interacting with DUT. @param service: Service name. @return: Return True if the specified service is fully started. Otherwise return False. """ try: output = dut.command('pgrep -f "docker wait %s"' % service) if output["stdout_lines"]: return True else: return False except: return False
def getCustomOutMsg(errMsg=None, errCode=None, msg=None, exitCode=None): """ Create custom return dictionary """ newOut = {} if errMsg: newOut['error_description'] = errMsg if errCode: newOut['error'] = errCode if msg: newOut['msg'] = msg if exitCode: newOut['exitCode'] = exitCode return newOut
def create_ordering_payload(order=None): """Creates a payload for the given order :param order: The order, defaults to None :type order: dict, optional :raises ValueError: If the order is not a dictionnary :return: The created payload :rtype: dict """ payload = {} if not order: return payload if not isinstance(order, dict): return payload direction = order.get("direction", "ASC") field = order.get("field", None) if direction not in ["ASC", "DESC"]: raise ValueError("Direction must be ASC or DESC") if direction == "DESC": field = "-{field}".format(field=field) payload["ordering"] = field return payload
def extract_value(obj, key): """Pull all values of specified key from nested JSON.""" arr = [] def extract(obj, arr, key): """Recursively search for values of key in JSON tree.""" if isinstance(obj, dict): for k, v in obj.items(): if k == key: arr.append(v) elif isinstance(v, (dict, list)): extract(v, arr, key) elif isinstance(obj, list): for item in obj: extract(item, arr, key) return arr results = extract(obj, arr, key) return results[0]
def _escape_key(string): """ The '_type' and '_meta' keys are reserved. Prefix with an additional '_' if they occur. """ if string.startswith("_") and string.lstrip("_") in ("type", "meta"): return "_" + string return string
def ERR_CHANNELISFULL(sender, receipient, message): """ Error Code 471 """ return "ERROR from <" + sender + ">: " + message
def list_reduce(fn, lst, dftl): """Implementation of list_reduce.""" res = dftl i = 0 while i < len(lst): res = fn(res, lst[i]) i = i + 1 return res
def fmt(x, pos): """ Format color bar labels """ if abs(x) > 1e4 or (abs(x) < 1e-2 and abs(x) > 0): a, b = f"{x:.2e}".split("e") b = int(b) return fr"${a} \cdot 10^{{{b}}}$" elif abs(x) > 1e2 or (float(abs(x))).is_integer(): return fr"${int(x):d}$" elif abs(x) > 1e1: return fr"${x:.1f}$" elif abs(x) == 0.0: return fr"${x:.1f}$" else: return fr"${x:.2f}$"
def get(seq, ind, defVal=None): """Return seq[ind] if available, else defVal""" try: return seq[ind] except LookupError: return defVal
def ascii_hex_to_byte(ascii_bytes): """ Returns integer value, which is encoded as hexadecimal in first two characters (ascii bytes) of input; assumes *ascii_bytes* is a string or array of characters. Raises ValueError if there was a problem parsing the hex value. """ assert len(ascii_bytes) >= 2 return int(ascii_bytes[0] + ascii_bytes[1], 16)
def at_least(actual_value, expected_value): """Assert that actual_value is at least expected_value.""" result = actual_value >= expected_value if result: return result else: raise AssertionError( "{!r} is LESS than {!r}".format(actual_value, expected_value) )
def any(p, xs): """ any :: (a -> Bool) -> [a] -> Bool Applied to a predicate and a list, any determines if any element of the list satisfies the predicate. For the result to be False, the list must be finite; True, however, results from a True value for the predicate applied to an element at a finite index of a finite or infinite list. """ return True in ((p(x) for x in xs))
def binpow(x: int, n: int, m: int) -> int: """Return x**n % m.""" ans = 1 while n: if n & 1: ans = ans * x % m x = x * x % m n >>= 1 return ans
def reshape_images(image_list=None): """ :param image_list: A list of images to reshape for plotting :return: Images that can be plotted with show_images """ if image_list is None: raise ValueError("Please provide a list of images to reshape.") final_list = [img[:, :, 0] if len(img.shape) == 3 and img.shape[2] != 3 else img for img in image_list] return final_list
def quoteIfNeeded(txt, quoteChar='"'): """ quoteIfNeededtxt) surrounds txt with quotes if txt includes spaces or the quote char """ if isinstance(txt, bytes): txt=txt.decode() if txt.find(quoteChar) or txt.find(' '): return "%s%s%s" % (quoteChar, txt.replace(quoteChar, "\\%s" % quoteChar), quoteChar) return txt
def create_batches(graphs, batch_size): """ Creating batches of graph locations. :param graphs: List of training graphs. :param batch_size: Size of batches. :return batches: List of lists with paths to graphs. """ batches = [graphs[i:i + batch_size] for i in range(0, len(graphs), batch_size)] return batches
def initialize_scale_config_details(node_classes, param_key, param_value): """ Initialize scale cluster config details. :args: node_class (list), param_key (string), param_value (string) """ scale_config = {} scale_config['scale_config'], scale_config['scale_cluster_config'] = [], {} for each_node in node_classes: scale_config['scale_config'].append({"nodeclass": each_node, "params": [{param_key: param_value}]}) scale_config['scale_cluster_config']['ephemeral_port_range'] = "60000-61000" return scale_config
def get_operand_string(mean, std_dev): """ Method to get operand string for Fsl Maths Parameters ---------- mean : string path to img containing mean std_dev : string path to img containing standard deviation Returns ------ op_string : string operand string """ str1 = "-sub %f -div %f" % (float(mean), float(std_dev)) op_string = str1 + " -mas %s" return op_string
def E_c(contact_dist, margin, constant, missing_weight=1): """ Contact energy function :param contact_dist: dictionary of geom id and its distance from the target :param margin: maximum distance between geom and target detected :param constant: constant dist we ideally want the geoms to "invade" target :param missing_weight: weight of geoms that are too far away from target :return: normalised contact energy function """ # add palm palm_w = 3 # palm weight to make it more important than the rest of the tips (must be integer) if contact_dist is not None and 12 in contact_dist: # palm id for i in range(palm_w - 1): contact_dist[12 + (i+1) * 100] = contact_dist[12] # add identical palm entries for the mean total = 5 + palm_w if contact_dist is not None: s = (total - len(contact_dist)) * missing_weight * ((margin + constant)**2) # punish for those that are not even in range for key in contact_dist: # ideally the distance is less than zero, so add constant to make it positive s += (max(max(contact_dist[key]) + constant, 0)) ** 2 # we want it to be less than 0 so there applied force # normalise # coeff = (len(contact_dist) + (5 - len(contact_dist)) * missing_weight) * ((margin + constant) ** 2) s /= (len(contact_dist) + (total - len(contact_dist)) * missing_weight) * ((margin + constant) ** 2) return s else: return 1
def compare_with_lt(x, y): """ Comparator function that promises only to use the `<` binary operator (not `>`, `<=`, etc.) See also: `functools.cmp_to_key` if you plan to use this with `sorted`. """ if x < y: return -1 elif y < x: return 1 else: return 0
def imlistidx(filelist, idx_in_filename): """Return index in list of filename containing index number""" return [i for (i, item) in enumerate(filelist) if (item.find('%d' % idx_in_filename) > 0)]
def parse_config(config, value): """Parse config for string interpolation""" config["tmp_value"] = value return config["tmp_value"]
def get_valid_uuids(uuids: list, full_paths: list, valid_full_paths: list) -> list: """Returns valid uuids.""" return [uuid for uuid, full_path in zip(uuids, full_paths) if full_path in valid_full_paths]
def filter_blobnames_for_prefix(candidates, prefix, sep): """Given a iterator of candidate blob names, return a set of 2-tuples indicating each match: (<sub-name>, <is-partial-match>) where, <sub-name> is the import component after the prefix <is-partial-match> is a boolean indicating if suffix is multipart. For example, given: candidates = ["LWP", "LWP::Authen::Basic", "LWP::Authen::Digest", "LWP::ConnCache", "LWP::Protocol", "LWP::Protocol::http", "LWP::Protocol::https", "LWP::UserAgent"] prefix = ("LWP",) sep = "::" the returned items should be: ("Authen", True) ("ConnCache", False) ("Protocol", False) ("Protocol", True) ("UserAgent", False) """ matches = set() if not prefix: for name in candidates: if name == "*": continue # skip "built-in" blob if sep in name: matches.add((name[:name.index(sep)], True)) else: matches.add((name, False)) else: sep_len = len(sep) sepped_prefix = sep.join(prefix) for name in candidates: if name == "*": continue # skip "built-in" blob if name.startswith(sepped_prefix + sep): # e.g. prefix is "xml", and we see "xml.sax" and "xml.bar.foo" subname = name[len(sepped_prefix)+sep_len:] # subname is "sax" and "bar.foo" if sep in subname: # we want to return bar, not bar.foo subname = subname[:subname.index(sep)] is_partial_match = True else: is_partial_match = False matches.add((subname, is_partial_match)) return matches
def _sprite_has_rectangular_region(sprite): """ A replacement function for the ugly compound in sprite_in_view """ return ( hasattr(sprite, "width") and hasattr(sprite, "height") and hasattr(sprite, "left") and hasattr(sprite, "right") and hasattr(sprite, "top") and hasattr(sprite, "bottom") )
def mod_inverse(a, n): """Return the inverse of a mod n. n must be prime. >>> mod_inverse(42, 2017) 1969 """ b = n if abs(b) == 0: return (1, 0, a) x1, x2, y1, y2 = 0, 1, 1, 0 while abs(b) > 0: q, r = divmod(a, b) #print("q : " + str(q) + " r : " + str(r)); x = x2 - q * x1 y = y2 - q * y1 a, b, x2, x1, y2, y1 = b, r, x1, x, y1, y #print("a : " + str(a) + " b : " + str(b) + " x2 : " + str(x2) + " x1 : " + str(x1) # + " y2 : " + str(y2) + " y1 : " + str(y1)); return x2 % n
def pad4(length): """ >>> pad4(9) 3 >>> pad4(20) 0 :param length: :return: """ return -(length % -4)
def new_game(n): """ Inicializa la matrix en blanco (4x4) lista de listas """ matrix = [] for i in range(n): matrix.append([0] * n) return matrix
def ll4(x,b,c,d,e): """Dose-response function - LM equation, LL.4 function (4-parameter sigmoidal function). - b: hill slope - c: min response - d: max response - e: EC50""" import numpy as np import warnings warnings.filterwarnings('ignore') return(c+(d-c)/(1+np.exp(b*(np.log(x)-np.log(e)))))
def qcVector(vectint, records): """ Given a set of vector interval and a genome to correct remove the sequence of the genomes overlapping with the vector intervals, if the overlap occurs less than 100nts away from the contig ends Args: vectint list of intervals genome genome sequence file Return: corrected genome sequence. Check the warning to see if regions were not corrected """ tomodify = {} for record in records: if record in vectint: modifications = {} # if contig in vectint # fuse interval fuseintervals = vectint[record] # begin or end +/- 10 recordlength = len(records[record].seq) if fuseintervals[0][0] < 100: # correct sequence at the begining modifications["trim5"] = fuseintervals[0][1] elif fuseintervals[-1][1] > recordlength-100: modifications["trim3"] = fuseintervals[-1][0] if len(modifications): tomodify[record] = modifications return tomodify
def note_and_bend(mycents, middle_note=60): """Take a cent value and return a MIDI note and bend. Scale to '0 cents = middle-C' if middle_c=True. """ note, remain = divmod(mycents + 50, 100.0) note = int(note + middle_note) bend = 8192 + int(round((remain - 50) * 40.96)) return note, bend
def str_or_NONE(value): """If the `value` is `None` returns a "NONE"", otherwise returns `str(value)` """ if value is None: return 'NONE' return str(value)
def format_box_wider2tfrecord(x, y, w, h, real_h, real_w): """ wider to tf_record record the rate of min point and width/height :param x: :param y: :param w: :param h: :param real_h: :param real_w: :return: """ print('orig: ', x, y, w, h, real_h, real_w) x_ = x / real_w y_ = y / real_h w_ = (x + w) / real_w h_ = (y + h) / real_h # return int(x), int(y), int(w), int(h) print('rate: ', x_, y_, w_, h_) return x_, y_, w_, h_
def precond_is_classifier(iterable=None, program=None): """Ensure that a program can do classification.""" if program.__class__.__name__ in ['SGDClassifier', 'LogisticRegression']: return True else: return False
def set_runtime_build(runtime_build: bool) -> bool: """ When runtime_build is True, csrc will be built at runtime. Default is False. """ if not isinstance(runtime_build, bool): raise TypeError("runtime_build must be bool") global _runtime_build _runtime_build = runtime_build return _runtime_build
def pad_to_multiple_of(n, mult): """ pads n to a multiple of mult """ extra = n % mult if extra > 0: n = n + mult - extra return n
def ArrowCurve(type=1, a=1.0, b=0.5): """ ArrowCurve( type=1, a=1.0, b=0.5, c=1.0 ) Create arrow curve Parameters: type - select type, Arrow1, Arrow2 (type=int) a - a scaling parameter (type=float) b - b scaling parameter (type=float) Returns: a list with lists of x,y,z coordinates for curve points, [[x,y,z],[x,y,z],...n] (type=list) """ newpoints = [] if type == 0: # Arrow1: a *= 0.5 b *= 0.5 newpoints = [ [-1.0, b, 0.0], [-1.0 + a, b, 0.0], [-1.0 + a, 1.0, 0.0], [1.0, 0.0, 0.0], [-1.0 + a, -1.0, 0.0], [-1.0 + a, -b, 0.0], [-1.0, -b, 0.0] ] elif type == 1: # Arrow2: newpoints = [[-a, b, 0.0], [a, 0.0, 0.0], [-a, -b, 0.0], [0.0, 0.0, 0.0]] else: # diamond: newpoints = [[0.0, b, 0.0], [a, 0.0, 0.0], [0.0, -b, 0.0], [-a, 0.0, 0.0]] return newpoints
def cardLuhnChecksumIsValid(card_number): """ checks to make sure that the card passes a luhn mod-10 checksum """ sum = 0 num_digits = len(card_number) oddeven = num_digits & 1 for count in range(num_digits): digit = int(card_number[count]) if not (( count & 1 ) ^ oddeven): digit = digit * 2 if digit > 9: digit = digit - 9 sum = sum + digit return (sum % 10) == 0
def kwargs_to_variable_assignment(kwargs: dict, value_representation=repr, assignment_operator: str = ' = ', statement_separator: str = '\n', statement_per_line: bool = False) -> str: """ Convert a dictionary into a string with assignments Each assignment is constructed based on: key assignment_operator value_representation(value) statement_separator, where key and value are the key and value of the dictionary. Moreover one can seprate the assignment statements by new lines. Parameters ---------- kwargs : dict assignment_operator: str, optional: Assignment operator (" = " in python) value_representation: str, optinal How to represent the value in the assignments (repr function in python) statement_separator : str, optional: Statement separator (new line in python) statement_per_line: bool, optional Insert each statement on a different line Returns ------- str All the assignemnts. >>> kwargs_to_variable_assignment({'a': 2, 'b': "abc"}) "a = 2\\nb = 'abc'\\n" >>> kwargs_to_variable_assignment({'a':2 ,'b': "abc"}, statement_per_line=True) "a = 2\\n\\nb = 'abc'\\n" >>> kwargs_to_variable_assignment({'a': 2}) 'a = 2\\n' >>> kwargs_to_variable_assignment({'a': 2}, statement_per_line=True) 'a = 2\\n' """ code = [] join_str = '\n' if statement_per_line else '' for key, value in kwargs.items(): code.append(key + assignment_operator + value_representation(value)+statement_separator) return join_str.join(code)
def version2tuple(ver: str) -> tuple: """Convert version to numeric tuple""" import re if re.match(r"\d+\.\d+\.\d+$", ver) is None: raise ValueError(r"Version must be well formed: \d+\.\d+\.\d+") return tuple([int(val) for val in ver.split(".")])
def has_two_stage_cooling(cool_stage): """Determines if the cooling stage has two-stage capability Parameters ---------- cool_stage : str The name of the cooling stage Returns ------- boolean """ if cool_stage == "two_speed" or cool_stage == "two_stage": return True return False
def _strip_declaration(contents: str): """ Strips declaration from the file if there - lxml doesn't like it.""" return str.replace(contents,r'<?xml version="1.0" encoding="utf-8"?>','').strip()
def format_error(worker_id, message): """Formats an error message with the provided worker ID.""" return f"Worker {worker_id}: {message}"
def reverse_match_odds(match, odds): """ Reverse match opponents and odds (away - home -> home - away) """ match = " - ".join(reversed(match.split(" - "))) odds.reverse() return match, odds
def merge_raw_data(commits, lines_of_code): """ Creates a list of the files sorted primarily by the number of changes and secondly by the number of lines of code. :param commits: a dict of file names and the number of commits :param lines_of_code: a dict of file names and the number of lines of code :return: a sorted list of tuple (name, changes, lines) """ data = [] for k, v in commits.items(): # File may not exist anymore but is still in log # Skip these files if k in lines_of_code: data.append((k, v, lines_of_code[k])) # Sort on secondary key data = sorted(data, key=lambda x: x[2], reverse=True) # Sort on primary key as this gives sorted by first value then by # second value return sorted(data, key=lambda x: x[1], reverse=True)
def handle(string: str) -> str: """ >>> handle('https://github.com/user/repo') 'user/repo' >>> handle('user/repo') 'user/repo' >>> handle('') '' """ splt = string.split("/") return "/".join(splt[-2:] if len(splt) >= 2 else splt)
def quote_path(path): """ Surrounds the path in quotes. :param path: :return: string """ return '"' + path.strip('"') + '"'
def canonise(i, j): """ Return canonical intervals of the input interval. Args: i (int): left endpoint of input interval (inclusive). j (int): right endpoint of input interval (inclusive). Returns: List of canonical intervals. Each interval is of the form (start,end) where start and end are integers. """ if j-i <= 8: return [] retval = [] retval.append((i, j)) midpoint = (i + j)/2 retval.extend(canonise(i, midpoint)) retval.extend(canonise(midpoint + 1, j)) return retval
def wrap_function_agg(function, args): """ Wrap function for the objective function in the BHHH. """ ncalls = [0] if function is None: return ncalls, None def function_wrapper(*wrapper_args): ncalls[0] += 1 return function(*(wrapper_args + args)).sum() return ncalls, function_wrapper
def _prod(lst): """ .. todo:: WRITEME """ p = 1 for l in lst: p *= l return p
def get_skeleton_mapIdx(numparts): """ Calculate the mapsIdx for each limb from the skeleton. Input: skeleton: list of part connection Output: list of ids for x and y for part """ connections_num = numparts mapIdx = list() for i in range(connections_num): mapIdx.append([2 * i, (2 * i) + 1]) return mapIdx