content
stringlengths
42
6.51k
def _get_dev_port_var(backend, instance=None): """Return the environment variable for a backend port. Backend ports are stored at GET_PORT_<backend> for backends and GET_PORT_<backend>.<instance> for individual instances. Args: backend: The name of the backend. instance: The backend instance (optional...
def match_gene_txs_variant_txs(variant_gene, hgnc_gene): """Match gene transcript with variant transcript to extract primary and canonical tx info Args: variant_gene(dict): A gene dictionary with limited info present in variant.genes. contains info on which transcript is canonic...
def add_previous_traffic(index, incidents): """Adds traffic level for the preceeding hour to the incident""" incidents[index]['previous_traffic'] = [incident['traffic_level'] for incident in reversed(incidents[index-6:index])] return incidents[index]
def get_locs(r1, c1, r2, c2): """Get ndarray locations of given bounds.""" rs = [] cs = [] for r in range(r1, r2 + 1): for c in range(c1, c2 + 1): rs.append(r) cs.append(c) return rs, cs
def dimorphism_trunc(_): """Enrich the match.""" data = {'dimorphism': 'sexual dimorphism'} return data
def product(l1, l2): """returns the dot product of l1 and l2""" return sum([i1 * i2 for (i1, i2) in zip(l1, l2)])
def scopes_to_string(scopes): """Converts scope value to a string. If scopes is a string then it is simply passed through. If scopes is an iterable then a string is returned that is all the individual scopes concatenated with spaces. Args: scopes: string or iterable of strings, the scopes. Returns: ...
def _warp_dir(intuple): """ Extract the ``restrict_deformation`` argument from metadata. Example ------- >>> _warp_dir(("epi.nii.gz", {"PhaseEncodingDirection": "i-"})) [[1, 0, 0], [1, 0, 0]] >>> _warp_dir(("epi.nii.gz", {"PhaseEncodingDirection": "j-"})) [[0, 1, 0], [0, 1, 0]] ""...
def build_complement(dna): """ :param dna: str, a DNA sequence that users inputs. :return: str, the complement DNA sequence of dna. """ ans = '' for base in dna: if base == 'A': ans += 'T' if base == 'T': ans += 'A' if base == 'C': ans ...
def splittime(datetime_str=None, level=1): """Split a timeString :param date_str: The ISO date string YYYY-DD-MM[ HH:MM:SS.UUU] :param level: A value between 1 & 3 determining which part to remove - date parts removed are replaced with '00 microsecond part is ALWAYS removed ' ...
def sliding_average(arr, k): """Find slinding averages of window size k for the elements of arr. Time: O(n) Space: O(1) """ averages = [] win_start = 0 win_sum = 0 for win_end in range(len(arr)): win_sum += arr[win_end] if win_end >= k - 1: averages.append(w...
def ngrams(text, n=3): """Return list of text n-grams of size n""" return {text[i:i + n].lower() for i in range(len(text) - n + 1)}
def _vcf_info(start, end, mate_id, info=None): """Return breakend information line with mate and imprecise location. """ out = "SVTYPE=BND;MATEID={mate};IMPRECISE;CIPOS=0,{size}".format( mate=mate_id, size=end-start) if info is not None: extra_info = ";".join("{0}={1}".format(k, v) for k...
def off_signal(obj, signal_type, func): """Disconnect a callback function from a signal.""" try: # Disconnect from blocked functions not the temporary fake signal type used when blocked if "blocked-" + signal_type in obj.event_signals: sig = obj.event_signals["blocked-" + signal_type...
def format_percent(d, t): """ Format a value as a percent of a total. """ return '{:.1%}'.format(float(d) / t)
def replace_in_keys(src, existing='.', new='_'): """ Replace a substring in all of the keys of a dictionary (or list of dictionaries) :type src: ``dict`` or ``list`` :param src: The dictionary (or list of dictionaries) with keys that need replacement. (required) :type existing: ``s...
def spanish_to_english(dictionary, word): """Translates a Spanish word to English. Current version this function is incapable of parsing translation data within a metadata dict (see txt_to_dict documentation). :param dict[str, str] dictionary: Keys are an English word and the value is the resp...
def avg_guesses_smart(n): """ computes the avg. nr. of optimal-strategy guesses needed with n words >>> avg_guesses_naive(100) - avg_guesses_smart(100) 0.0 """ if n == 1: return 1 pow2, k, sum_pow2, sum_guesses = 1, 1, 1, 1 while True: rest = n - sum_pow2 pow2 *=...
def binary_search1(xs, x): """ Perform binary search for a specific value in the given sorted list :param xs: a sorted list :param x: the target value :return: an index if the value was found, or None if not """ lft, rgt = 0, len(xs) while lft < rgt: mid = (lft + rgt) // 2 ...
def swap_namedtuple_dict(d): """ Turn {a:namedtuple(b,c)} to namedtuple({a:b},{a:c}) """ if not isinstance(d, dict): return d keys = list(d.keys()) for k, v in d.items(): assert v._fields == d[keys[0]]._fields fields = d[keys[0]]._fields t = [] for i in range(len(...
def make_payment(text): """Simply returns the args passed to it as a string""" return "Made Payment! %s" % str(text)
def luminance_to_contrast_ratio(luminance1, luminance2): """Calculate contrast ratio from a pair of relative luminance. :param luminance1: Relative luminance :type luminance1: float :param luminance2: Relative luminance :type luminance2: float :return: Contrast ratio :rtype: float """ ...
def expand_dict_lists(d): """Neat little function that expands every list in a dict. So instead of having one dict with a list of 5 things + a list of 3 things, you get a list of 5x3=15 dicts with each dict representing each possible permutation of things. :param d: Dictionary that can contain some...
def get_version_without_patch(version): """ Return the version of Kili API removing the patch version Parameters ---------- - version """ return '.'.join(version.split('.')[:-1])
def return_node_position(node_index): """Conversion of node_index to position tuple :param node_index: id of respective node :type: int """ return (node_index, None, None)
def verify_rename_files(file_name_map): """ Each file name as key should have a non None value as its value otherwise the file did not get renamed to something new and the rename file process was not complete """ verified = True renamed_list = [] not_renamed_list = [] for k, v in lis...
def charCodeForNumber(i): """ Returns a for 0, b for 1, etc. """ char = "" while(i > 25): char += chr(97 + (i % 25)) i = i - 25 char += chr(97 + i) return char
def split(l, sizes): """Split a list into sublists of specific sizes.""" if not sum(sizes) == len(l): raise ValueError('sum(sizes) must equal len(l)') sub_lists = [] ctr = 0 for size in sizes: sub_lists.append(l[ctr:ctr+size]) ctr += size return sub_lists
def hsv_to_rgb(hue, sat, val): """ Convert HSV colour to RGB :param hue: hue; 0.0-1.0 :param sat: saturation; 0.0-1.0 :param val: value; 0.0-1.0 """ if sat == 0.0: return (val, val, val) i = int(hue * 6.0) p = val * (1.0 - sat) f = (hue * 6.0) - i ...
def longest_bar_len(bars_in_frames): """ DEPRECATED Returns the size of the longest bar among all, in number of frames. Parameters ---------- bars_in_frames : list of tuples of integers The bars, as tuples (start, end), in number of frames. Returns ------- max_len : integer...
def get_feature_suffix(feature_name: str) -> str: """Gets the suffix of a feature from its name.""" if "_" not in feature_name: return "" return feature_name.split("_")[-1]
def get_non_empty_text_from_doc(doc) -> str: """ Build document text from title + abstract :param doc: S2 paper :return: Document text """ text = '' if 'title' in doc: text += doc['title'] if doc['abstract']: text += '\n' + doc['abstract'] if doc['body...
def factorial(n: int) -> int: """ Recursion function. >>> factorial(0) 1 >>> factorial(1) 1 >>> factorial(5) 120 >>> factorial(6) 720 """ return 1 if n == 0 or n == 1 else n * factorial(n - 1)
def c_sum32(*args): """ Add all elements of *args* within the uint32 value range. >>> c_sum32(0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF) 4294967293 """ return sum(args) & 0xFFFFFFFF
def sort_return_tuples(response, **options): """ If ``groups`` is specified, return the response as a list of n-element tuples with n being the value found in options['groups'] """ if not response or not options['groups']: return response n = options['groups'] return list(zip(*[respo...
def joinSet(itemSet, length): """Join a set with itself and returns the n-element itemsets""" return set([i.union(j) for i in itemSet for j in itemSet if len(i.union(j)) == length])
def _is_int_expression(s): """ copied from https://qiita.com/agnelloxy/items/137cbc8651ff4931258f """ try: int(s) return True except ValueError: return False
def get_atoms_per_fu(doc): """ Calculate and return the number of atoms per formula unit. Parameters: doc (list/dict): structure to evaluate OR matador-style stoichiometry. """ if 'stoichiometry' in doc: return sum([elem[1] for elem in doc['stoichiometry']]) return sum([elem[1] for...
def convert_datastores_to_hubs(pbm_client_factory, datastores): """Convert given datastore morefs to PbmPlacementHub morefs. :param pbm_client_factory: Factory to create PBM API input specs :param datastores: list of datastore morefs :returns: list of PbmPlacementHub morefs """ hubs = [] fo...
def fmt_msg(event, payload=None, serial=None): """ Packs a message to be sent to the server. Serial is a function to call on the frame to serialize it, e.g: json.dumps. """ frame = { 'e': event, 'p': payload, } return serial(frame) if serial else frame
def trimText(message): """ This functions cleans the string It removes all the characters without A-Z, a-z :param message: The string which I want to trim :return: returns a string """ trimmed_text = [] for i in range(len(message)): if 'A' <= message[i] <= 'Z'...
def cmake_cache_entry(name, value): """ Helper that creates CMake cache entry strings used in 'host-config' files. """ return 'set({0} "{1}" CACHE PATH "")\n\n'.format(name, value)
def distL1(x1,y1, x2,y2): """Compute the L1-norm (Manhattan) distance between two points. The distance is rounded to the closest integer, for compatibility with the TSPLIB convention. The two points are located on coordinates (x1,y1) and (x2,y2), sent as parameters""" return int(abs(x2-x1) + abs(y2-y1)+.5...
def sqrt(target): """ Find the square root of the given number If the square root is not an integer, the next lowest integer is returned. If the square root cannot be determined, None is returned. :param target: The square :return: int or None """ # Explicitly handle the edge-cases he...
def fact(n): """doc""" # r : Number r = 1 # i : int i = 2 while i <= n: r = r * i i = i + 1 print("i="+str(i)) return r
def fields_to_batches(d, keys_to_ignore=[]): """ The input is a dict whose items are batched tensors. The output is a list of dictionaries - one per entry in the batch - with the slices of the tensors for that entry. Here's an example. Input: d = {"a": [[1, 2], [3,4]], "b": [1, 2]} Output: r...
def extractLeafs(nt, leafDict): """Given a newick tree object, it returns a dict of leaf objects. Operates recursively. """ if nt is None: return None nt.distance = 0 if nt.right is None and nt.left is None: leafDict[nt.iD] = True else: extractLeafs(nt.right, leafDict...
def Usable(entity_type, entity_ids_arr): """For a MSVC solution file ending with .sln""" file_path = entity_ids_arr[0] return file_path.endswith(".sln")
def subs(task, key, val): """ Perform a substitution on a task Examples -------- >>> subs((inc, 'x'), 'x', 1) # doctest: +SKIP (inc, 1) """ type_task = type(task) if not (type_task is tuple and task and callable(task[0])): # istask(task): try: if type_task is type...
def quote(string: str) -> str: """ Wrap a string with quotes iff it contains a space. Used for interacting with command line scripts. :param string: :return: """ if ' ' in string: return '"' + string + '"' return string
def make_divisible(v, divisor=8, min_value=None): """ make `v` divisible """ if min_value is None: min_value = divisor new_v = max(min_value, int(v + divisor/2) // divisor * divisor) # Make sure that round down does not go down by more than 10% if new_v < 0.9 * v: new_v += di...
def square(n): """Returns the square of a number.""" squared = n ** 2 print ("%d squared is %d." % (n, squared)) return squared
def jaccard_similarity(query, document): """Not used for now""" intersection = set(query).intersection(set(document)) union = set(query).union(set(document)) return len(intersection)/len(union)
def is_podcast_episode_id(item_id): """Validate if ID is in the format of a Google Music podcast episode ID.""" return len(item_id) == 27 and item_id.startswith('D')
def _xypointlist(a): """formats a list of xy pairs""" s = '' for e in a: # this could be done more elegant s += str(e)[1:-1] + ' ' return s
def factorial_dp(n): """Nth number of factorial series by bottom-up DP. - Time complexity: O(n). - Space complexity: O(n). """ T = [0 for _ in range(n + 1)] T[0] = 1 T[1] = 1 for k in range(2, n + 1): T[k] = k * T[k - 1] return T[n]
def is_array_like(item): """ Checks to see if something is array-like. >>> import numpy as np >>> is_array_like([]) True >>> is_array_like(tuple()) True >>> is_array_like(np.ndarray([])) True >>> is_array_like("hello") False >>> is_array_like(1) False >>> is_arr...
def update_or_add_message(msg, name, sha): """ updates or builds the github version message for each new asset's sha256. Searches the existing message string to update or create. """ new_text = '{0}: {1}\n'.format(name, sha) start = msg.find(name) if (start != -1): end = msg.find(...
def _GetIndentedString(indentation, msg): """ Return `msg` indented by `indentation` number of spaces """ return ' ' * indentation + msg
def unsplit(f): """ join a list of strings, adds a linefeed """ ln = "" for s in f: ln = "%s %s" % (ln, s) ln = ln + "\n" return ln
def teste(area): """Rederizando uma view com o decorador do jinja.""" return dict(nome=area)
def _get_domain(email): """Get the domain of an email address (eg. gmail.com in hello@gmail.com) """ comps = email.split("@") if len(comps) != 2: return None return comps[1]
def formula2components(formula): """Convert a glass/any composition formula to component dictionary. Parameters ---------- formula : string Glass/any composition for e.g. 50Na2O-50SiO2. Returns ------- dictionary Dictionary where keys are components of glass/any composition...
def duration_formatted(seconds, suffixes=['y','w','d','h','m','s'], add_s=False, separator=' '): """ Takes an amount of seconds (as an into or float) and turns it into a human-readable amount of time. """ # the formatted time string to be returned time = [] # the pieces of time to iterate over...
def style_category(category): """Return predefined Boostrap CSS classes for each banner category.""" css_class = "alert alert-{}" if category == "warning": css_class = css_class.format("warning") elif category == "other": css_class = css_class.format("secondary") else: css_cl...
def create_api_host_url(host, endpoints): """ create_api_host_url Creates the endpoint url for the API call. INPUTS @host [str]: The base URL for the API call. @endpoints [list]: The API endpoint names for the chosen method RETURNS @api_url [str]: The full endpoint url for the method....
def calculate_single_gpa(score): """ Calculate gpa with a score. Use a lookup table to calculate a single gpa. Empty scores or scores not between 0 and 100 will be regarded as 0. """ lookup_table = [0.0] * 60 + [1.0] * 4 + [1.5] * 4 + [2.0] * 4 + \ [2.3] * 3 + [2.7] * 3 + [3.0] * 4 + [3...
def fixedsplit(text, separator=None, maxsplit=-1): """Split a string and return a fixed number of parts""" parts = text.split(separator, maxsplit) maxparts = maxsplit + 1 missing = maxparts - len(parts) if missing > 0: parts = parts + (missing * [""]) return parts
def stationary(t): """Probe is stationary at location h = 2, v = 0""" return 0.*t, 2/16 + 0*t, 0*t
def check_permutation(s, t): """ Check if s and t are permutations of each other Check if each character in s is in t this solution is incorrect because there can be a situation when s and t are the same length but have different number of a character. Ex. aarp != arrp but efficiency is O(...
def norm_angle(a): """Return the given angle normalized to -180 < *a* <= 180 degrees.""" a = (a + 360) % 360 if a > 180: a = a - 360 return a
def valid_operation(x: str) -> bool: """ Whether or not an opcode is valid :param x: opcode :return: whether or not the supplied opcode is valid """ return not x.startswith("__") and not x == "bytecode_format"
def name_of_variable(var): """Return the name of an object""" for n,v in globals().items(): print(n) if id(v) == id(var): return n return None
def count_digits(n: int) -> int: """Counts the digits of number in base 10. Args: n: A non-negative integer. Returns: The number of digits in the base-10 representation of ``n``. """ return len(str(n))
def itofm(i): """Converts midi interval to frequency multiplier.""" return 2 ** (i / 12.0)
def is_year_leap(year): """Checks if year is leap, and returns result""" if year % 4 == 0 and year % 100 != 0 or year % 400 == 0: return True else: return False
def _validate_dataset_id(dataset_id, parent): """Ensure the dataset ID is set appropriately. If ``parent`` is passed, skip the test (it will be checked / fixed up later). If ``dataset_id`` is unset, attempt to infer the ID from the environment. :type dataset_id: string :param dataset_id: A da...
def start_point(upper_int): """ Get the circle that this element is in, and its first elem """ n, last, start = 1, 1, 2 while start < upper_int: last = start start = (4*pow(n, 2)) + (4*n) + 2 n += 1 return (last, n)
def if_not_null(data, f): """ Execute the given function if the data is not null :param data: :param f: :return: f(data) if data != None, else None """ if data: return f(data) return None
def make_initial_state(supporters): """ Creates a string of alternating Tottenham(T) and Arsenal(A) supporters of length 'supporters' with two blank seats represented by two underscores at the end of the string. make_initial_state(int) -> str """ return "TA"*supporters + "__"
def isIn(char, aStr): """ char: a single character aStr: an alphabetized string returns: True if char is in aStr; False otherwise """ if len(aStr) <= 1: return char == aStr middle_index = len(aStr) // 2 middle_char = aStr[middle_index] if char == middle_char: return ...
def _get_rekey_ddi_data(ddi_data): """Takes a list of lists of dict's and converts to a list of dict's, of dicts. As well as rekey's the dict's with the network address.""" for enum, item in enumerate(ddi_data): ddi_data[enum] = dict((d['network'], dict(d, index=index...
def find_nested_key(my_json, find_key): """Search in a nested dict for a key or None.""" if find_key in my_json: return my_json[find_key] for _, vval in my_json.items(): if isinstance(vval, dict): item = find_nested_key(vval, find_key) if item is not None: ...
def parse_name(name): """ extract the important stuff from the array filename. Returning the parent image the file is from. Parameters: ------------ name: string file path of the numpy array Returns: --------- string: e.g "MCF7_img_13_90.npy" will return...
def _self_interactions(num_qubits): """Return the indices corresponding to the self-interactions.""" interactions = [] for qubit in range(num_qubits): for pindex in range(1, 4): term = [0] * num_qubits term[qubit] = pindex interactions.append(tuple(term)) retu...
def convert(s, numRows): """ :type s: str :type numRows: int :rtype: str """ if len(s) <= 0 or len(s) <= numRows or numRows == 1: return s list = {} row = 0 add = True for i in range(len(s)): s1 = '' if row in list: s1 = list[row] list[...
def cleanup_code(content): """Automatically removes code blocks from the code.""" # remove ```py\n``` if content.startswith('```') and content.endswith('```'): return '\n'.join(content.split('\n')[1:-1]) return content.strip('` \n')
def derive_param_default(obj_param): """Derive a parameter default Parameters ---------- obj_param : dict * parameter dict from TaniumPy object Returns ------- def_val : str * default value derived from obj_param """ # get the default value for this param if it exis...
def inverse_hybrid_transform(value): """ Transform back from the IRAF-style hybrid log values. This takes the hybrid log value and transforms it back to the actual value. That value is returned. Unlike the hybrid_transform function, this works on single values not a numpy array. That is because ...
def fast_exponentiation(a, p, n): """Calculates r = a^p mod n """ result = a % n remainders = [] while p != 1: remainders.append(p & 1) p = p >> 1 while remainders: rem = remainders.pop() result = ((a ** rem) * result ** 2) % n return result
def float_repr(value, precision_digits): """Returns a string representation of a float with the the given number of fractional digits. This should not be used to perform a rounding operation (this is done via :meth:`~.float_round`), but only to produce a suitable string representation fo...
def filestorage_to_binary(file_list): """ Transform a list of images in Flask's FileStorage format to binary format. """ binary_list = [] for f in file_list: binary_list.append(f.read()) return binary_list
def strip_suffixes(s, suffixes): """ Helper function to remove suffixes from given string. At most, a single suffix is removed to avoid removing portions of the string that were not originally at its end. :param str s: String to operate on :param iter<str> tokens: Iterable of suffix strings ...
def in_ranges(value, ranges): """Check if a value is in a list of ranges""" return all(low <= value <= high for low, high in ranges)
def find_greater_numbers(nums): """Return # of times a number is followed by a greater number. For example, for [1, 2, 3], the answer is 3: - the 1 is followed by the 2 *and* the 3 - the 2 is followed by the 3 Examples: >>> find_greater_numbers([1, 2, 3]) 3 >>> find_great...
def fields_string(field_type, field_list, sep): """Create an error string for <field_type> field(s), <field_list>. <sep> is used to separate items in <field_list>""" indent = ' '*11 if field_list: if len(field_list) > 1: field_str = "{} Fields: ".format(field_type) else: ...
def disorder_rate(values): """i.e. Inversion count calculation""" dr = 0 for i in range(len(values)-1): for j in range(i+1,len(values)): if values[i] > values[j]: dr += 1 return dr
def clamp(value: float, mini: float, maxi: float) -> float: """ it clamps a value between mini and maxi :param value: the value that will be clamped :param mini: the floor value :param maxi: the ceil value :type value: float :type mini: float :type maxi: float :return: Union[int, flo...
def collatz_seq(start): """ Algorithm returning whole Collatz sequence starting from a given interger. """ n = start seq = [start] while n > 1: if n % 2 == 0: n = n // 2 seq.append(n) else: n = (n * 3 + 1) // 2 seq.extend([n * 2, n]...
def taille(arbre): """Fonction qui renvoie la taille d'un arbre binaire""" if arbre is None: return 0 tg = taille(arbre.get_ag()) td = taille(arbre.get_ad()) return tg + td + 1