content
stringlengths
42
6.51k
def summarize(f): """Return the function's doc summary.""" return (f.__doc__ or "").split("\n", 1)[0].strip()
def _params_to_ints(querystring): """Convert a list of string iD to a list of integers""" return [int(str_id) for str_id in querystring.split(",")]
def get_netmask_bits(netmask): """ Count the number of bits in the netmask """ rv = 0 stop = False for chunk in netmask.split('.'): byte = int(chunk) for bit in reversed(range(8)): if byte & 2**bit: if stop: raise RuntimeError("One bit after zero bit") rv += 1 else: stop = True return rv
def toggle(collection, item): """ Toggles an item in a set. """ if item is None: return collection if item in collection: return collection - {item} else: return collection | {item}
def count_digits(number: int) -> int: """ >>> count_digits(-123) 3 >>> count_digits(-1) 1 >>> count_digits(0) 1 >>> count_digits(123) 3 >>> count_digits(123456) 6 """ number = abs(number) count = 0 while True: number = number // 10 count = count + 1 if number == 0: break return count
def time_to_decimal(time): """ Get the decimal part of a date. Parameters ---------- time : array a time with hms format split by ':' Returns ------- decimal_time : string the decimal part of a date. Examples -------- >>> time = [20, 17, 40.088] >>> time_to_decimal(time) '73040' """ return str(int(time[0]) * 3600 + int(time[1]) * 60 + int(time[0]))
def extract_content(entity): """ Given an entity, attempt to find "content" (encoded bytes) and "content-type" (Mime type of file). """ content = None content_type = None for key in entity.keys(): if "content" in key.split(":"): content = entity[key] if "content-type" in key.split(":"): content_type = entity[key] return content, content_type
def count(count: int, noun: str) -> str: """Count a given noun, pluralizing if necessary.""" return f"{count} {noun}{'s' if count != 1 else ''}"
def generate_normalized_name(name_tuple): """ Generates a normalized name (without whitespaces and lowercase) """ name_arr = list(name_tuple) name_arr.sort() name_str = ''.join(name_arr) return name_str.lower()
def strip_cstring(data: bytes) -> str: """Strip strings to the first null, and convert to ascii. The CmdSeq files appear to often have junk data in the unused sections after the null byte, where C code doesn't touch. """ if b'\0' in data: return data[:data.index(b'\0')].decode('ascii') else: return data.decode('ascii')
def Qconjugate(q): """ Qconjugate """ return (q[0], -q[1], -q[2], -q[3])
def location_check(csv_name): """ Function creates path for giving csv file (based on csv file name) :param csv_name: csv file name :return: path where to save giving file """ csv_name = str(csv_name) tournament_type = csv_name[-13:-11] tournament_gender = csv_name[-7] team_individual = csv_name[-5] if tournament_gender == 'M': gender = 'Man' elif tournament_gender == 'W': gender = 'Women' elif tournament_gender == 'X': gender = 'Mixed' else: gender = '?' print("Something went wrong - gender: " + tournament_gender) if "WC" == tournament_type: type_tour = 'World Cup' elif "GP" == tournament_type: type_tour = "Grand Prix" elif "OL" == tournament_type: type_tour = 'Olympics' elif "CH" == tournament_type: type_tour = 'World Championship' else: type_tour = "?" print("Something went wrong - tournament type: " + tournament_type) if "I" == team_individual: team_ind = 'Individual' elif "T" == team_individual: team_ind = 'Team' else: team_ind = "?" print("Something went wrong - team/ind: " + team_individual) # location / path where the file will be save location = f"/Users/pik/Desktop/SKI_DB/{gender}/{type_tour}/{team_ind}/" return location
def s_curve(CurrTime, Amp, RiseTime, StartTime=0.0): """ Function to generate an s-curve command Arguments: CurrTime : The current timestep or an array of times Amp : The magnitude of the s-curve (or final setpoint) RiseTime : The rise time of the curve StartTime : The time that the command should StartTime Returns : The command at the current timestep or an array representing the command over the times given (if CurrTime was an array) """ scurve = 2.0 * ((CurrTime - StartTime)/RiseTime)**2 * (CurrTime-StartTime >= 0) * (CurrTime-StartTime < RiseTime/2) \ +(-2.0 * ((CurrTime - StartTime)/RiseTime)**2 + 4.0 * ((CurrTime - StartTime)/RiseTime) - 1.0) * (CurrTime-StartTime >= RiseTime/2) * (CurrTime-StartTime < RiseTime) \ + 1.0 * (CurrTime-StartTime >= RiseTime) return Amp * scurve
def densityWater(temperature): """ Calculates the density of water from an interpolation by Cheng (see viscosity docstring for reference). Args: temperature (float): in Celsius in the range [0, 100] Returns: :class:`float` Density of water in kg/m^3 """ rho = 1000 * (1 - abs((temperature - 4) / (622.0)) ** (1.7)) waterDensity = rho return waterDensity
def _convert_yaml_to_bool(_yaml_bool_value): """This function converts the 'yes' and 'no' YAML values to traditional Boolean values. .. versionchanged:: 2.5.2 A conversion is now only attempted if the value is not already in Boolean format. """ if type(_yaml_bool_value) != bool: true_values = ['yes', 'true'] if _yaml_bool_value.lower() in true_values: _yaml_bool_value = True else: _yaml_bool_value = False return _yaml_bool_value
def sort_items_by_count(items): """ Takes a dictionary of items, and returns a list of items sorted by count. :param items: A dictionary in {choice: count} format. :return: A list of (choice, count) tuples sorted by count descending. """ return sorted([(item, items[item]) for item in items], key=lambda x: -x[1])
def fix_count(count): """Adds commas to a number representing a count""" return '{:,}'.format(int(count))
def strictNamespaceMappingEnvarParse(envar=None): """Custom format STRICT_NAMESPACE_MAPPING env variable parsing. Note: STRICT_NAMESPACE_MAPPING value example: 'frontend.develop.example.com:develop,frontend.staging.example.com:staging' No spaces or special chars. """ if envar: items = envar.split(',') mapdict = {} for item in items: mapdict[item.split(':')[0]] = item.split(':')[1] return mapdict return None
def parse_gb_allele_freqs_col(_bytes): """ Parse 'alleleFreqs' column of table snp146 in UCSC genome browser """ if _bytes == b'': return [] else: # "0.2,0.8,".split(',') = ['0.2', '0.8', ''] # Remove the last empty string freq_str = _bytes.decode("utf-8").split(',')[:-1] freq_float = [float(i) for i in freq_str] return freq_float
def recup_min_line (matrix): """Recuperation des min par ligne""" line_min_elt = [] for y_elt in matrix: min_line = y_elt[0] for x_elt in y_elt: if min_line > x_elt: min_line = x_elt line_min_elt.append(min_line) return line_min_elt
def readtime(wordcount: int, words_per_minute=300): """Given a number of words, estimate the time it would take to read them. :return: The time in minutes if it's more than 1, otherwise 1.""" return max(1, round(wordcount / 300))
def isSubhist(hist1, hist2): """ Checks if hist1 is a subset of hist2 Input: hist1, hist2 -- dictionary histograms Output: Boolean """ for letter in hist1: if letter not in hist2 or hist1[letter] > hist2[letter]: return False return True
def world_to_pixel(geoMatrix, x, y): """ Uses a gdal geomatrix (gdal.GetGeoTransform()) to calculate the pixel location of a geospatial coordinate """ ulX = geoMatrix[0] ulY = geoMatrix[3] xDist = geoMatrix[1] yDist = geoMatrix[5] rtnX = geoMatrix[2] rtnY = geoMatrix[4] pixel = int((x - ulX) / xDist) line = int((ulY - y) / xDist) return (pixel, line)
def levenshtein_distance(first,second): """ Return the levenshtein distance between two strings. http://rosettacode.org/wiki/Levenshtein_distance#Python """ if len(first) > len(second): first, second = second, first distances = range(len(first)+1) for index2, char2 in enumerate(second): new_distances = [index2 + 1] for index1, char1 in enumerate(first): if char1 == char2: new_distances.append(distances[index1]) else: new_distances.append(1 + min((distances[index1], distances[index1+1], new_distances[-1]))) distances = new_distances return distances[-1]
def get_prefix(url): """ @Description: get the prefix of a url to form the sub-level url --------- @Param: url:str ------- @Returns: a substr end where '/' last time appears ------- """ return url[0:url.rfind("/") + 1]
def fragment_3(N): """Fragment-3 for exercise.""" ct = 0 for _ in range(0,N,2): for _ in range(0,N,2): ct += 1 return ct
def create_mask(indexes): """ Convert index to hex mask. """ val = 0 for index in indexes: val |= 1 << int(index) return hex(val).rstrip("L")
def _fix_quoted_whitespace(line): """Replace spaces and tabs which appear inside quotes in `line` with underscores, and return it. """ i = 0 while i < len(line): char = line[i] i += 1 if char != '"': continue quote = char while i < len(line): char = line[i] i += 1 if char == quote: break if char in " \t": line = line[:i-1] + "_" + line[i:] return line
def drop_substring_from_str(item: str, substring: str) -> str: """Drops 'substring' from 'item'. Args: item (str): item to be modified. substring (str): substring to be added to 'item'. Returns: str: modified str. """ if substring in item: return item.replace(substring, '') else: return item
def complete(prog_comp, obs_comp): """ Observation completion weighting factor. - 1.0 if observation not completed - 0.0 if observation or program are completed Parameters ---------- prog_comp : float fraction of program completed. obs_comp : float fraction of observation completed. Returns ------- float completion weighting factor """ if obs_comp >= 1. or prog_comp >= 1.: return 0 else: return 1
def get_tag_list(task, tagging_schema): """ Set up the tag list """ task = task.lower() tagging_schema = tagging_schema.lower() if task == 'absa': if tagging_schema == 'ot': return ['O', 'T-POS', 'T-NEG', 'T-NEU'] elif tagging_schema == 'bio': return ['O', 'B-POS', 'I-POS', 'B-NEG', 'I-NEG', 'B-NEU', 'I-NEU'] elif tagging_schema == 'bieos': return ['O', 'B-POS', 'I-POS', 'E-POS', 'S-POS', 'B-NEG', 'I-NEG', 'E-NEG', 'S-NEG', 'B-NEU', 'I-NEU', 'E-NEU', 'S-NEU'] else: raise Exception("Invalid tagging schema: {}".format(tagging_schema)) elif task == 'ate': if tagging_schema == 'ot': return ['O', 'T'] elif tagging_schema == 'bio': return ['O', 'B', 'I'] elif tagging_schema == 'bieos': return ['O', 'B', 'I', 'E', 'S'] else: raise Exception("Invalid tagging schema: {}".format(tagging_schema)) else: raise Exception("Invalid task name: {}".format(task))
def compute_protien_mass(protien_string): """ test case >>> compute_protien_mass('SKADYEK') 821.392 """ p={'A':'71.03711','C':'103.00919','D':'115.02694','E':'129.04259','F':'147.06841','G':'57.02146','H':'137.05891','I':'113.08406','K':'128.09496','L':'113.08406','M':'131.04049','N':'114.04293','P':'97.05276','Q':'128.05858','R':'156.10111','S':'87.03203','T':'101.04768','V':'99.06841','W':'186.07931','Y':'163.06333'} mass=0 for x in protien_string: mass=mass+float(p[x]) #to change number of values after decimel point to 3 mass=round(mass,3) return mass
def pprint_size(value): """Pretty-print size (with rounding)""" for postfix, limit in [("G", 1e9), ("M", 1e6), ("K", 1e3), ("", 1)]: if value >= limit: return "{}{}".format(int(value/limit), postfix)
def get_alt_support_by_color(is_in_support): """ ***NOT USED YET*** :param is_in_support: :return: """ if is_in_support == 254.0: return 1 elif is_in_support == 152.0: return 0
def ifexists(total_pages, page_no): """ This function checks whether the given page number is in the specified range of total pages. :param total_pages: :param page_no: :return: True or False """ if page_no <= total_pages: return False return True
def catch_parameter(opt): """Change the captured parameters names""" switch = {'-h':'help', '-i':'imp', '-l':'lstm_act', '-d':'dense_act', '-n':'norm_method', '-f':'folder', '-m':'model_file', '-t':'model_type', '-a':'activity', '-e':'file_name', '-b':'n_size', '-c':'l_size', '-o':'optim'} try: return switch[opt] except: raise Exception('Invalid option ' + opt)
def get_skip_initial_samples_min(post_proc_args): """ Function iterates over a list of arguments of the form ["plot_all_individual_cdfs", "visualise_traceworkload", "skipmins_3"] searches for "skipmins_3" and returns 3 in this case. This parameter indicates how many minutes to skip from the ycsb results""" for p in post_proc_args: if p.startswith("skipmins"): skipmins = int(p.split("_")[1]) return skipmins return 0
def dict2coord(d): """dictionary as 'key1=value1, key2=value2, ...' string""" return ', '.join('{0}={1:.2f}'.format(*x) for x in d.items())
def literal(x): """Make literal""" if isinstance(x, str): if x and x[0] == x[-1] and x[0] in '"\'`': # already literal quoted return x # literal quote return f'"{x}"' if isinstance(x, list): # apply to children return [literal(x_) for x_ in x] if isinstance(x, dict): # apply to children return {k: literal(v) for k, v in x.items()} return x
def option_not_exist_msg(option_name, existing_options): """ Someone is referencing an option that is not available in the current package options """ result = ["'options.%s' doesn't exist" % option_name] result.append("Possible options are %s" % existing_options or "none") return "\n".join(result)
def provided_args(attrs): """Extract the provided arguments from a class's attrs. Arguments: attrs (:py:class:`dict`) :The attributes of a class. Returns: :py:class:`set`: The provided arguments. """ return attrs.get('PROVIDED', set())
def _is_field_in_transition_actions(actions, field_name): """ Returns True if there is field with given name in one of actions. """ for action in actions: if field_name in getattr(action, 'form_fields', {}): return True return False
def _filter_nonvalid_data(json_data): """ Remove channels that are disabled or that do not declare their policies. """ # Filter to channels having both peers exposing their policies json_data['edges'] = list(filter(lambda x: x['node1_policy'] and x['node2_policy'], json_data['edges'])) # Filter to non disabled channels json_data['edges'] = list(filter(lambda x: not (x['node1_policy']['disabled'] or x['node2_policy']['disabled']), json_data['edges'])) return json_data
def truthiness(s): """If input string resembles something truthy then return True, else False.""" return s.lower() in ('true', 'yes', 'on', 't', '1')
def above_threshold (student_scores, threshold): """Determine how many of the provided student scores were 'the best' based on the provided threshold. :param student_scores: list of integer scores :param threshold : integer :return: list of integer scores that are at or above the "best" threshold. """ result = [] for element in student_scores: if element >= threshold: result.append (element) return result
def parse_requirements_fname(dep_name): """Parse requirements file path from dependency declaration (-r<filepath>). >>> parse_requirements_fname('pep8') >>> parse_requirements_fname('-rrequirements.txt') 'requirements.txt' :param dep_name: Name of the dependency :return: Requirements file path specified in the dependency declaration if specified otherwise None :rtype: str or None """ req_option = "-r" if dep_name.startswith(req_option): return dep_name[len(req_option) :]
def get_objects(predictions: list, img_width: int, img_height: int): """Return objects with formatting and extra info.""" objects = [] decimal_places = 3 for pred in predictions: if isinstance(pred, str): # this is image class not object detection so no objects return objects name = list(pred.keys())[0] box_width = pred[name][2]-pred[name][0] box_height = pred[name][3]-pred[name][1] box = { "height": round(box_height / img_height, decimal_places), "width": round(box_width / img_width, decimal_places), "y_min": round(pred[name][1] / img_height, decimal_places), "x_min": round(pred[name][0] / img_width, decimal_places), "y_max": round(pred[name][3] / img_height, decimal_places), "x_max": round(pred[name][2] / img_width, decimal_places), } box_area = round(box["height"] * box["width"], decimal_places) centroid = { "x": round(box["x_min"] + (box["width"] / 2), decimal_places), "y": round(box["y_min"] + (box["height"] / 2), decimal_places), } confidence = round(pred['score'], decimal_places) objects.append( { "bounding_box": box, "box_area": box_area, "centroid": centroid, "name": name, "confidence": confidence, } ) return objects
def td(obj): """Create a table entry from string or object with html representation.""" if hasattr(obj, '_repr_html_'): return f'<td style="text-align:left;">{obj._repr_html_()}</td>' elif hasattr(obj, '_repr_image_svg_xml'): return f'<td style="text-align:left;">{obj._repr_image_svg_xml()}</td>' else: return f'<td style="text-align:left;">{obj}</td>'
def isASNTable(inputFilelist): """Return TRUE if inputFilelist is a fits ASN file.""" if ("_asn" or "_asc") in inputFilelist: return True return False
def shape_to_stride(shape): """Return the stride. Parameters ---------- shape : tuple(int) The shape tuple """ ndim = len(shape) stride = [1] * ndim for i in range(ndim-1, 0, -1): stride[i-1] = stride[i] * shape[i] return tuple(stride)
def lwrap(list_, w=None): """docstring for lwrap""" result = [] o = w or '"' for elem in list_: result.append(o + elem + o) return result
def size_converter(_bytes: int) -> str: """ Converts bytes to KB, MB & GB Returns: formated str """ KB = _bytes / float(1 << 10) MB = _bytes / float(1 << 20) GB = _bytes / float(1 << 30) if GB > 1: return f"{round(GB, 2):,} GB" elif MB > 1: return f"{round(MB, 2):,} MB" return f"{round(KB, 2):,} KB"
def levenshtein(string1, string2, swap=0, substitution=2, insertion=1, deletion=3): """ This is levenshtein distance calculation utility taken from https://github.com/git/git/blob/master/levenshtein.c @param string1: @param string2: @param swap: @param substitution: @param insertion: @param deletion: @return: """ len1 = len(string1) len2 = len(string2) row0 = list() row1 = list() row2 = [0] * (len2 + 1) for j in range(len2 + 1): row1.append(j * insertion) for i in range(len1): # print i dummy = [0] * (len2 + 1) row2[0] = (i + 1) * deletion for j in range(len2): # substitution row2[j + 1] = row1[j] + substitution * (string1[i] != string2[j]) # swap if (i > 0 and j > 0 and string1[i-1] == string2[j] and string1[i] == string2[j-1] and row2[j+1] > row0[j-1] + swap): row2[j + 1] = row0[j - 1] + swap # deletion if row2[j + 1] > row1[j + 1] + deletion: row2[j + 1] = row1[j + 1] + deletion # insertion if row2[j + 1] > row2[j] + insertion: row2[j + 1] = row2[j] + insertion dummy, row0, row1, row2 = row0, row1, row2, dummy return row1[len2]
def all_suffixes(li): """ Returns all suffixes of a list. Args: li: list from which to compute all suffixes Returns: list of all suffixes """ return [tuple(li[len(li) - i - 1:]) for i in range(len(li))]
def gcd_rec(num1: int, num2: int) -> int: """ Return the greatest common divisor of two numbers. Parameters ---------- num1 : int num2 : int Raises ------ TypeError if num1 or num2 is not integer. Returns ------- int """ def _gcd(dividend: int, divisor: int) -> int: """Return the gcd of two numbers.""" if divisor: return _gcd(divisor, dividend % divisor) return dividend for num in (num1, num2): if not isinstance(num, int): raise TypeError(f"{num} is not integer") return _gcd(num1, num2)
def dms2dd(d, m, s): """ Convert degrees minutes seconds to decimanl degrees :param d: degrees :param m: minutes :param s: seconds :return: decimal """ return d+((m+(s/60.0))/60.0)
def is_success(code): """ Returns the expected response codes for HTTP GET requests :param code: HTTP response codes :type code: int """ if (200 <= code < 300) or code in [404, 500]: return True return False
def same_shape(shape1, shape2): """ Checks if two shapes are the same Parameters ---------- shape1 : tuple First shape shape2 : tuple Second shape Returns ------- flag : bool True if both shapes are the same (same length and dimensions) """ if len(shape1) != len(shape2): return False for i in range(len(shape1)): if shape1[i] != shape2[i]: return False return True
def get_tidy_invocation(f, clang_tidy_binary, checks, build_path, quiet, config): """Gets a command line for clang-tidy.""" start = [clang_tidy_binary] # Show warnings in all in-project headers by default. start.append('-header-filter=src/') if checks: start.append('-checks=' + checks) start.append('-p=' + build_path) if quiet: start.append('-quiet') if config: start.append('-config=' + config) start.append(f) return start
def inv_mod_p(x, p): """ Compute an inverse for x modulo p, assuming that x is not divisible by p. """ if x % p == 0: raise ZeroDivisionError("Impossible inverse") return pow(x, p-2, p)
def is_function(x): """ Checks if the provided expression x is a function term. i.e., a tuple where the first element is callable. """ return isinstance(x, tuple) and len(x) > 0 and callable(x[0])
def r(a): """ Make a slice from a string like start:stop:step (default 0:-1:1). """ a = a.split(":") if len(a) == 1: i = int(a[0]) return slice(i,i+1,1) x = a[0] and int(a[0]) or 0 y = a[1] and int(a[1]) or None s = len(a) == 3 and int(a[2]) or 1 return slice(x, y, s)
def evaluate_poly(poly, x): """ Computes the polynomial function for a given value x. Returns that value. Example: >>> poly = (0.0, 0.0, 5.0, 9.3, 7.0) # f(x) = 7x^4 + 9.3x^3 + 5x^2 >>> x = -13 >>> print evaluate_poly(poly, x) # f(-13) = 7(-13)^4 + 9.3(-13)^3 + 5(-13)^2 180339.9 poly: tuple of numbers, length > 0 x: number returns: float """ len_poly = len(poly) if len_poly > 0: exponent = len_poly-1 # useful for debugging # print poly[-1], '*', x, '**', exponent, '=', poly[-1]*x**exponent return poly[-1]*x**exponent + evaluate_poly(poly[:-1], x) else: return 0.0
def is_child(parent, child, locations): """ Determines if child is child of parent Args: parent: parent_id child: child_id locations: all locations in dict Returns: is_child(Boolean): True if child is child of parent """ parent = int(parent) child = int(child) if child == parent or parent == 1: return True loc_id = child while loc_id != 1: loc_id = locations[loc_id].parent_location if loc_id == parent: return True return False
def get_position(row_index, col_index, board_size): """(int, int, int) -> int Return the str_index of the cell in the game board of size board_size within the row, row_index, and the column, col_index >>>get_position(1, 1, 2) 0 >>>get_position(3, 2, 3) 7 """ return (row_index - 1) * board_size + col_index - 1
def gaussian(x, mean, var): """Given the mean and variance of a 1-d gaussian, return the y value for a given `x` value. .. math:: \\frac{1}{\\sigma\\sqrt{2\\pi}}e^{-\\frac{1}{2}(\\frac{x-\\mu}{\\sigma})^2} """ from math import sqrt, exp, pi denom = sqrt(2*pi*var) num = exp(-((x-mean)**2)/(2*var)) ret = num/float(denom) #print "Gaussian of x=%s (m=%s, var=%s) is %s" % (x, mean, var, ret) return ret
def get2(item, key, if_none=None, strict=True): """ similar to dict.get functionality but None value will return then if_none value :param item: dictionary to search :param key: the dictionary key :param if_none: the value to return if None is passed in :param strict: if False an empty string is treated as None :return: """ if not strict and item.get(key) == "": return if_none elif item.get(key) is None: return if_none else: return item.get(key)
def peptide_mods(peptide): """Looks for modification symbols in peptides. Returns list of mod symbols. THIS NEEDS TO BE CHANGED TO HANDLE NEW COMET MODS """ # see if there are bounding residues temp = peptide.split('.') if len(temp) > 1: peptide = temp[1] # check for Comet modification symbols (also has older style n-term and c-term symbols) mod_list = [] for char in peptide: if char in ['*', '#', '@', '^', '~', '$', '%', '!', '+', 'n', 'c', '[', ']']: mod_list.append(char) # return mod_list
def _format_description(description): """Clean the description of a node for display in Graphviz""" return description.replace('\'', '').encode('unicode_escape').decode()
def step_t(w1, w2, t0, width, t): """ Step function that goes from w1 to w2 at time t0 as a function of t. """ return w1 + (w2 - w1) * (t > t0)
def sort_dict_keys_by_value(d): """ Sort the keys in the dictionary by their value and return as a list This function uses `sorted`, so the values should be able to be sorted appropriately by that builtin function. """ ret = sorted(d, key=d.get) return ret
def fix_brace_o(a, b): """Move any `{`s between the contents of line `a` and line `b` to the start of line `b`. :param a: A line of Lean code, ending with `\n' :param b: A line of Lean code, ending with `\n' :returns: A tuple `(anew, bnew, fix)`, where `anew` and `bnew` are `a` and `b` with corrected brace positions, and `fix` is a boolean indicating whether there was a change, i.e. `fix = ((anew, bnew) != (a, b))`. """ astr = a.rstrip() if astr == "": return a, b, False if not astr[-1] == '{': return a, b, False a = astr[:-1].rstrip() + '\n' bstr = b.lstrip() indent = len(b) - len(bstr) indent = max(indent - 2, 0) b = " " * indent + "{ " + bstr return a, b, True
def max_number_len(n): """Find max power of 10 which can be less or equals than sum of its digits power.""" power_of_9 = 9**n k = 1 while k*power_of_9 >= 10 ** k: k += 1 return k
def common_prefix(strings): """ Given a list of strings, return the common prefix between all these strings. """ ref = strings[0] prefix = '' for size in range(len(ref)): test_prefix = ref[:size+1] for string in strings[1:]: if not string.startswith(test_prefix): return prefix prefix = test_prefix return prefix
def s2b(s): """ Converts a string to boolean value """ s = s.lower() return s == 'true' or s == 'yes' or s == 'y' or s == '1'
def fix_greengenes_missing_data(taxa_list): """ Writes taxa levels as separate list items, passes levelAbbreviation__ for missing data""" blank_taxa_terms = ['k__', 'p__', 'c__', 'o__', 'f__', 'g__', 's__'] missing_terms = 7 - len(taxa_list) if missing_terms != 0: taxa_list.extend(blank_taxa_terms[-missing_terms:]) return taxa_list
def _getResultArray(rows, columns): """ Returns a pre-initialized results array with values <tt>-1</tt>. """ results = {} for row in rows: results[row] = {} for column in columns: results[row][column] = -1 return results
def index(sequence, condition): """ Returns index of the first item in a sequence that satisfies specified condition. Args: sequence: iterable Sequence of items to go through. condition: callable Condition to test. Returns: int Index of the first valid item. """ for i, item in enumerate(sequence): if condition(item): return i raise ValueError()
def compute_transition_table(init, target, iterations): """Compute a list of values for a smooth transition between 2 numbers. Args: init (int): initial value target (int): target value iterations (int): number of in-between values to create Returns: list: the transition list """ # Get the increment and create the inital table if target < init: incr = -1 else: incr = 1 tmp_range = [i for i in range(init, target, incr)] # if tmp range is 0 len, that means there is no change for this color, if len(tmp_range) is 0: tmp_range.append(target) # If the range is too long, pop some values until we are ok pop_index = 1 while len(tmp_range) > iterations: tmp_range.pop(pop_index % len(tmp_range)) pop_index += 4 # If the range is too short, add some values twice until we are ok insert_index = 0 while len(tmp_range) < iterations: insert_index = insert_index % len(tmp_range) tmp_range.insert( insert_index, tmp_range[insert_index-1 if insert_index-1 > 0 else 0]) insert_index += 4 # Pop the first and append the index tmp_range.pop(0) tmp_range.append(target) return tmp_range
def arithmetic_mean(samples): """Computes the arithmetic mean of a set of samples. """ return float(sum(samples)) / float(len(samples))
def remove_keys_filter(row,keys): """ Remove given keys from the row """ for key in keys: row.pop(key,None) return row
def create_silence(length): """Create a piece of silence.""" data = bytearray(length) i = 0 while i < length: data[i] = 128 i += 1 return data
def _clean_accounting_column(x: str) -> float: """ Perform the logic for the `cleaning_style == "accounting"` attribute. This is a private function, not intended to be used outside of `currency_column_to_numeric``. It is intended to be used in a pandas `apply` method. :returns: An object with a cleaned column. """ y = x.strip() y = y.replace(",", "") y = y.replace(")", "") y = y.replace("(", "-") if y == "-": return 0.00 return float(y)
def aqi(concentration): """Convert PM 2.5 concentration to AQI.""" if concentration <= 12.: return round(4.1667 * concentration) elif concentration <= 35.4: return round(2.1030 * (concentration - 12.1) + 51.) elif concentration <= 55.4: return round(2.4623 * (concentration - 35.5) + 101.) elif concentration <= 150.4: return round(0.5163 * (concentration - 55.5) + 151.) elif concentration <= 250.4: return round(0.9910 * (concentration - 150.5) + 201.) elif concentration <= 500.4: return round(0.7963 * (concentration - 250.5) + 301.) else: return 999.
def write_internals_visible_to(actions, name, others): """Write a .cs file containing InternalsVisibleTo attributes. Letting Bazel see which assemblies we are going to have InternalsVisibleTo allows for more robust caching of compiles. Args: actions: An actions module, usually from ctx.actions. name: The assembly name. others: The names of other assemblies. Returns: A File object for a generated .cs file """ if len(others) == 0: return None attrs = actions.args() attrs.set_param_file_format(format = "multiline") attrs.add_all( others, format_each = "[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(\"%s\")]", ) output = actions.declare_file("bazelout/%s/internalsvisibleto.cs" % name) actions.write(output, attrs) return output
def yes_no_none(value): """Convert Yes/No/None to True/False/None""" if not value: return None # Yes = True, anything else false return value.lower() == 'yes'
def _attrprint(d, delimiter=', '): """Print a dictionary of attributes in the DOT format""" return delimiter.join(('"%s"="%s"' % item) for item in sorted(d.items()))
def reduce(fea): # pragma: no cover """restore some formula""" rules = [ ('a r c s i n', 'arcsin'), ('a r c c o s', 'arccos'), ('a r c t a n', 'arctan'), ('s i n h', 'sinh'), ('c o s h', 'cosh'), ('t a n h', 'tanh'), ('s i n', 'sin'), ('c o s', 'cos'), ('t a n', 'tan'), ('c o t', 'cot'), ('s e c', 'sec'), ('c s c', 'csc'), ('l g', 'lg'), ('l o g', 'log'), ('l n', 'ln'), ('m a x', 'max'), ('m i n', 'min'), ('{ i m g }', '{img}'), ('i m g', '{img}'), ('< u >', '{blank}'), (' ', ' ') ] fea = ' '.join(fea) for a, b in rules: fea = fea.replace(a, b) return fea.strip().split()
def freq_id_to_stream_id(f_id): """ Convert a frequency ID to a stream ID. """ pre_encode = (0, (f_id % 16), (f_id // 16), (f_id // 256)) stream_id = ( (pre_encode[0] & 0xF) + ((pre_encode[1] & 0xF) << 4) + ((pre_encode[2] & 0xF) << 8) + ((pre_encode[3] & 0xF) << 12) ) return stream_id
def inherits_from(obj, a_class): """return inherits""" return issubclass(type(obj), a_class) and type(obj) != a_class
def labels_to_onehot(labels, classes): """ Convert a list of labels (integers) into one-hot format. Parameters ---------- labels : list A list of integer labels, counting from 0. classes : int Number of class integers. Returns ------- list List of one-hot lists. """ for c, i in enumerate(labels): onehot = [0] * classes onehot[i] = 1 labels[c] = onehot return labels
def clean_ensembl_id(identifier): """ Formats an ensembl gene identifier to drop the version number. E.g., ENSG00000002822.15 -> ENSG00000002822 Args: identifier (str) Returns: identifier (str) """ return identifier.split('.')[0].upper()
def longest_prefix(names): """Find the longest common prefix of the repository names.""" return next( names[0][:n] for n in range(min(len(s) for s in names), 0, -1) if len({s[:n] for s in names}) == 1 )
def both_positive(a, b): """Returns True if both a and b are positive. >>> both_positive(-1, 1) False >>> both_positive(1, 1) True """ return a > 0 and b > 0
def _sort_resources(resources): """ Sorts a stack's resources by LogicalResourceId Parameters ---------- resources : list Resources to sort Returns ------- list List of resources, sorted """ if resources is None: return [] return sorted(resources, key=lambda d: d["LogicalResourceId"])
def pad(s, n): """Pad a string with spaces on both sides until long enough""" while len(s) < n: if len(s) < n: s = s + " " if len(s) < n: s = " " + s return s
def create_margin(x): """Creates a margin with the specified ratio to the width or height.""" return dict(l=x, r=x, b=x, t=x)
def thread(x, *fns): """Threads `x` left-to-right through the `fns`, returning the final result. thread x :: a -> a thread x, *fns :: a_0, *(a_i -> a_i+1) -> a_n""" for f in fns: x = f(x) return x
def _captchasolutiontokey(captcha, solution): """Turn the CAPTCHA and its solution into a key. >>> captcha = 'KSK@hBQM_njuE_XBMb_? with 10 plus 32 = ?' >>> solution = '42' >>> _captchasolutiontokey(captcha, solution) b'KSK@hBQM_njuE_XBMb_42' """ secret = captcha.split("?")[0] key = secret + str(solution) return key.encode("utf-8")
def collatz_rec(p, nr_steps): """Recursive Collatz Step Calculation""" nr_steps += 1 if (p <= 1): return nr_steps if p % 2 == 0: return collatz_rec(int(p/2), nr_steps) else: return collatz_rec(int(3*p + 1), nr_steps)