content
stringlengths
42
6.51k
def shiftRight(n, x): """ shift n for x places """ return (n >> x & 0xFF)
def palindrome_permutation(string: str) -> bool: """ Determine if a string has a permutation that makes it a palindrome. Args: string (str): The string we are checking. Returns: bool: True if the string has a viable permutation. """ characters = set() for c in string: if c in characters: characters.remove(c) else: characters.add(c) return len(characters) <= 1
def cchunkify(lines, lang='', limit=2000): """ Creates code block chunks from the given lines. Parameters ---------- lines : `list` of `str` Lines of text to be chunkified. lang : `str`, Optional Language prefix of the code-block. limit : `int`, Optional The maximal length of a generated chunk. Returns ------- result : `list` of `str` Raises ------ ValueError` If limit is less than `500`. """ if limit < 500: raise ValueError(f'Minimal limit should be at least 500, got {limit!r}.') starter = f'```{lang}' limit = limit-len(starter)-5 result = [] chunk_length = 0 chunk = [starter] for line in lines: while True: ln = len(line)+1 if chunk_length+ln > limit: position = limit-chunk_length if position < 250: chunk.append('```') result.append('\n'.join(chunk)) chunk.clear() chunk.append(starter) chunk.append(line) chunk_length = ln break position = line.rfind(' ', position-250, position-3) if position == -1: position = limit-chunk_length-3 post_part = line[position:] else: post_part = line[position+1:] pre_part = line[:position]+'...' chunk.append(pre_part) chunk.append('```') result.append('\n'.join(chunk)) chunk.clear() chunk.append(starter) if len(post_part) > limit: line = post_part chunk_length = 0 continue chunk.append(post_part) chunk_length = len(post_part)+1 break chunk.append(line) chunk_length += ln break if len(chunk)>1: chunk.append('```') result.append('\n'.join(chunk)) return result
def get_game_ids(experiment_id): """ Get the games (train, eval) belonging to the given experiment ID. Training games will be randomized, where the evaluation games will not. """ if experiment_id in [1]: return [10000, ] * 10, \ [10000 + i for i in range(1, 21)] elif experiment_id in [2]: return [10000, ] * 10, \ [20000 + i for i in range(1, 19)] + [20100 + i for i in range(1, 19)] elif experiment_id in [3, 8]: return [30000, ] * 10, \ [30000 + i for i in range(1, 21)] elif experiment_id in [4]: # Combines experiment1&2 return [10000, ] * 10, \ [10000 + i for i in range(1, 21)] + \ [20000 + i for i in range(1, 19)] + \ [20100 + i for i in range(1, 19)] elif experiment_id in [6, 7]: return [60000, ] * 10, \ [60000 + i for i in range(1, 19)] else: raise Exception(f"Experiment of ID {experiment_id} is not supported")
def min_abs_mod(a, b): """ This function returns absolute minimum modulo of a over b. """ if a >= 0: return a - b * ((a + a + b) // (b + b)) a = -a return -(a - b * ((a + a + b) // (b + b)))
def generate_ena_api_endpoint(result: str, data_portal: str, fields: str, optional: str = ''): """ Generate the url for ENA API endpoint :param result: either be read_run (for experiment, file, dataset import) or analysis (for analysis import) :param data_portal: either ena (legacy data) or faang (faang data) :param fields: all (only faang data supports all) or list of fields separated by ',' (for legacy data) :param optional: optional constraint, e.g. species :return: the generated url """ if optional == "": return f"https://www.ebi.ac.uk/ena/portal/api/search/?" \ f"result={result}&format=JSON&limit=0&fields={fields}&dataPortal={data_portal}" else: return f"https://www.ebi.ac.uk/ena/portal/api/search/?" \ f"result={result}&format=JSON&limit=0&{optional}&fields={fields}&dataPortal={data_portal}"
def not_found_response(resource='servers'): """ Return a 404 response body for Nova, depending on the resource. Expects resource to be one of "servers", "images", or "flavors". If the resource is unrecognized, defaults to "The resource culd not be found." """ message = { 'servers': "Instance could not be found", 'images': "Image not found.", 'flavors': "The resource could not be found.", 'loadbalancer': "Load balancer not found", 'node': "Node not found" } resp = { "itemNotFound": { "message": message.get(resource, "The resource could not be found."), "code": 404 } } if resource == 'loadbalancer' or resource == 'node': return resp["itemNotFound"] return resp
def warn(string: str) -> str: """Add warn colour codes to string Args: string (str): Input string Returns: str: Warn string """ return "\033[93m" + string + "\033[0m"
def isLowSurrogate(ch): """Tests whether a Unicode character is from the low surrogates range""" code = ord(ch) return (0xDC00 <= code and code < 0xDFFF)
def shortened_hash(s, n): """ Return a shortened string with the first and last bits of a hash :param s: the full string to shorten :param n: the desired length of the string returned :return: An n-character string with the first and last bits of s """ side_len = int((n - 3) / 2) if len(s) <= n: return s else: return s[0:side_len] + "..." + s[(-1 * side_len):]
def generate_file_name(year_lst): """Generate a csv title including the years being scraped Args: year_lst (list): list containing the years being scrapped. Returns: str: csv file name specific to the years being scrapped. """ return f"{year_lst[0]}-{year_lst[-1]}_Team_Stats.csv"
def get_from_power_tuple(power_tuple, index): """ Extracts an exponent from an exponent tuple that may have been canonicalized to be shorter than the expected length, by removing extra zeroes. """ if index >= len(power_tuple): return 0 else: return power_tuple[index]
def cycle_checker(head): """Check if the Singly Linked List is cyclic. Returns boolean value based on the result """ marker_1 = head marker_2 = head flag = False while marker_2 != None and marker_2.next_node != None: marker_1 = marker_1.next_node marker_2 = marker_2.next_node.next_node if marker_1 == marker_2: return True return False
def line_number_match(array1, array2): """ Function that compares two lists of line numbers and determines which line numbers are missing from either array. :param array1: A list to be compared :param array2: A list to be compared :return: Where in the program there is a parenthesis missing as an integer """ if len(array1) < len(array2): for number in array1: try: array2.remove(number) except ValueError: return number return array2[0] else: for number in array2: try: array1.remove(number) except ValueError: return number if len(array1) != 0: return array1[0] else: return None
def merge_dicts(*dicts, **kwargs): """Merge all dicts in `*dicts` into a single dict, and return the result. If any of the entries in `*dicts` is None, and `default` is specified as keyword argument, then return `default`.""" result = {} for d in dicts: if d is None and "default" in kwargs: return kwargs["default"] if d: result.update(d) return result
def disappear_angle_brackets(text: str) -> str: """ Remove all angle brackets, keeping the surrounding text; no spaces are inserted :param text: text with angle bracket :return: text without angle brackets """ text = text.replace("<", "") text = text.replace(">", "") return text
def convertListToString(theList): """ Really simply converts a list to a string """ string = "" for x in range(0, len(theList)): string = string + theList[x] return string
def selection_sort(m): """From left to right, replace each element with element with larger index and smallest value.""" for i in range(len(m)): min_pos = i # assume i has the smallest value. for j in range(i + 1, len(m)): # compare with the rest of elements. if m[min_pos] > m[j]: min_pos = j if min_pos != i: m[i], m[min_pos] = m[min_pos], m[i] return m
def say_hi(name: str, age: int) -> str: """ Hi! """ # your code here return "Hi. My name is {} and I'm {} years old".format(name, age)
def binary_search_iterative(array, left, right, key): """Iterativni verze predesle funkce. Iterativni podobu napiste podle intuice. """ while left < right: mid = (left + right) // 2 if key < array[mid]: right = mid - 1 elif key > array[mid]: left = mid + 1 else: return mid return left if array[left] == key else -1
def get_first_image_in_list(body_response, name_filter=None): """ Gets the first image in the list :param body_response: Parsed response (Python dic) :param name_filter: If this arg is set, this method will filtered by name content :return: First image in list (that contains name_filter in its name); None if not found or list is empty """ image_id = None if name_filter is not None: for image in body_response['images']: if name_filter in image['name']: image_id = image['id'] break else: if len(body_response['images']) != 0: image_id = body_response['images'][0]['id'] return image_id
def split_array(array, cells): """ Helper function for parsing fdtget output """ if array is None: return None assert (len(array) % cells) == 0 return frozenset(tuple(array[i*cells:(i*cells)+cells]) for i in range(len(array) // cells))
def parse_params(all_params): """Parses all_params dictionary into separate dictionaries""" directories = all_params.pop('directories') params = all_params.pop('parameters') classes = all_params.pop('classes') class_numbers = {c: n for (c, n) in list(zip(classes, [i for i in range(len(classes))]))} if not params['label_all_classes']: for c in classes: if c not in params['labeled_classes']: class_numbers[c] = -1 return directories, params, (classes, class_numbers)
def pick_penalty(table, wtype, bpart, rank): """ Picks the relevant penalty from the specified penalty table based on: - The weapon type - The body part - The seriousness of the damage """ try: return table[wtype][bpart][rank] except KeyError as error: return 'key_error', error.args[0] except IndexError as error: return 'index_error', error.args[0]
def del_key_if_present(dict_, key): """Returns dict with deleted key if it was there, otherwise unchanged dict""" if key in dict_.keys(): del dict_[key] return dict_
def assign_item(obj, index, val, oper=None): """ does an augmented assignment to the indexed (keyed) item of obj. returns obj for chaining. does a simple replacement if no operator is specified usually used in combination with the operator module, though any appropriate binary function may be used. >>> from operator import add >>> spam = [40] >>> assign_item(spam,0, 2,add) [42] >>> assign_item(globals(),'eggs', 12)['eggs'] 12 >>> eggs 12 """ if oper: obj[index] = oper(obj[index], val) else: obj[index] = val return obj
def generate_memory_region(region_descriptor): """ Generates definition of memory region. Args: region_descriptor (dict): memory region description Returns: string: repl definition of the memory region """ return """ {}: Memory.MappedMemory @ sysbus {} size: {} """.format(region_descriptor['name'], region_descriptor['address'], region_descriptor['size'])
def remove_excess_whitespace(line): """ Remove excess whitespace from a line. Args: line (str): line to remove excess whitespace from. Returns: str: The line with excess whitespace removed. """ return " ".join(line.strip().split())
def make_table(oldtable=None, values=None): """Return a table with thermodynamic parameters (as dictionary). Arguments: - oldtable: An existing dictionary with thermodynamic parameters. - values: A dictionary with new or updated values. E.g., to replace the initiation parameters in the Sugimoto '96 dataset with the initiation parameters from Allawi & SantaLucia '97: >>> from Bio.SeqUtils.MeltingTemp import make_table, DNA_NN2 >>> table = DNA_NN2 # Sugimoto '96 >>> table['init_A/T'] (0, 0) >>> newtable = make_table(oldtable=DNA_NN2, values={'init': (0, 0), ... 'init_A/T': (2.3, 4.1), ... 'init_G/C': (0.1, -2.8)}) >>> print("%0.1f, %0.1f" % newtable['init_A/T']) 2.3, 4.1 """ if oldtable is None: table = { "init": (0, 0), "init_A/T": (0, 0), "init_G/C": (0, 0), "init_oneG/C": (0, 0), "init_allA/T": (0, 0), "init_5T/A": (0, 0), "sym": (0, 0), "AA/TT": (0, 0), "AT/TA": (0, 0), "TA/AT": (0, 0), "CA/GT": (0, 0), "GT/CA": (0, 0), "CT/GA": (0, 0), "GA/CT": (0, 0), "CG/GC": (0, 0), "GC/CG": (0, 0), "GG/CC": (0, 0), } else: table = oldtable.copy() if values: table.update(values) return table
def user_match(user, username): """ Return True if this is the user we are looking for. Compares a user structure from a Gerrit record to a username (or email address). All users match if the username is None. """ if username is None: return True def field_match(field): if field not in user: return False return user[field] == username return field_match('email' if '@' in username else 'username')
def audit_fields(): """return audit fields""" return(("effective_user",), ("update_time",), ("update_user",), ("creation_time",), ("creation_user",))
def to_bytes(string: str) -> bytes: """Encodes the string to UTF-8.""" return string.encode("utf-8")
def process_files(args_array, cfg, log): """Function: process_files Description: This is a function stub for pulled_search.process_files. Arguments: (input) args_array -> Dictionary of command line options and values. (input) cfg -> Configuration setup. (input) log -> Log class instance. """ status = True if args_array and cfg and log: status = True return status
def remove_duplicate_awarded_flairs(all_awarded_flairs): """Edit find all award flairs that have the same type (duplicates) and remove one, putting information of there being more into a field""" ls = [] flair_id_ls = [] for awarded_flair in all_awarded_flairs: if awarded_flair.flair_id in flair_id_ls: continue # Done this ID already count = 0 for flair in all_awarded_flairs: if awarded_flair.flair_id == flair.flair_id: count = count+1 # Set count of the number of times against this AwardedFlair object awarded_flair.awarded_count = count flair_id_ls.append(awarded_flair.flair_id) # Used to avoid duplicates by ID instead of object ls.append(awarded_flair) return ls
def get_full_policy_path(arn: str) -> str: """ Resource string will output strings like the following examples. Case 1: Input: arn:aws:iam::aws:policy/aws-service-role/AmazonGuardDutyServiceRolePolicy Output: aws-service-role/AmazonGuardDutyServiceRolePolicy Case 2: Input: arn:aws:iam::123456789012:role/ExampleRole Output: ExampleRole :param arn: :return: """ resource_string = arn.partition("/")[2] return resource_string
def quasi_newton( f , xi , step , epsilon=1e-5 , max=100 ): """ quasi_newton( f , xi , step , epsilon , max ). This is a root-finding method that finds the minimum of a function (f) using quasi-newton method. Parameters: f (function): the function to minimize xi (float): the starting point for the iterative process step (float): small step size to calculate an approached value to the derivatives epsilon (float): very small number max (int): max number of iterations Returns: x: optimum value """ k=0 x=xi fx=f(x) fplus=f(x+step) fmoins=f(x-step) x=x-((step*(fplus-fmoins))/(2*(fplus-2*fx+fmoins))) fplus=f(x+step) fmoins=f(x-step) dfx=(fplus-fmoins)/(2*step) while abs(dfx)>epsilon and k<max: fplus=f(x+step) fmoins=f(x-step) fx=f(x) dfx=(fplus-fmoins)/(2*step) x=x-((step*(fplus-fmoins))/(2*(fplus-2*fx+fmoins))) k+=1 if k==max: print("Error") else: return x
def read_count(f, n): """Read n bytes from a file stream; return empty string on EOF""" buf = '' while len(buf) < n: nextchunk = f.read(n - len(buf)) if not nextchunk: return '' buf += nextchunk return buf
def safe_division(a, b): """ :param a: quantity A :param b: quantity B :return: the quatient :rtype: float """ try: return a / b except ZeroDivisionError: return 0.0
def localname(uri): """Determine the local name (after namespace) of the given URI.""" return uri.split('/')[-1].split('#')[-1]
def format_binary(byte_array: bytearray): """ Formats the given byte array into a readable binary string. """ return ''.join('{:08b}_'.format(i) for i in byte_array)
def highlight(text): """Returns a text fragment (tuple) that will be highlighted to stand out.""" return ('highlight', text)
def merge_sort(input_list): """Merge sort function to split lists and recurrisvely call on left/right side, then add to results list.""" if isinstance(input_list, list): center = len(input_list) // 2 left = input_list[:center] right = input_list[center:] if len(left) > 1: left = merge_sort(left) if len(right) > 1: right = merge_sort(right) result = [] while left and right: if left[-1] >= right[-1]: result.append(left.pop()) else: result.append(right.pop()) return (left or right) + result[::-1] else: raise TypeError('Function only accepts list.')
def dist2(p1, p2): """ calculate 3d euclidean distance between points. """ return (p1[0]-p2[0])**2 + (p1[1]-p2[1])**2 + (p1[2]-p2[2])**2
def sum_var_named_args(a, b, **kwargs): """perform math operation, variable number of named args""" sum = a + b for key, value in sorted(kwargs.items()): sum += value return sum
def generate_ctrlpts_weights(ctrlpts): """ Generates unweighted control points from weighted ones in 1-D. This function #. Takes in 1-D control points list whose coordinates are organized in (x*w, y*w, z*w, w) format #. Converts the input control points list into (x, y, z, w) format #. Returns the result :param ctrlpts: 1-D control points (P) :type ctrlpts: list :return: 1-D weighted control points (Pw) :rtype: list """ # Divide control points by weight new_ctrlpts = [] for cpt in ctrlpts: temp = [float(pt / cpt[-1]) for pt in cpt] temp[-1] = float(cpt[-1]) new_ctrlpts.append(temp) return new_ctrlpts
def data_by_type(data_iterable): """ Takes a iterable of data and creates a dictionary of data types and sets up an array. """ data_by_typ = {} for datum in data_iterable: if datum.typ not in data_by_typ: data_by_typ[datum.typ] = [] data_by_typ[datum.typ].append(datum) # Parts of the code rely on the data to be in an array form and so we must # make the dictionary an array. This doesn't make sense to have here since # we may have to remove data in trim_data(). #for typ in data_by_typ: # data_by_typ[typ] = np.array(data_by_typ[typ], dtype=datatypes.Datum) return data_by_typ
def invert_map(dict_): """Invert the keys and values in a dict.""" inverted = {v: k for k, v in dict_.items()} return inverted
def is_point_in_rect(pt, rect=(0, 0, 0, 0)): """ To detect point is in rect or not :param pt: :param rect: :return: return True/False value to mean point is including in rect or not """ (x_min, x_max, y_min, y_max) = rect x = pt[0] y = pt[1] if x >= x_min and x < x_max and y >= y_min and y < y_max: return True else: return False
def is_dataset(X, require_attrs=None): """ Check whether an object is a Dataset. Parameters ---------- X : anything The object to be checked. require_attrs : list of str, optional The attributes the object has to have in order to pass as a Dataset. Returns ------- bool Whether the object is a Dataset or not. """ if require_attrs is None: require_attrs = ["data_vars", "coords", "dims", "to_array"] return all([hasattr(X, name) for name in require_attrs])
def get_filter_arg_csr(f, arg): """Convert integer to csr string.""" arg_types = { 1: 'CSR_ALLOW_UNTRUSTED_KEXTS', 2: 'CSR_ALLOW_UNRESTRICTED_FS', 4: 'CSR_ALLOW_TASK_FOR_PID', 8: 'CSR_ALLOW_KERNEL_DEBUGGER', 16: 'CSR_ALLOW_APPLE_INTERNAL', 32: 'CSR_ALLOW_UNRESTRICTED_DTRACE', 64: 'CSR_ALLOW_UNRESTRICTED_NVRAM', 128: 'CSR_ALLOW_DEVICE_CONFIGURATION', } if arg in arg_types.keys(): return '"%s"' % (arg_types[arg]) else: return '%d' % arg
def isDominated(wvalues1, wvalues2): """Returns whether or not *wvalues1* dominates *wvalues2*. :param wvalues1: The weighted fitness values that would be dominated. :param wvalues2: The weighted fitness values of the dominant. :returns: :obj:`True` if wvalues2 dominates wvalues1, :obj:`False` otherwise. """ not_equal = False for self_wvalue, other_wvalue in zip(wvalues1, wvalues2): if self_wvalue > other_wvalue: return False elif self_wvalue < other_wvalue: not_equal = True return not_equal
def validate_output(output_str): """This function returns true if the string given is a suitable value from interacting with gravi_utils""" errors = ['Could not resolve hostname', 'not found', 'Error writting to device', 'Timeout error'] if any(error in output_str for error in errors): return False else: return True
def _fixSlist(slist): """ Guarantees that a signed list has exactly four elements. """ slist.extend([0] * (4-len(slist))) return slist[:4]
def _el_orb(string): """Parse the element and orbital argument strings. The presence of an element without any orbitals means that we want to plot all of its orbitals. Args: string (str): The element and orbitals as a string, in the form ``"C.s.p,O"``. Returns: dict: The elements and orbitals as a :obj:`dict`. For example:: {'Bi': ['s', 'px', 'py', 'd']}. If an element symbol is included with an empty list, then all orbitals for that species are considered. """ el_orbs = {} for split in string.split(','): orbs = split.split('.') orbs = [orbs[0], 's', 'p', 'd', 'f'] if len(orbs) == 1 else orbs el_orbs[orbs.pop(0)] = orbs return el_orbs
def _to_original(sequence, result): """ Cast result into the same type >>> _to_original([], ()) [] >>> _to_original((), []) () """ if isinstance(sequence, tuple): return tuple(result) if isinstance(sequence, list): return list(result) return result
def remover_sp_str_load(list_parameters): """ Remove the sp and the brackets of the elements of the list """ i = 0 length = len(list_parameters) while i < length: list_parameters[i] = list_parameters[i].replace("[", "").replace("]", "").replace("sp", "") i += 1 list_parameters.remove("") if len(list_parameters) == 1: list_parameters.append("#0") return [list_parameters[0], list_parameters[1]]
def app_engine_service_account(project_id): """Get the default App Engine service account.""" return project_id + '@appspot.gserviceaccount.com'
def parseDockerAppliance(appliance): """ Takes string describing a docker image and returns the parsed registry, image reference, and tag for that image. Example: "quay.io/ucsc_cgl/toil:latest" Should return: "quay.io", "ucsc_cgl/toil", "latest" If a registry is not defined, the default is: "docker.io" If a tag is not defined, the default is: "latest" :param appliance: The full url of the docker image originally specified by the user (or the default). e.g. "quay.io/ucsc_cgl/toil:latest" :return: registryName, imageName, tag """ appliance = appliance.lower() # get the tag if ':' in appliance: tag = appliance.split(':')[-1] appliance = appliance[:-(len(':' + tag))] # remove only the tag else: # default to 'latest' if no tag is specified tag = 'latest' # get the registry and image registryName = 'docker.io' # default if not specified imageName = appliance # will be true if not specified if '/' in appliance and '.' in appliance.split('/')[0]: registryName = appliance.split('/')[0] imageName = appliance[len(registryName):] registryName = registryName.strip('/') imageName = imageName.strip('/') return registryName, imageName, tag
def flatten(x, out=None, prefix='', sep='.'): """ Flatten nested dict """ out = out if out is not None else {} if isinstance(x, dict): for k in x: flatten(x[k], out=out, prefix=f"{prefix}{sep if prefix else ''}{k}", sep=sep) elif isinstance(x, (list, tuple)): for k, v in enumerate(x): flatten(k, out=out, prefix=f"{prefix}{sep if prefix else ''}{k}", sep=sep) else: out[prefix] = x return out
def int_or_none(v, default=None, get_attr=None): """Check if input is int. Args: v (int): Input to check. default (type, optional): Expected type of get_attr. Defaults to None. get_attr (getter, optional): Getter to use. Defaults to None. Returns: int or None: Return int if valid or None. """ if get_attr: if v is not None: v = getattr(v, get_attr, None) if v == "": v = None if v is None: return default try: return int(v) except (ValueError, TypeError): return default
def common_substring(s1, s2): """ :type s1: str :type s2: str :rtype: str """ s1 = set(s1) s2 = set(s2) for c in s1: if c in s2: return True return False
def _parseUNIX(factory, address, mode='666', backlog=50, lockfile=True): """ Internal parser function for L{_parseServer} to convert the string arguments for a UNIX (AF_UNIX/SOCK_STREAM) stream endpoint into the structured arguments. @param factory: the protocol factory being parsed, or L{None}. (This was a leftover argument from when this code was in C{strports}, and is now mostly None and unused.) @type factory: L{IProtocolFactory} or L{None} @param address: the pathname of the unix socket @type address: C{str} @param backlog: the length of the listen queue @type backlog: C{str} @param lockfile: A string '0' or '1', mapping to True and False respectively. See the C{wantPID} argument to C{listenUNIX} @return: a 2-tuple of (args, kwargs), describing the parameters to L{twisted.internet.interfaces.IReactorUNIX.listenUNIX} (or, modulo argument 2, the factory, arguments to L{UNIXServerEndpoint}. """ return ( (address, factory), {'mode': int(mode, 8), 'backlog': int(backlog), 'wantPID': bool(int(lockfile))})
def get_y_from_key(key): """ :param key: :return: """ return (key >> 16) & 0xFF
def percent(num): """Format number as per cent with 2 decimal places.""" return "{:.2f}%".format(num * 100)
def is_sequence(value): """ Return ``True`` if ``value`` is a sequence type. Sequences are types which can be iterated over but are not strings or bytes. """ return not isinstance(value, str) and not isinstance(value, bytes) and hasattr(type(value), '__iter__')
def assign_to_red_or_black_group(x, y, x_cutoff, y_cutoff): """xcoord is coefficient (MAST already took log2). ycoord is -log10(pval). label is gene name.""" if abs(x) > x_cutoff and y > y_cutoff: color = "red" # x coordinate (coef) is set to 0 if one of the two groups has zero counts (in that case, # a fold change cannot be calculated). We'll color these points with 'salmon' (similar to red) elif abs(x) == 0 and y > y_cutoff: color = "salmon" else: color = "black" return color
def is_valid_state(state): """this function returns true if the given state is of formed by only . and 0, false otherwise GIVEN: a state WHEN: I apply it to generate an initial state THEN: the result is true if it contains only . and 0 """ return set(state) == {".","0"}
def show_collapsing_menu(outline): """ This template tag takes a list of dicts, outline, with the following structure: [ { 'title': title, 'url': url, 'children': [ { 'title': title, 'url': url, 'children': [ { 'title': title, 'url': url } ] } ] } ] Menu items, at each level, can have the following properties Required title: - the name displayed for the link Optional url bookmark: - the bookmark on the page to scroll too... this could be in the url property but sometimes this is displayed differently attrs: - a dictionary attributes to apply to this item (applied to the <li> by default) children_attrs: - a dictionary of attributes to apply to the <ul> for children """ return {'outline': outline}
def str_version(version): """converts a tuple of intergers to a version number""" return '.'.join(str(versioni) for versioni in version)
def conj_phrase(list_, cond='or'): """ Joins a list of words using English conjunction rules Args: list_ (list): of strings cond (str): a conjunction (or, and, but) Returns: str: the joined cconjunction phrase References: http://en.wikipedia.org/wiki/Conjunction_(grammar) Example: >>> # ENABLE_DOCTEST >>> from utool.util_str import * # NOQA >>> list_ = ['a', 'b', 'c'] >>> result = conj_phrase(list_, 'or') >>> print(result) a, b, or c Example1: >>> # ENABLE_DOCTEST >>> from utool.util_str import * # NOQA >>> list_ = ['a', 'b'] >>> result = conj_phrase(list_, 'and') >>> print(result) a and b """ if len(list_) == 0: return '' elif len(list_) == 1: return list_[0] elif len(list_) == 2: return ' '.join((list_[0], cond, list_[1])) else: condstr = ''.join((', ' + cond, ' ')) return ', '.join((', '.join(list_[:-2]), condstr.join(list_[-2:])))
def file_url(category, event_id=None, train_or_test="train"): """Returns the path of a csv corresponding to a given event and data category. Arguments: category -- one of "cells", "hits", "particles", "truth", "detectors", "sample_submission" or "hit_orders". event_id -- the integer id of an event. Should be included unless category is "detectors" or "sample submission". Ensure that event_id and train_or_test are consistent with each other. train_or_test -- one of "train" (default) or "test". """ if category == 'hit_orders': folder = 'particles-in-order' elif category in ('sample_submission', 'detectors'): return '/home/ec2-user/SageMaker/efs/codalab_dataset/{0}.csv'.format(category) else: folder = 'codalab_dataset/' + train_or_test return '/home/ec2-user/SageMaker/efs/{0}/event{1:09d}-{2}.csv'.format( folder, event_id, category)
def calculate_markedness(PPV, NPV): """ Calculates the markedness meassure of the supplied data, using the equation as per: http://www.flinders.edu.au/science_engineering/fms/School-CSEM/publications/tech_reps-research_artfcts/TRRA_2007.pdf (page 5) Markedness = PPV+NPV-1 Input: PPV: Positive Prediction Value NPV: Negative Pediction Value Output: Markedness """ return PPV+NPV-1
def _scaleRep(reportData): """ Scales reports of different sets of terms. Using the percent change with the 1 month overlap should take care of the variation in time of a single report. However, if, at the same moment in time, a secondary report contains a term which is larger than the constant term and so causes the constant to have different values, then the scale is off. To fix this, we select a value for the constant term at the same time across the new and old reports. factor = old / new, and multiply factor across the new report to have the same scale as the old one. """ baseMonth = reportData[0][0] for i in range(1, len(reportData)): testMonth = reportData[i][0] factor = 0.0 for j in range(len(baseMonth)): old = baseMonth[j][len(baseMonth[j])-1] #last term in line new = testMonth[j][len(testMonth[j])-1] #ditto if abs(new - old) > 3: #^means that there is a large difference and we need to scale old = 1.0 if old == 0.0 else old new = 1.0 if new == 0.0 else new factor = old / float(new) break if abs(factor) > 0.0003: #in case floating point error for j in range(len(reportData[i])): for k in range(len(reportData[i][j])): for l in range(1, len(reportData[i][j][k])): reportData[i][j][k][l] = factor*reportData[i][j][k][l] return reportData
def _validate_boolean(value): """Validate value is a float.""" if isinstance(value, str): value = value.lower() if value not in {True, False, "true", "false"}: raise ValueError("Only boolean values are valid.") return value is True or value == "true"
def safename(name): """Make name filesystem-safe.""" name = name.replace(u'/', u'-') name = name.replace(u':', u'-') return name
def isAncestorOf(ancestor, child): """Return True if `ancestor` is an ancestor of `child`, QObject-tree-wise.""" while child is not None: if child is ancestor: return True child = child.parent() return False
def args_from_id(id, arg_ranges): """Convert a single id number to the corresponding set of arguments""" args = list() for arg_range in arg_ranges: i = id % len(arg_range) id = id // len(arg_range) args.append(arg_range[i]) return tuple(args)
def get_summary_length(num_summarizers): """ Inputs: - summary: the summary Outputs: the summary length Purpose: to calculate the fifth truth value T5. This helps avoid long summaries that are not easily comprehensible by the human user """ return 2 * (0.5 ** num_summarizers)
def get_dict_path(base, path): """ Get the value at the dict path ``path`` on the dict ``base``. A dict path is a way to represent an item deep inside a dict structure. For example, the dict path ``["a", "b"]`` represents the number 42 in the dict ``{"a": {"b": 42}}`` """ path = list(path) level = path.pop(0) if path: return get_dict_path(base[level], path) return base[level]
def SQRT(number): """ Calculates the square root of a positive number and returns the result as a double. See https://docs.mongodb.com/manual/reference/operator/aggregation/sqrt/ for more details :param number: The number or field of number :return: Aggregation operator """ return {'$sqrt': number}
def _StripPC(addr, cpu_arch): """Strips the Thumb bit a program counter address when appropriate. Args: addr: the program counter address cpu_arch: Target CPU architecture. Returns: The stripped program counter address. """ if cpu_arch == "arm": return addr & ~1 return addr
def parse_bool(value): """Represents value as boolean. :param value: :rtype: bool """ if isinstance(value, bool): return value value = str(value).lower() return value in ('1', 'true', 'yes')
def objc_strip_extension_registry(lines): """Removes extensionRegistry methods from the classes.""" skip = False result = [] for line in lines: if '+ (GPBExtensionRegistry*)extensionRegistry {' in line: skip = True if not skip: result.append(line) elif line == '}\n': skip = False return result
def canonicalize_job_spec(job_spec): """Returns a copy of job_spec with default values filled in. Also performs a tiny bit of validation. """ def canonicalize_import(item): item = dict(item) if item.setdefault('ref', None) == '': raise ValueError('Empty ref should be None, not ""') return item result = dict(job_spec) result['import'] = [ canonicalize_import(item) for item in result.get('import', ())] return result
def pairWiseSwap(head): """ We dont need to change the references just swap the values of the next and the current node """ ptr = head while ptr and ptr.next: ptr.data, ptr.next.data = ptr.next.data, ptr.data ptr = ptr.next.next return head
def de_jong_step_a_function(transposed_decimal_pop_input): """De Jong Step - A Test Function""" y = [] for individual in transposed_decimal_pop_input: de_jong_step = 0 for xi in individual: de_jong_step = de_jong_step + abs(round(xi)) # (abs) was used to adjust the function for minimization y.append(de_jong_step) return y
def mili_to_standard(militaryTime): """Function to convert military time to Standard time. :param militaryTime: Military time in format HH:MM :type militaryTime: str :return: Standard time that was converted from the supplied military time :rtype: str """ # Handles formatting errors in the military time supplied if ':' not in militaryTime or len(militaryTime.split(':')) != 2: raise ValueError('militaryTime value must be supplied in the following format HH:MM') # Creates variables for the hours and minutes supplied by the user and interprets them as integers hour, minute = militaryTime.split(':') hour, minute = int(hour), int(minute) # handles errors in the supplied hour and minute of the military time if minute > 60: raise ValueError('Supplied minute value can not be greater than 60, you entered {}'.format(minute)) if hour > 24: raise ValueError('Supplied hour value can not be greater than 24, you entered {}'.format(hour)) # Determines weather the military time specified is AM or PM and converts it to standard time if hour > 12: ampm = 'PM' hour -= 12 else: ampm = 'AM' # Returns standard time to user return '{}:{}:{}'.format(hour, minute, ampm)
def is_keyed_tuple(obj): """Return True if ``obj`` has keyed tuple behavior, such as namedtuples or SQLAlchemy's KeyedTuples. """ return isinstance(obj, tuple) and hasattr(obj, '_fields')
def _parse_duration(duration: str) -> float: """ Convert string value of time (duration: "25:36:59") to a float value of seconds (92219.0) """ try: # {(1, "s"), (60, "m"), (3600, "h")} mapped_increments = zip([1, 60, 3600], reversed(duration.split(":"))) seconds = sum(multiplier * int(time) for multiplier, time in mapped_increments) return float(seconds) # ! This usually occurs when the wrong string is mistaken for the duration except (ValueError, TypeError, AttributeError): return 0.0
def frames_to_seconds(num_frames, frame_length, frame_step): """ compute the time given the frame number """ if num_frames == 0: return 0 return (num_frames - 1) * frame_step + frame_length
def generate_op_run_log(op_data): """Returns operator execution log.""" return 'device id={} op={}, ready={}, start={}, end={}\n'.format( op_data['p'], op_data['name'], op_data['ready_ts'], op_data['start_ts'], op_data['end_ts'])
def prime_factorization(n): """Return the prime factorization of `n`. Parameters ---------- n : int The number for which the prime factorization should be computed. Returns ------- dict[int, int] List of tuples containing the prime factors and multiplicities of `n`. """ # begin solution prime_factors = {} i = 2 while i**2 <= n: if n % i: i += 1 else: n /= i try: prime_factors[i] += 1 except KeyError: prime_factors[i] = 1 if n > 1: try: prime_factors[n] += 1 except KeyError: prime_factors[n] = 1 return prime_factors # end solution
def adding_two_numbers(number_1,number_2): """ This function returns the sum of two numbers. PARAMETERS; number_1: float, takes in the first numbber to sum; number_2: float, takes in the second number to sum; RETURN TYPE; The return type should be in float. EXAMPLE: add(7,7) """ total_sum = number_1 + number_2 return total_sum
def to_bytearray(value): """ Convert hex to byte array """ if value and isinstance(value, str): value = bytearray.fromhex(value) return value
def isint(val): """ check if the entry can become an integer (integer or string of integer) Parameters ---------- val an entry of any type Returns ------- bool True if the input can become an integer, False otherwise """ try: int(val) return True except ValueError: return False
def generate_status_bar(percent: float, img_size: int): """ take a percent and create a progress bar :param percent: percent complete :param img_size: size of the image MB :return: progress bar """ bar_length = 50 number_bars = round((int(str(percent).split(".")[0])) / (100 / bar_length)) # calculate number of bars progress_bar = "[" current_write = img_size * (percent / 100) for i in range(number_bars): if i == number_bars - 1: progress_bar += ">" else: progress_bar += "=" for i in range(bar_length - number_bars): progress_bar += " " return progress_bar + "] " + \ str(round(percent)) + "% - " + str(round(current_write)) + "/" + str(img_size) + " MB Written"
def porcentage(number, porc): """This function will return the porcentage plus the value. Args: number (int/float): value porcentage (int/float): porcentage quantity """ return number + (number * (porc / 100))
def hparams_power(hparams): """Some value we want to go up in powers of 2 So any hyper param that ends in power will be used this way. """ hparams_old = hparams.copy() for k in hparams_old.keys(): if k.endswith("_power"): k_new = k.replace("_power", "") hparams[k_new] = int(2 ** hparams[k]) return hparams
def tweakObject(obj): """ Takes as input an object and returns a list of synonyms - Input: * obj (string) - Output: * tweakedObj (list of strings) """ tweakedObj = [obj] if obj == 'bell_pepper': tweakedObj = ['bell pepper'] elif obj == 'cup': tweakedObj = ['cup', 'mug'] elif obj == 'pot': tweakedObj = ['pot', 'saucepan'] elif obj == 'eating_utensil': tweakedObj = ['eating utensil', 'knife', 'spoon', 'fork'] elif obj == 'cooking_utensil': tweakedObj = ['cooking utensil', 'knife', 'scissors', 'peeler', 'scale', 'jug', 'colander', 'strainer', 'blender'] elif obj == 'fridge_drawer': tweakedObj = ['fridge drawer', 'refrigerator drawer'] elif obj == 'cutting_board': tweakedObj = ['cutting board', 'cut board', 'chopping board', 'chop board'] elif obj == 'cheese_container': tweakedObj = ['cheese container', 'cheese recipient', 'cheese package'] elif obj == 'oil_container': tweakedObj = ['oil container', 'oil recipient', 'oil bottle'] elif obj == 'bread_container': tweakedObj = ['bread container', 'bread recipient', 'bread package'] elif obj == 'grocery_bag': tweakedObj = ['grocery bag', 'groceries'] elif obj == 'seasoning_container': tweakedObj = ['seasoning container', 'seasoning recipient', 'seasoning bottle', 'seasoning package'] elif obj == 'condiment_container': tweakedObj = ['condiment container', 'condiment recipient', 'condiment bottle'] elif obj == 'tomato_container': tweakedObj = ['tomato container', 'tomato recipient'] elif obj == 'fridge': tweakedObj = ['fridge', 'refrigerator'] elif obj == 'paper_towel': tweakedObj = ['paper towel', 'tissue', 'kitchen paper', 'kitchen towel'] elif obj == 'cabinet': tweakedObj = ['cabinet', 'locker', 'cupboard'] return tweakedObj
def life_counter(field): """ returns quanity of living squares """ hype = 0 for y in range(len(field)): for x in range(len(field[y])): if field[y][x] == 0: hype += 1 return hype