content
stringlengths
42
6.51k
def get_return_data_type(func_name): """Return a somewhat-helpful data type given a function name""" if func_name.startswith('get_'): if func_name.endswith('_list'): return 'List' elif func_name.endswith('_count'): return 'Integer' return ''
def smarter_nestify(l, record): """adapted from: http://stackoverflow.com/questions/37014500/how-to-use-recursion-to-nest-dictionaries-while-integrating-with-existing-record """ if len(l) == 2: key = l[0] value = l[1] return {key: value} else: key = l[0] reco...
def normalize_port(port): """Normalize a port into a number or false.""" if port is None: return False try: return int(port) except ValueError: return False
def to_sqlite3_float(x): """Identical to Python 'float', maps 'x' onto an 8-byte IEEE floating point number. """ # TO DO: this might need more work to do the right thing at the boundaries # and with infinity values, see 'sys.float_info'; seems to work return float(x)
def is_Out_of_Range(x, keys, params): """ Returns a Boolean type indicating whether the current point is within the range Parameters ---------- x : tuple the current point in the hyperspace to be checked keys: list each correspond to a dimension in the hyperspace, ...
def get_session_ids(project_dict): """Gets the relevant session ids from the project_dict Parameters ---------- project_dict: dict A dictionary containing all the project's json values Returns ------- session_id_dict: dict a dict of the session ids and directories used by the proj...
def print_run_result(r, success_msg=''): """print the stdour & stderr when return code is non-zero.""" if r[0]: s1 = '\n'.join(r[1]) s2 = '\n'.join(r[2]) if s1 or s2: print('%s' % '\n'.join([s1, 'Error:', s2])) elif success_msg: print('%s' % success_msg) retur...
def return_stats(job): """Collect various stats into a dictionary""" stats = {"isDone": job["isDone"], "doneProgress": float(job["doneProgress"])*100, "scanCount": int(job["scanCount"]), "eventCount": int(job["eventCount"]), "resultCount": int(job["resultCo...
def map_type_list_field(old_type): """ This function maps the list type into individual field type which can contain the individual values of the list. Mappings - list:reference <table> --> refererence <table> - list:integer --> integer - list:string --> string ...
def isBogusAddress(addr): """ Returns true if the given address is bogus, i.e. 0.0.0.0 or 127.0.0.1. Additional forms of bogus might be added later. """ if addr.startswith('0.') or addr.startswith('127.'): return True return False
def read_GameOfLife(pattern, origin=(0,0), alive='O'): """Reads a pattern and return its set of live cells.""" universe = set() for y,row in enumerate(reversed(pattern)): for x,cell in enumerate(row): if cell == alive: universe.add((origin[0]+x, origin[1]+y)) return universe
def get_dictionary(key, resources): """Return a new dictionary using the given key and resources (key value). Keyword arguments: key -- the key to use in the dictionary resources -- the resources to use as the key value """ return { key: resources, }
def endswith(s, suffix): """ True if the string ends with the specified suffix. """ return s.endswith(suffix)
def create_address_argument(ports, use_ipv6=False): """ >>> create_address_argument([8080, 8081]) '"127.0.0.1:8080,127.0.0.1:8081"' >>> create_address_argument([8080, 8081]) '"[::1]:8080,[::1]:8081"' """ is_first = True argument = '"' address = '127.0.0.1' if use_ipv6: ad...
def dot_product(d1, d2, default_value=0): """Calcualte the dot product for the intersection of two dictionary objects. If the key does not exist in d2, default_value is used instead. """ return sum(map(lambda x: float(d1[x]) * float(d2.get(x, default_value)), d1.keys()))
def _split_choices(choices_string): """ Riceve una stringa e la splitta ogni ';' creando una tupla di scelte """ str_split = choices_string.split(';') choices = tuple((x, x) for x in str_split) return choices
def sin2tan(sin: float) -> float: """returns Tan[ArcSin[x]] assuming -pi/2 < x < pi/2.""" return sin * ((-sin + 1) * (sin + 1)) ** (-0.5)
def valFromPercent(percentage, total): """ Returns the value that percentage represents in terms of total. """ return total * percentage / 100.0
def splitdoc(doc): """Split a doc string into a synopsis line (if any) and the rest.""" lines = doc.strip().split('\n') if len(lines) == 1: return lines[0], '' elif len(lines) >= 2 and not lines[1].rstrip(): return lines[0], '\n'.join(lines[2:]) return '', '\n'.join(lines)
def limit_string(string, ls2): """impose minimal and maximal lengths of string. NB maxlen = 0 indicate there is no max length (not that the max is zero) """ assert len(ls2) == 2 ,'specifier v should be a 2 member list' minlen = ls2[0] maxlen = ls2[1] assert minlen >= 0 assert maxlen >= ...
def _utf8(s): """Decodes an str to unicode.""" if s is None: return s return s.decode('utf-8')
def is_up(line): """ Returns True if the interface is up, False if it's down, and None if there is not enuough information present to determine whether it's up or down """ if "UP" in line: return True if "DOWN" in line: return False return None
def round_even(n): """Round a number to the nearest even integer.""" r = int(n) return r + 1 if r & 1 else r
def get_suitable_int_type(upper: int, lower: int = 0) -> str: """Returns the suitable integer type with the least bits. Returns the integer type that can hold all values between max_val and min_val (inclusive) and has the least bits. Args: max_val: Maximum value that needs to be valid. min_val: Minimu...
def to_M(logres, base = -6): """ converts to molar with the given base """ return (10**logres) * (10**(-base))
def rough_color_distance(col1, col2): """Same as color_distance, but without the square root. Doesn't give exact distance value, but is good enough to compare different distances. Args: col1: First colour to compare. col2: Second colour to compare. Returns: Union[ :obj:`int`, :obj:...
def getoutpath(filepath,ftype,num="0000"): """get the output path for the tiles""" a = filepath.rindex("\\") b = filepath.rindex(".") filename = filepath[a:b] if ftype == "raw": outpath = filepath[:a] + "\\.previews\\" + str(num) else: outpath = filepath[:a] + "\\.previews\\" + f...
def is_value_name_applicable(buckets_names, value_name): """ Returns True if the given value name is AltFS applicable. Otherwise, returns False """ return value_name[:-5] in buckets_names and value_name[-5] == "." and \ all([char.isdigit() for char in value_name[-4:]])
def apply_npi_effectiveness(mixing_params, npi_effectiveness): """ Adjust the mixing parameters according by scaling them according to NPI effectiveness :param mixing_params: dict Instructions for how the mixing matrices should vary with time, including for the baseline :param npi_effectiveness:...
def compare_lists(list1, list2): """ Compare two lists of strings, showing the first mismatch. Return the index of the first mismatched lines, or None if identical. """ import itertools it = itertools.zip_longest(list1, list2, fillvalue='Missing!') for i, (s1, s2) in enumerate(it): ...
def generate_early_stop_file_name(file_prefix, net_number): """ Generate file name and suffix for EarlyStopHistory-file (.pth). """ return f"{file_prefix}-early-stop{net_number}.pth"
def remove_char(s): """ It's pretty straightforward. Your goal is to create a function that removes the first and last characters of a string. You're given one parameter, the original string. You don't have to worry with strings with less than two characters. :param s: original string input. :return...
def to_bytes(text, encoding: str = "utf-8", errors: str = "strict"): """Return the binary representation of `text`. If `text` is already a bytes object, return it as-is.""" if not text: return b"" if isinstance(text, bytes): return text return text.encode(encoding, errors)
def get_varname_Nd(fromNd, toNd): """ returns variable name of N_x<dy. :param fromNd: :param toNd: :return: """ if fromNd > 0: varNameN = 'N%d_d_%d' % (fromNd, toNd) else: varNameN = 'Nd_%d' % toNd return varNameN
def normalize_title(title, opt_title): """Return a string with that contains the title and opt_title if it's not the empty string See test_normalize_title() for usage """ if opt_title is not "": title = opt_title + " - " + title return title
def exponential_annealing(step, start_value, end_value, decay_rate, num_steps_decay_rate): """Bridges the gap between start_value and end_value exponentially.""" progress = decay_rate**(step / num_steps_decay_rate) return end_value + (start_value - end_value) * progress
def str_to_dec(string): """ Convert a string into decimal value >>> print (str_to_dec("123")) 123 >>> print (str_to_dec("0123")) 123""" string = string.lstrip("0") if len(string) == 0: return 0 else: return eval(string)
def _gf2bitlength_linear(a): """ Computes the length of a polynomial coefficient bit vector = degree + 1. Parameters ---------- a : integer Polynomial coefficient bit vector. Returns ------- n : integer length of polynomial `a`. """ n = 0 while a ...
def solve_parts(parts, key, substitution): """ Solve the place holders from the parts. :param parts: the parts :type parts: list[str] :param key: the name of the place holder :type key: str :param substitution: the value of the place holder :type substitution: str :return: the solve...
def standardize_dir(f_dir): """ replace all '\' with '/' make sure dir ends with '/' """ f_dir = (f_dir.strip(' \n') .replace('\\', '/') .lower()) if not f_dir.endswith('/'): f_dir += '/' return f_dir
def ini_conf_to_bool(value): """ Depending INI file interpreter, False values are simple parsed as string, so use this function to consider them as boolean :param value: value of ini parameter :return: bollean value """ if value in ('False', 'false', '0', 'off', 'no'): return False ...
def get_filters(filters): """ Get Globus Search filters for each facet. Currently only supports "match_all". :param filters: A dict where the keys are filters and the values are a list of elements to filter on. :return: a list of formatted filters ready to send off to Globus Search Example...
def dot_prod(a,b): """ This function takes two vectors, a and b, and finds the dot product,c. """ c = a[0]*b[0] + a[1]*b[1] + a[2]*b[2] return(c)
def any_keys_in_dict(in_dict, keys): """ Check that at least one key is present in a dictionary. Args: in_dict (dict): Input dict. keys (list): Keys that can be present in ``in_dict``. Returns: True if at least one key in ``keys`` is in ``in_dict``, False ...
def get_nearest(v, l): """ Returns the index of the nearest value in a list """ for i in range(len(l)): if l[i] < v: prev = l[i - 1] prevDiff = prev - v curr = l[i] currDiff = v - curr if prevDiff < currDiff: return i...
def _coerce_params(params): """Force xgboost parameters into appropriate types The output from hyperopt is always floats, but some xgboost parameters explicitly require integers. Cast those as necessary Parameters ---------- params : dict xgboost parameters Returns ------- ...
def coding_problem_44(arr): """ We can determine how "out of order" an array A is by counting the number of inversions it has. Two elements A[i] and A[j] form an inversion if A[i] > A[j] but i < j. That is, a smaller element appears after a larger element. Given an array, count the number of inversions ...
def power_of_2(number: int) -> bool: """ Check whether this number is a power of 2 :param number: int :return: True or False if it is a power of 2 """ return ((number - 1) & number == 0) and not number == 0
def join3(joiner, s1, s2, s3): """ >>> join3.cmd(", 1 2 3") '1,2,3' >>> join3.cmd(["-", "a", "b", "cdef"]) 'a-b-cdef' >>> join3.cmd("insufficient args") Traceback (most recent call last): ... SystemExit: 2 """ return joiner.join([s1, s2, s3])
def determina_netmask_dec(netmask_binar): """ Ia netmask-ul in format binar si il transforma in decimal :param (str) netmask_binar: :return (str) netmask_dec: formatat in decimal """ nums = netmask_binar.split(".") netmask_dec = "" for num in nums: netmask_dec += str(i...
def _get_connect_string(backend, user, passwd, database=None, variant=None): """Forms a sqlalchemy database uri string for the given values.""" if backend == "postgres": if not variant: variant = 'psycopg2' backend = "postgresql+%s" % (variant) elif backend == "mysql": if...
def add_pic(num): """ adds appropriate picture tags and marks the picture number :input: picture number (int) """ return '<figure>\n\t<center><img class=\"materialboxed responsive-img\" src =\"/assets/pic_folder/pic_{}\" alt=\"picture {}\" style=\"max-width: 95%;\"><figcaption></figcapt...
def find_sublist_containing(el, lst, index=False): """ Parameters ---------- el : The element to search for in the sublists of `lst`. lst : collections.Sequence A sequence of sequences or sets. index : bool, default: False If False (default), the subsequence or subset co...
def role_doc_entry(role_name, local_roles): """Generates Documentation entry If the included role isn't hosted on tripleo-validations, we point to the validations-common role documentation. Otherwise, it generates a classical local toctree. """ local_role_doc = (".. toctree::\n\n" ...
def go_to_next_page(next_page, next_page_number=None, max_page=10, printing=False): """ According to next_page, and number of pages to scrap, tells if we should go on or stop. returns a boolean value : True (you should follow taht url) / False (you should stop scrapping) - next_page (str) : the u...
def create_search_url(keyword_list, url="https://www.google.com/search?q="): """Create Google search URL for a keyword from keyword_list Args: keyword_list (list): list of strings that contain the search keywords url (str): Google's base search url Returns: list: Google search url ...
def generateDiscretizedValue(value, point_ranges, min_value, max_value): """ Generate discrete symbol based on range This function computes the discrete symbol representation of the value based on the point ranges supplied. The representation will be lowerRange..upperRange. Note: point_ranges must ...
def flatten_filter(value): """Combine incoming sequences in one.""" seq = [] for s in value: seq.extend(s) return seq
def MayaRender(frames, scene_file): """Render the given frames from the given scene..""" return {'renderings': '/renderings/file.%04d.exr'}
def get_max_id(database, table, column, order=None): """ Gets the query to determine the maximum id for a given table / column. :type str :param database: A database name :type str :param table: A table name :type str :param column: A column name :type str :param order: A column...
def get_default_alignment_parameters(adjustspec): """ Helper method to extract default alignment parameters as passed in spec and return values in a list. for e.g if the params is passed as "key=value key2=value2", then the returned list will be: ["key=value", "key2=value2"] """ default_al...
def bigram_parse(data): """ Parse strings into bigrams without nltk :str required: """ from collections import Counter count = Counter() input_list = data.split(' ') zip_bigrams = zip(input_list, input_list[1:]) for element in zip_bigrams: count[element] += 1 return ...
def add_sort_list( l1: list, l2: list, ) -> list: """Add two lists and sort them Parameters ---------- l1 : list The first list to be added l2 : list The second list to be added Returns ------- list The added and sorted list """ # Add ...
def pad_sen_id(id): """ Add padding zeroes to sen_id. """ note_id, sen_no = id.split('_') return '_'.join([note_id, f"{sen_no:0>4}"])
def fix_path(path) : """if on Windows, replace backslashes in path with forward slashes :param path: input path :returns: fixed up path """ return path.replace('\\', '/')
def height(node): """ https://stackoverflow.com/questions/575772/the-best-way-to-calculate-the-height-in-a-binary-search-tree-balancing-an-avl """ if node is None: return 0 else: return node.height
def _process_axes_functions(axes, axes_functions): """Process axes functions of the form `axes.functions(*args, **kwargs).""" if axes_functions is None: return None output = None for (func, attr) in axes_functions.items(): axes_function = getattr(axes, func) # Simple functions (...
def filter_by_name(cases, names): """Filter a sequence of Simulations by their names. That is, if the case has a name contained in the given `names`, it will be selected. """ if isinstance(names, str): names = [names] return sorted( [x for x in cases if x.name in names], key...
def hairpin_check(bps): """ Check to make sure no hairpins are too short.""" for bp in bps: if bp[1] - bp[0] < 4: print('A hairpin is too short.') return False # Everything checks out return True
def match_candidates_by_order(images, max_neighbors): """Find candidate matching pairs by sequence order.""" if max_neighbors <= 0: return set() n = (max_neighbors + 1) // 2 pairs = set() for i, image in enumerate(images): a = max(0, i - n) b = min(len(images), i + n) ...
def _locations_mirror(x): """ Mirrors the points in a list-of-list-of-...-of-list-of-points. For example: >>> _locations_mirror([[[1, 2], [3, 4]], [5, 6], [7, 8]]) [[[2, 1], [4, 3]], [6, 5], [8, 7]] """ if hasattr(x, '__iter__'): if hasattr(x[0], '__iter__'): r...
def getDerivs(timex,y): """https://math.stackexchange.com/questions/2875173/numerical-second-derivative-of-time-series-data """ yderiv = [float('nan') for x in range(len(y))] y2deriv = [float('nan') for x in range(len(y))] for i,t in enumerate(timex[1:(len(timex)-1)]): yderiv[i] = (y[i+1] - y[i-1])/2.0 y2deriv...
def generate_pi(intervals): """ Generates pi for the BAF gaussian model, which maps from SNP location to interval number. In this implementation, pi maps from a chromsome number to ranges of positions and the interval number associated with that range. See the THetA2 supplement for a more in-depth explanation Ar...
def unscalar_lex(arg): """Lexically unwraps a string containing a string or numeric constant, such as are created by the PyTT parser. If the argument (presumed to be a string) starts with the string "scalar(" and ends with the string ")", evaluates and returns the portion of the argument between th...
def linear_search_v2(lst, value): """ Searches for a specified value in a list. @param lst: a list containing numbers @param value: value to be search @return: True if value is found. Otherwise, False. """ for i in range(len(lst)): if lst[i] == value: return ...
def create_data_model(vehicle_data, location_data, distance_matrix, time_matrix): """Stores the data for the problem""" data = {} data['distance_matrix'] = distance_matrix data['time_matrix'] = time_matrix data['demands'] = [0] for i in range(1, (location_data['num'])): data['demands'].append(1) data['vehicle...
def remove_repetition_of_nonterminals_from_productions(grammar_in_text: str): """ Remove nonterminal repeats on the left side of the rule For example: grammar: S -> a S b S -> a b grammar after function execution: S -> a S b | a b """ productions = dict() for production in gramm...
def _quote_if_str(val): """Helper to quote a value if it's a string. """ if isinstance(val, str): return "'{}'".format(val) return val
def generate_arn(service, arn_suffix, region=None): """Returns a formatted arn for AWS. Keyword arguments: service -- the AWS service arn_suffix -- the majority of the arn after the initial common data region -- the region (can be None for region free arns) """ arn_value = "arn"...
def canonsort_keys(keys, canonical_order=None): """ Sorts leading keys according to canonical_order. Keys not specified in canonical_order will appear alphabetically at the end. >>> keys = ['DTEND', 'DTSTAMP', 'DTSTART', 'UID', 'SUMMARY', 'LOCATION'] >>> canonsort_keys(keys) ['DTEND', 'DTSTAMP'...
def check_hypervisor_availability(available_images, fname, hyp_type): """ This routine checks if a given hypervisor is present in given list of images in FVM. Args: available_images(str): JSON of response of enumerating hypervisors in FVM. fname(str): Name of file to be searched in response. hyp_ty...
def function_with_multiline_call(x): """Docstring.""" return range( x, x + 1, )
def range_to_cost_linear(start: int, stop: int) -> float: """Return the length of the slice between `start` (inclusive) and `stop` (exclusive).""" return float(stop - start)
def tracing_mag_int_frac(mag): """Split trace magnitude into integer and fractional components for chip""" mag_int = int(mag) mag_frac = int(128 * (mag - mag_int)) return mag_int, mag_frac
def psh_term_filter(psh_list_terms, keyword): """ Filter one subject from a list of keywords that matched the taxonomy. :param psh_list_terms: List of keywords. :param keyword: :return: taxonomy_term """ psh_list_terms = [term for term in psh_list_terms if "PSH" in term.tree_path] if len...
def true_positive(a, b): """ Return quantity of TP - True Positives What is in A and B being A the set of Positive prediction and B the set of Actual Positive """ tp = 0 for item in a: if item in b: tp += 1 return tp
def get_module_name(module): """Returns a module's name or None if one cannot be found. Relevant PEP: https://www.python.org/dev/peps/pep-0451/ """ if hasattr(module, '__spec__'): return module.__spec__.name return getattr(module, '__name__', None)
def to_vantage_level(level): """Convert the given HASS light level (0-255) to Vantage (0.0-100.0).""" return float((level * 100) / 255)
def Pad(ids, pad_id, length): """Pad or trim list to len length. Args: ids: list of ints to pad pad_id: what to pad with length: length to pad or trim to Returns: ids trimmed or padded with pad_id """ assert pad_id is not None assert length is not None if len(ids) < ...
def _bump(char, position): """ only treats `\n` as newline """ line, col = position if char == '\n': return (line + 1, 1) return (line, col + 1)
def part2(commands): """ down X increases your aim by X units. up X decreases your aim by X units. forward X does two things: It increases your horizontal position by X units. It increases your depth by your aim multiplied by X. Calculate the horizontal position and depth you would ...
def convertUnicodeString(inputNames): """ Function gets unicode string and converts it to a string. :param outputNames: List of input names """ retNames = [] if (isinstance(inputNames, list)): for elem in inputNames: retNames.append(str(elem)) else: retNames = ...
def bool_string_to_int(value): """ Convert a boolean string to corresponding integer value :param value: e.g. 'TRUE' :return: 1 if string is 'true', 0 otherwise :throws: AttributeError if value is not type of string """ return 1 if value.lower() == 'true' else 0
def z(x, mu, sigma): """ Returns the z-location of the given stimulus levels """ return (x - mu) / sigma
def h(string): """ hash to map the buttons """ return str(tuple((string[:2]))).replace(' ', '')
def get_item_from_list_by_key_value(items, key, value): """Get the item from list containing sequence of dicts.""" for item in items: if item[key] == value: return item return None
def unquote_ident(val): """Unquotes possibly quoted SQL identifier.""" if val[0] == '"' and val[-1] == '"': return val[1:-1].replace('""', '"') return val
def _toUnicode(msg, *args): """ Unicode representation of the formatted message. String is decoded with the codeset used by the filesystem of the operating system. """ try: msg_ = msg % args except TypeError: # Also allow dict with keywords in format string, passed as first a...
def concatenate_lists(entry): """ take a list with a key (e.g. date) that has a list of resourceTypes entries Copy all lists to a single list entry should be: {'entry': [{'2020-12-22T09:30:00+00:00': [{'resourceType': 'Encounter', 'id': ... :param entry: :return: big_entry """ big_...
def tobin(data, width): """ """ data_str = bin(data & (2**width-1))[2:].zfill(width) return [int(x) for x in tuple(data_str)]