content
stringlengths
42
6.51k
def ProcessName(name, isedge): """ Process the name of the node. :param name: name of the node :param isedge: whether this is a edge :return: new name """ if isedge: firstnode, secondnode = name.split("--") firstnode = firstnode.strip() secondnode = secondnode.strip() return firstnode, secondnode else: return name.strip()
def _legend_add_subtitle(handles, labels, text, func): """Add a subtitle to legend handles.""" if text and len(handles) > 1: # Create a blank handle that's not visible, the # invisibillity will be used to discern which are subtitles # or not: blank_handle = func([], [], label=text) blank_handle.set_visible(False) # Subtitles are shown first: handles = [blank_handle] + handles labels = [text] + labels return handles, labels
def is_runtime_parameter(argument): """Return True if the directive argument defines a runtime parameter, and False otherwise.""" return argument.startswith('$')
def name_to_uri(name): """ Transforms the name of a file into a URI """ return name.split(".")[0].replace(" ", "-").lower();
def numCorrects(trueCoops, inferredCoops): """ Count the number of correct predictions given the true and inferred cooperator pairs. """ numCorrects = 0 if trueCoops['AC'] == inferredCoops['AC']: numCorrects += 1 if trueCoops['AB'] == inferredCoops['AB']: numCorrects += 1 if trueCoops['BC'] == inferredCoops['BC']: numCorrects += 1 return numCorrects
def camel_case_to_separate_words(camel_case_string: str) -> str: """Convert CamelCase string into a string with words separated by spaces""" words = [[camel_case_string[0]]] for character in camel_case_string[1:]: if words[-1][-1].islower() and character.isupper(): words.append(list(character)) else: words[-1].append(character) return " ".join("".join(word) for word in words)
def load_dotted(name): """ Imports and return the given dot-notated python object """ components = name.split('.') path = [components.pop(0)] obj = __import__(path[0]) while components: comp = components.pop(0) path.append(comp) try: obj = getattr(obj, comp) except AttributeError: __import__('.'.join(path)) try: obj = getattr(obj, comp) except AttributeError: raise ImportError('.'.join(path)) return obj
def escape(s, quote=None): """Replace special characters '&', '<' and '>' by SGML entities.""" s = s.replace("&", "&amp;") # Must be done first! s = s.replace("<", "&lt;") s = s.replace(">", "&gt;") if quote: s = s.replace('"', "&quot;") return s
def mode(nums): """Return most-common number in list. For this function, there will always be a single-most-common value; you do not need to worry about handling cases where more than one item occurs the same number of times. >>> mode([1, 2, 1]) 1 >>> mode([2, 2, 3, 3, 2]) 2 """ # counter = {} # for num in nums: # counter[num] = counter.get(nums.count(num)) # lst.sort() # return lst.pop(0) c = 0 ans = 0 for n in nums: if nums.count(n) > c: ans = n return ans
def _next_power_of_2_or_max(n: int, max_n: int) -> int: """Return the smallest power of 2 greater than or equal to n, with a limit. Useful when used in splitting a tensor into chunks with power-of-2 sizes. """ # special case, just split to 1 element chunks. if n == 0: return 1 orig_n = n n -= 1 n |= n >> 1 n |= n >> 2 n |= n >> 4 n |= n >> 8 n |= n >> 16 n += 1 assert n >= orig_n, f"{n} vs. {orig_n}" assert bin(n).count("1") == 1, bin(n) # Catch the case n is too large for this function. if n > max_n: return max_n return n
def fileheader2dic(head): """ Convert fileheader list into a Python dictionary """ dic = dict() dic["nblocks"] = head[0] dic["ntraces"] = head[1] dic["np"] = head[2] dic["ebytes"] = head[3] dic["tbytes"] = head[4] dic["bbytes"] = head[5] dic["vers_id"] = head[6] dic["status"] = head[7] dic["nbheaders"] = head[8] # unpack the status parameter dic["S_DATA"] = (dic["status"] & 0x1) // 0x1 dic["S_SPEC"] = (dic["status"] & 0x2) // 0x2 dic["S_32"] = (dic["status"] & 0x4) // 0x4 dic["S_FLOAT"] = (dic["status"] & 0x8) // 0x8 dic["S_COMPLEX"] = (dic["status"] & 0x10) // 0x10 dic["S_HYPERCOMPLEX"] = (dic["status"] & 0x20) // 0x20 dic["S_ACQPAR"] = (dic["status"] & 0x80) // 0x80 dic["S_SECND"] = (dic["status"] & 0x100) // 0x100 dic["S_TRANSF"] = (dic["status"] & 0x200) // 0x200 dic["S_NP"] = (dic["status"] & 0x800) // 0x800 dic["S_NF"] = (dic["status"] & 0x1000) // 0x1000 dic["S_NI"] = (dic["status"] & 0x2000) // 0x2000 dic["S_NI2"] = (dic["status"] & 0x4000) // 0x4000 return dic
def get_unique_value_from_summary(test_summary, index): """ Gets list of unique target names """ result = [] for test in test_summary: target_name = test[index] if target_name not in result: result.append(target_name) return sorted(result)
def ensure_datetime(datetime_obj): """If possible/needed, return a real datetime.""" try: return datetime_obj._to_real_datetime() except AttributeError: return datetime_obj
def canPublish_func(val): """ :Description: Example callback function used to populate a jinja2 variable. Note that this function must be reentrant for threaded applications. Args: val (object): generic object for the example Returns: example content (True) """ # do some processing.... return True
def only_true(*elts): """Returns the sublist of elements that evaluate to True.""" return [elt for elt in elts if elt]
def _format_servers_list_power_state(state): """Return a formatted string of a server's power state :param state: the power state number of a server :rtype: a string mapped to the power state number """ power_states = [ 'NOSTATE', # 0x00 'Running', # 0x01 '', # 0x02 'Paused', # 0x03 'Shutdown', # 0x04 '', # 0x05 'Crashed', # 0x06 'Suspended' # 0x07 ] try: return power_states[state] except Exception: return 'N/A'
def nested_get(input_dict, keys_list): """Get method for nested dictionaries. Parameters ---------- input_dict : dict Nested dictionary we want to get a value from. keys_list : list List of of keys pointing to the value to extract. Returns ---------- internal_dict_value : The value that keys in keys_list are pointing to. """ internal_dict_value = input_dict for k in keys_list: internal_dict_value = internal_dict_value.get(k, None) if internal_dict_value is None: return None return internal_dict_value
def cocktail_shaker_sort(unsorted: list) -> list: """ Pure implementation of the cocktail shaker sort algorithm in Python. >>> cocktail_shaker_sort([4, 5, 2, 1, 2]) [1, 2, 2, 4, 5] >>> cocktail_shaker_sort([-4, 5, 0, 1, 2, 11]) [-4, 0, 1, 2, 5, 11] >>> cocktail_shaker_sort([0.1, -2.4, 4.4, 2.2]) [-2.4, 0.1, 2.2, 4.4] >>> cocktail_shaker_sort([1, 2, 3, 4, 5]) [1, 2, 3, 4, 5] >>> cocktail_shaker_sort([-4, -5, -24, -7, -11]) [-24, -11, -7, -5, -4] """ for i in range(len(unsorted) - 1, 0, -1): swapped = False for j in range(i, 0, -1): if unsorted[j] < unsorted[j - 1]: unsorted[j], unsorted[j - 1] = unsorted[j - 1], unsorted[j] swapped = True for j in range(i): if unsorted[j] > unsorted[j + 1]: unsorted[j], unsorted[j + 1] = unsorted[j + 1], unsorted[j] swapped = True if not swapped: break return unsorted
def graph_filename_url(site_id, base_graph_name): """This function returns a two-tuple: graph file name, graph URL. The graph file name is used to save the graph to the file system; the graph URL is used in an HTML site report to load the graph into an image tag. Parameters: 'site_id': the Site ID of the site this graph is related to. 'base_graph_name': a graph file name, not including the Site ID and not including the 'png' extension. For example: 'eco_g1', which will produce a graph file name of 'ANSBG1_eco_g1.png' assuming the Site ID is ANSBG1. """ fn = 'output/images/{}_{}.png'.format(site_id, base_graph_name) url = 'images/{}_{}.png'.format(site_id, base_graph_name) return fn, url
def vocab_unfold(desc, xs, oov0): """Covert a description to a list of word indices.""" # assume desc is the unfolded version of the start of xs unfold = {} for i, unfold_idx in enumerate(desc): fold_idx = xs[i] if fold_idx >= oov0: unfold[fold_idx] = unfold_idx return [unfold.get(x, x) for x in xs]
def navigation(obj): """ Goes through json file and shows its structure """ if isinstance(obj,dict): print() print("This object is dictionary") keys = list(obj.keys()) print() print(keys) print() user_choice = input("Here are keys of this dictionary. \ Please enter name of key you want to see: ") next_element = obj[user_choice] elif isinstance(obj,list): print() print("This object is list.") print() user_choice = input('This list consists of '+str(len(obj))+' elements. \ Please enter number from 0 to '+str(len(obj)-1)+' \ to choose number of element you want to display: ') next_element = obj[int(user_choice)] else: print() user_choice = '' if isinstance(obj,str): user_choice = input('This object is a string. Do you want to display it?\ (Enter yes or no): ') elif isinstance(obj,bool): user_choice = input('This object is a boolean. Do you want to display it?\ (Enter yes or no): ') elif isinstance(obj,int): user_choice = input('This object is a integer. Do you want to display it?\ (Enter yes or no): ') elif isinstance(obj,float): user_choice = input('This object is a float number. Do you want to display it?\ (Enter yes or no): ') else: print(obj) if user_choice == 'yes': print(obj) print() print('This is the end of the file.') return 0 return navigation(next_element)
def add_intf_to_map(intf_map, bridge_or_bond, config_type, intf_index, lacp=False): """Adds an interface to the interface map, after performing validation interface_map has a specific structure. this method checks and inserts keys if they're missing for the bridge or interface being added. :param intf_map: interface map object to which the interface is added :param bridge_or_bond: bridge or bond name to which the interface belongs :param config_type: type of object - either bridge or bond :param intf_index: name or index number of the interface if interface is in nicX format, this will be a numerical index, else name. both would be string. :param lacp: boolean flag, specifying whether intf is part of some form of link aggregation or no. :return: intf_map after being updated """ if bridge_or_bond not in intf_map: intf_map[bridge_or_bond] = {} if 'config_type' not in intf_map[bridge_or_bond]: intf_map[bridge_or_bond]['config_type'] = config_type if 'members' not in intf_map[bridge_or_bond]: intf_map[bridge_or_bond]['members'] = [] if config_type == 'linux_bond' or lacp: # for linux_bond config type, always True. Otherwise, depends on # whether its a bond or individual interface in a bridge. intf_map[bridge_or_bond]['lacp'] = True else: intf_map[bridge_or_bond]['lacp'] = False intf_map[bridge_or_bond]['members'].append(intf_index) return intf_map
def encode_file_name(file_name): """ encodes the file name - i.e ignoring non ASCII chars and removing backslashes Args: file_name (str): name of the file Returns: encoded file name """ return file_name.encode('ascii', 'ignore')
def simple_one_default(one, two='hi'): """Expected simple_one_default __doc__""" return "simple_one_default - Expected result: %s, %s" % (one, two)
def _extract_first_field(data): """Extract first field from a list of fields.""" return list(next(iter(zip(*data))))
def get_person_box_at_frame(tracking_results, target_frame_idx): """Get all the box from the tracking result at frameIdx.""" data = [] for frame_idx, track_id, left, top, width, height in tracking_results: if frame_idx == target_frame_idx: data.append({ "track_id": track_id, "bbox": [left, top, width, height] }) return data
def is_analytics_type(odk_type): """Test if an odk type is suitable for tracking in analytics. Args: odk_type (str): The type to test Returns: Return true if and only if odk_type is good for analytics """ bad_types = ( "type", "calculate", "hidden", "start", "end", "begin ", "deviceid", "simserial", "phonenumber", ) bad = any((odk_type.startswith(bad) for bad in bad_types)) return not bad and odk_type != ""
def int_list_to_str(int_list): """ Reverses a list of utf8 encoded bytes into a string. """ byte_list = [bytes([c]) for c in int_list] return ''.join([c.decode() for c in byte_list])
def find_best_step(v): """ Returns best solution for given value :param v: value :return: best solution or None when no any solutions available """ s = bin(v)[2:] r = s.find("0") l = len(s) - r if (r == -1) or ((l - 1) < 0): return None return 1 << (l - 1)
def parse_bool(name, value): """Parse an environment variable value as a boolean.""" value = value.lower() if value in ("false", "off", "no", "0"): return False if value in ("true", "on", "yes", "1"): return True raise ValueError(f"Invalid boolean environment variable: {name}={value}")
def rotate_jump_code_sql(jumpcode, rotation): """ Create a piece of SQL command that rotates the jumpcode to the right value """ q = str(jumpcode) + "-" + str(jumpcode) + "%12" q += "+(" + str(jumpcode) + "%12+" +str(rotation) + ")%12" return q
def factorial(n): """ On this function we'll calculate the factorial of a number n using recursion """ if n == 1: #base case. Avoiding the infinity loop return 1 else: #calling itself result = ((n) * (factorial(n-1))) #returning the value of n! return result
def is_mostl_numeric(token): """ Checks whether the string contains at least 50% numbers :param token: :return: """ a = len(token) for i in range(0, 10): token = token.replace(str(i), "") if len(token) < 0.5*a and len(token) != a: return True else: return False
def Func_MakeShellWord(str_python): """ Func_MakeShellWord(str_python) Adds shell escape charakters to Python strings """ return str_python.replace('?','\\?').replace('=','\\=').replace(' ','\\ ').replace('&','\\&').replace(':','\\:')
def calcExpGrowth(mgr, asym): """Calculate exponential growth value 'r'""" return 4 * mgr / asym
def encode_time(time): """ Converts a time string in HH:MM format into minutes """ time_list = time.split(":") if len(time_list) >= 2: return (int(time_list[0]) * 60) + int(time_list[1]) return 0
def _combine_overlapping_cities_hashed(my_list): """If two cities' markers overlap, combine them into a single entry. Explanation: Use latitude and longitude rounded to N_DIGITS to create a PKEY for each city. Rounding will cause nearby cities to have the same PKEY. Largest city chosen: As SQL queries make use of 'ORDER BY COUNT() DESC', the largest cities appear and be logged first. This means that e.g. 2 occurrences of Kanata will be merged into Ottawa's 30 occurrences. """ N_DIGITS = 1 merge_dict = {} for dict_ in my_list: city_name = dict_['offering_city'] count = dict_['count'] # Python's 'round' internal func uses technique 'round half to even' # https://en.wikipedia.org/wiki/Rounding#Round_half_to_even lat = round(dict_['offering_lat'], N_DIGITS) if dict_['offering_lat'] != '' else '' lng = round(dict_['offering_lng'], N_DIGITS) if dict_['offering_lng'] != '' else '' pkey = str(lat) + str(lng) # If the city lacks lat, lng values (e.g. a webcast), use the city name as its pkey pkey = pkey if pkey != '' else city_name # Log first occurrence if pkey not in merge_dict: # Log non-rounded values for maximum accuracy merge_dict[pkey] = dict_ # If lat/lng already logged, combine cities else: merge_dict[pkey]['count'] += count # Return merge_dict's values in list results = [value for value in merge_dict.values()] return results
def sort_012(input_list): """ Sort a list containing the integers 0, 1, and 2, in a single traversal :param input_list: list :return: list """ current_index = 0 zero_index = 0 two_index = len(input_list) - 1 while current_index <= two_index: if input_list[current_index] is 2: input_list[current_index], input_list[two_index] = input_list[two_index], input_list[current_index] two_index -= 1 continue if input_list[current_index] is 0: input_list[current_index], input_list[zero_index] = input_list[zero_index], input_list[current_index] zero_index += 1 current_index += 1 return input_list
def score(goal, test_string): """compare two input strings and return decimal value of quotient likeness""" #goal = 'methinks it is like a weasel' num_equal = 0 for i in range(len(goal)): if goal[i] == test_string[i]: num_equal += 1 return num_equal / len(goal)
def bi_var_equal(var1, unifier1, var2, unifier2): """Check var equality. Returns True iff variable VAR1 in unifier UNIFIER1 is the same variable as VAR2 in UNIFIER2. """ return (var1 == var2 and unifier1 is unifier2)
def arraysize(x): """ Returns the number of elements in x, where x is an array. Args: x: the array for which you want to get the number of elements. Returns: int: the size of the array. If **x** is not an array, this function returns 0. """ if '__len__' in dir(x): return len(x) return 0
def test_policy_category_value(recipe): """Test that policy category is Testing. Args: recipe: Recipe object. Returns: Tuple of Bool: Failure or success, and a string describing the test and result. """ result = False description = "POLICY_CATEGORY is 'Testing'." result = (recipe["Input"].get("POLICY_CATEGORY") == "Testing") return (result, description)
def is_valid_position(position: str) -> bool: """Filters out players without a valid position. Args: position (str): Player's current position Returns: bool: True if the player has a valid position, False otherwise """ valid_position_values = ["TE", "RB", "WR", "QB"] if position not in valid_position_values: return False else: return True
def dot(A, b, transpose=False): """ usual dot product of "matrix" A with "vector" b. ``A[i]`` is the i-th row of A. With ``transpose=True``, A transposed is used. """ if not transpose: return [sum(A[i][j] * b[j] for j in range(len(b))) for i in range(len(A))] else: return [sum(A[j][i] * b[j] for j in range(len(b))) for i in range(len(A[0]))]
def is_multiply_of(value, multiply): """Check if value is multiply of multiply.""" return value % multiply == 0
def _check_value(expected_value, received_value): """Check that the received value contains the expected value. Checks that the received value (a hex string) contains the expected value (a string). If the received value is longer than the expected value, make sure any remaining characters are zeros. Args: expected_value (str): the expected hex string received_value (str): the string to verify Returns: bool: True if the values match, False otherwise """ char = None # Comparisons are lower case received_value = received_value.lower() # Convert the expected value to hex characters expected_value_hex = "".join( "{:02x}".format(ord(c)) for c in expected_value).lower() # Make sure received value is at least as long as expected if len(received_value) < len(expected_value_hex): return False # Make sure received value starts with the expected value if expected_value_hex not in received_value[:len(expected_value_hex)]: return False # Make sure all characters after the expected value are zeros (if any) for char in received_value[len(expected_value_hex):]: if char != "0": return False return True
def isMatchDontCare(ttGold, testRow): """ Helper function for comparing truth table entries - accounting for don't cares Arguments: ttGold {[str]} -- Row from the LUT tt that may contain don't care inputs testRow {[str]} -- Row from other function to check as a match against ttGold Returns: boolean -- indicates whether or not the given inputs are a functional match """ for i in range(len(ttGold)): if testRow[i] == "-": continue elif ttGold[i] != testRow[i]: return False return True
def check_fibonacci(n): """Returns the nth Fibonacci number for n up to 40""" fib = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181,6765, 10946, 17711, 28657, 46368, 75025, 121393, 196418, 317811, 514229, 832040, 1346269, 2178309, 3524578, 5702887, 9227465, 14930352, 24157817, 39088169, 63245986, 102334155] if n > 40 or n < 1: print('Sorry, n should be 40 or less and greater than 0') return 0 else: return fib[n-1]
def defect(p=1/3, n=1): """ return the probability of 1st defect is found during the nth inspection """ return (1-p)**(n-1)*p
def escape(s, quote=True): """ Replace special characters "&", "<" and ">" to HTML-safe sequences. If the optional flag quote is true (the default), the quotation mark characters, both double quote (") and single quote (') characters are also translated. """ s = s.replace('&', '&amp;') s = s.replace('<', '&lt;') s = s.replace('>', '&gt;') if quote: s = s.replace('"', '&quot;') s = s.replace("'", '&#x27;') return s
def gcf(m: int, n: int) -> int: """Find gcf of m and n.""" while n: m, n = n, m % n return m
def without_duplicates(seq): """Returns a copy of the list with duplicates removed while preserving order. As seen in http://stackoverflow.com/questions/480214/how-do-you-remove-duplicates-from-a-list-in-python-whilst-preserving-order """ seen = set() seen_add = seen.add return [x for x in seq if not (x in seen or seen_add(x))]
def to_csv(data, headers): """ convert a set of data to a csv, based on header column names""" rows = [",".join(headers)] for datarow in data: rowdata = [str(datarow.get(h, "")) for h in headers] rows += [",".join(rowdata)] csv = "\n".join(rows) return csv.encode()
def twos_comp(val, bits): """compute the 2's compliment of int value val""" if( (val&(1<<(bits-1))) != 0 ): val = val - (1<<bits) return val
def cleansignature(value): """ **Filter** Removes ``?`` and everything after from urls. for example: .. code-block:: html {{object.file.url|cleansignature}} """ if '?' not in value: return value t = value.index('?') return value[0:t]
def cascade(s1,s2): """Cascade returns the cascaded sparameters of s1 and s2. s1 and s2 should be in complex list form [[f,S11,S12,S21,S22]...] and the returned sparameters will be in the same format. Assumes that s1,s2 have the same frequencies. If 1-S2_22*S1_11 is zero we add a small non zero real part or loss.""" out_sparameters=[] for row_index,row in enumerate(s1): [f1,S1_11,S1_12,S1_21,S1_22]=row [f2,S2_11,S2_12,S2_21,S2_22]=s2[row_index] if f1!=f2: raise TypeError("Frequencies do not match! F lists must be the same") denominator=(1-S1_22*S2_11) if denominator ==complex(0,0): denominator=complex(10**-20,0) S11=S1_11+S2_11*(S1_12*S1_21)/denominator S12=S1_12*S2_12/(denominator) S21=S1_21*S2_21/denominator S22=S2_22+S1_22*(S2_12*S2_21)/denominator new_row=[f1,S11,S12,S21,S22] out_sparameters.append(new_row) return out_sparameters
def energy_value(h, J, sol): """ Obtain energy of an Ising solution for a given Ising problem (h,J). :param h: External magnectic term of the Ising problem. List. :param J: Interaction term of the Ising problem. Dictionary. :param sol: Ising solution. List. :return: Energy of the Ising string. :rtype: Integer or float. """ ener_ising = 0 for elm in J.keys(): if elm[0] == elm[1]: raise TypeError("""Interaction term must connect two different variables""") else: ener_ising += J[elm] * int(sol[elm[0]]) * int(sol[elm[1]]) for i in range(len(h)): ener_ising += h[i] * int(sol[i]) return ener_ising
def consecutiveSlopes(ys, xs): """ Get slopes of consecutive data points. """ slopes = [] samplePeriod = xs[1]-xs[0] for i in range(len(ys)-1): slope = (ys[i+1]-ys[i])/(samplePeriod) slopes.append(slope) return slopes
def switch_string_to_numeric(argument): """ Switch status string to numeric status (FLAT - POOR: 0, POOR - POOR TO FAIR = 1, FAIR TO GOOD - EPIC = 2) """ switcher = { "FLAT": 0, "VERY POOR": 0, "POOR": 0, "POOR TO FAIR":1, "FAIR":1, "FAIR TO GOOD":2, "GOOD":2, "VERY GOOD":2, "GOOD TO EPIC":2, "EPIC":2 } # get() method of dictionary data type returns # value of passed argument if it is present # in dictionary otherwise second argument will # be assigned as default value of passed argument return switcher.get(argument, "nothing")
def frenchText(frenchInput): """ This function returns translation if input matches """ if frenchInput == 'Bonjour': return 'Hello'
def page_data(total_count: int, paginator: dict) -> dict: """Build a payload object out of paginator data.""" return { "total_count": total_count, "page": paginator["page"], "max_per_page": paginator["max_per_page"], }
def get_bottle_message(num_of_bottles): """ Parse Bottle Message """ return ( "No more bottles" if num_of_bottles == 0 else f"{num_of_bottles} bottle" if num_of_bottles == 1 else f"{num_of_bottles} bottles" )
def filter_by_title_summary(strict, gse_gsm_info): """ Filter GSE by title and/or summary Args: strict: boolean to indicate if filter by both title and summary gse_gsm_info: the GSE and GSM info tuple Returns: filtered results """ gse_id, gsm_info = gse_gsm_info is_pert_summary, is_pert_title = map(eval, gsm_info[2:4]) if strict: return is_pert_summary and is_pert_title else: return is_pert_summary or is_pert_title
def format_cpf(value): """ This function returns the Brazilian CPF with the normal format. :param value is a string with the number of Brazilian CPF like 12345678911 :return: Return a sting with teh number in the normal format like 123.456.789-11 """ return f'{value[:3]}.{value[3:6]}.{value[6:9]}-{value[9:]}'
def rgb_to_RGB(r, g, b): """ Convert rgb values to RGB values :param r,g,b: (0,1) range floats :return: a 3 element tuple of RGB values in the range (0, 255) """ return (int(r * 255), int(g * 255), int(b * 255))
def make_seqs(a, b): """ Makes mutliple sequences of length b, from 0 to a. The sequences are represented as tuples with start and stop numbers. Note that the stop number of one sequence is the start number for the next one, meaning that the stop number is NOT included. """ seqs = [] x = 0 while x < a: x2 = x + b if x2 > a: x2 = a seqs.append( (x, x2) ) x = x2 return seqs
def format_size(size_bytes): """ Format size in bytes approximately as B/kB/MB/GB/... >>> format_size(2094521) 2.1 MB """ if size_bytes < 1e3: return "{} B".format(size_bytes) elif size_bytes < 1e6: return "{:.1} kB".format(size_bytes / 1e3) elif size_bytes < 1e9: return "{:.1} MB".format(size_bytes / 1e6) elif size_bytes < 1e12: return "{:.1} GB".format(size_bytes / 1e9) else: return "{:.1} TB".format(size_bytes / 1e12)
def count_set_bits_with_bitwise_and_simple(number): """Counts set bits in a decimal number Parameters ---------- number : int decimal number e.g Returns ------- int a count of set bits in a number >>> count_set_bits_with_bitwise_and_simple(125) 6 """ set_bits_count = 0 while number: set_bits_count += number & 1 number = number >> 1 return set_bits_count
def order(x, count=0): """Returns the base 10 order of magnitude of a number""" if x / 10 >= 1: count += order(x / 10, count) + 1 return count
def i_to_n(i, n): """ Translate index i, ranging from 0 to n-1 into a number from -(n-1)/2 through (n-1)/2 This is necessary to translate from an index to a physical Fourier mode number. """ cutoff = (n-1)/2 return i-cutoff
def BackslashEscape(s, meta_chars): # type: (str, str) -> str """Escaped certain characters with backslashes. Used for shell syntax (i.e. quoting completed filenames), globs, and EREs. """ escaped = [] for c in s: if c in meta_chars: escaped.append('\\') escaped.append(c) return ''.join(escaped)
def unescape(s): """Replace escaped HTML-special characters by their originals""" if '&' not in s: return s s = s.replace("&lt;", "<") s = s.replace("&gt;", ">") s = s.replace("&apos;", "'") s = s.replace("&quot;", '"') s = s.replace("&amp;", "&") # Must be last return s
def compute_time(sign, FS): """Creates the signal correspondent time array. """ time = range(len(sign)) time = [float(x)/FS for x in time] return time
def parse_comment(r): """ Used to parse the extra comment. """ return str(r.get("opmerk", ""))
def count_substring(string, sub_string): """ Cuenta cuantas veces aparece el sub_string en el string Args: string: (string) sub_string: (string) rerturn : int """ return string.count(sub_string)
def getAllStreetPointsLookingForName(allStreetInfoOSM, streetName): """ getAllStreetPointsLookingForName(allStreetInfoOSM, streetName) Get list of points of all streets which all Streets in Info OSM are the same as streetName Parameters ---------- allStreetInfoOSM : list of dictionary List with the OSM structure for each street. streetName : String Name of the string what need to be compared. Returns ------- List Get all points where the street are the same. """ lstPoints = [] for street in allStreetInfoOSM: if street['type'].strip().lower() == 'linestring': if streetName.strip().lower() in street['properties'][u'name'].strip().lower(): if len(street['geometry']) > 0: for point in street['geometry']: if point not in lstPoints: lstPoints.append(point) return lstPoints
def remove_end_from_pathname(filen, end='.image'): """ Retrieve the file name excluding an ending extension or terminating string. Parameters ---------- filen : str end : str End to file name to remove. If an extension, include the period, e.g. ".image". """ if not filen.endswith(end): raise ValueError('Path does not end in "{0}": {1}'.format(end, filen)) assert len(filen) > len(end) stem = filen[:-len(end)] return stem
def convert_to_underscores(name): """ This function will convert name to underscores_name :param name: name to convert :return: parsed name """ return "_".join(name.lower().split(" "))
def noun(name: str, num: int) -> str: """ This function returns a noun in it's right for a specific quantity :param name: :param num: :return: """ if num == 0 or num > 1: return name + "s" return name
def check_if_errors_exist(error_dict): """This function checks that all the values of the `error_dict` dictionary evaluate to `None`. If they don't, it means that there exists errors and it returns `True`, otherwise `False`.""" if error_dict is None: # there are no errors return False return any(value is not None for value in error_dict.values())
def chopping_frequency(frequency1, frequency2): """Compute the chopping frequency Parameters ---------- frequency1: int, float frequency2: int, float Returns ------- out: int, float """ return 2 * (frequency2 - frequency1)
def _vectorize_input_string(input_ingredient: str, word_index: dict): """ Converts parsed input ingredient to a list of indexs. Where each word is converted into a number :param input_ingredients: Ingredient String e.g. "1 red apple" :param word_index: :return: List of words numeric representations [1, 120, 3] """ # Convert to list of words word_list = input_ingredient.split(" ") idx_list = [] # Convert list to indexes - replace with OOV token if not in word list for word in word_list: if word in word_index: idx_list.append(word_index[word]) else: idx_list.append(word_index['<OOV>']) return idx_list
def is_dna(a): """Return True if input contains only DNA characters, otherwise return False Args: a (str): string to test Returns: bool: True if all characters are DNA, otherwise False """ if len(a) == 0: return(False) dna_chars = 'atcgnATCGN' return all(i in dna_chars for i in a)
def create_param_string(data, cols): """ Create a param string given the provided data and the columns that were determined to exist in the provided csv. We don't want NULL values to be inserted into the param string. Args: data: One row of data from the provided csv cols: The columns that have been determined to exist in this csv Returns: A dict containing all the FPDS query columns that the provided file has """ param_string = '' for col in cols: if data[col]: param_string += '{}:"{}" '.format(cols[col], data[col]) return param_string
def distance(a, b): """Returns the manhattan distance between the two points a and b.""" return abs(a[0] - b[0]) + abs(a[1] - b[1])
def _convert(lines): """Convert compiled .ui file from PySide2 to Qt.py Arguments: lines (list): Each line of of .ui file Usage: >> with open("myui.py") as f: .. lines = _convert(f.readlines()) """ def parse(line): line = line.replace("from PySide2 import", "from Qt import QtCompat,") line = line.replace("QtWidgets.QApplication.translate", "QtCompat.translate") if "QtCore.SIGNAL" in line: raise NotImplementedError("QtCore.SIGNAL is missing from PyQt5 " "and so Qt.py does not support it: you " "should avoid defining signals inside " "your ui files.") return line parsed = list() for line in lines: line = parse(line) parsed.append(line) return parsed
def sindex(i,j,qi,qj): """ Returns the location of {i,j} in the set {{0,0},{0,1},...,{0,qj-1},...{qi-1,qj-1}}. """ return int((i * qj) + j)
def factorial2(x): """ second method with exploating recursion """ if x == 1: return 1 else: return x*factorial2(x-1)
def update_ave_depth(leaf_depth_sum, set_of_leaves): """ Average tree depth update. Inputs: - leaf_depth_sum: The sum of the depth values of all leaf nodes. - set_of_leaves: A python set of leaf node ids. Output: - ave_depth: The average depth of the tree. """ ave_depth = leaf_depth_sum/len(set_of_leaves) return ave_depth
def _norm_path(path): """Returns a path with '/' and remove the trailing slash.""" path = path.replace("\\", "/") if path[-1] == "/": path = path[:-1] return path
def _split_uri(uri): """ Split the scheme and the remainder of the URI. >>> _split_uri('http://test.com/something.txt') ('http', '//test.com/something.txt') >>> _split_uri('eods:LS7_ETM_SYS_P31_GALPGS01-002_101_065_20160127') ('eods', 'LS7_ETM_SYS_P31_GALPGS01-002_101_065_20160127') >>> _split_uri('file://rhe-test-dev.prod.lan/data/fromASA/LANDSAT-7.89274.S4A2C1D3R3') ('file', '//rhe-test-dev.prod.lan/data/fromASA/LANDSAT-7.89274.S4A2C1D3R3') >>> _split_uri('file:///C:/tmp/first/something.yaml') ('file', '///C:/tmp/first/something.yaml') """ comp = uri.split(':') scheme = comp[0] body = ':'.join(comp[1:]) return scheme, body
def unpack_bits(bits): """Unpack ID3's syncsafe 7bit number format.""" value = 0 for chunk in bits: value = value << 7 value = value | chunk return value
def str2bool(v): """ Convert strings with Boolean meaning to Boolean variables. :param v: a string to be converted. :return: a boolean variable that corresponds to the input string """ if v.lower() in ('yes', 'true', 't', 'y', '1'): return True elif v.lower() in ('no', 'false', 'f', 'n', '0'): return False else: raise TypeError('Boolean value expected.')
def _splitext(p): """ """ from os.path import splitext try: s = splitext(p) except (AttributeError, TypeError): # Added TypeError for python>=3.6 s = (None, None) return s
def fill_gap_to_win(board, ai_mark): """Put a third mark ('ai_mark) to win in the gap on the line if doing so returns True, otherwise False.""" # copy of board board_copy = board.copy() # Changing 'board' lines from vertical to horizontal and put in 'tmp_list', # this means that the vertical lines of the list are the horizontal tmp_vertical = [] for i in range(3): tmp_in_v = [] for j in range(3): tmp_in_v.append(board[j][i]) tmp_vertical.append(tmp_in_v) # Adding two lists board_copy, tmp_list and two diagonal lines lines = board_copy + tmp_vertical + \ [[board[0][0], board[1][1], board[2][2]], [board[0][2], board[1][1], board[2][0]]] counter = 0 row = 0 for line in lines: if counter <= 2: # Searching in horizontal lines two marks and in this case is adding third mark if line.count(ai_mark) == 2 and line.count(".") == 1: board[row][line.index(".")] = ai_mark return True row += 1 elif 2 < counter <= 5: # Searching in vertical lines two marks and in this case is adding third mark if counter == 3: row = 0 if line.count(ai_mark) == 2 and line.count(".") == 1: board[line.index(".")][row] = ai_mark return True row += 1 elif counter > 5: # Searching in diagonal lines two marks and in this case is adding third mark if counter == 6: if line.count(ai_mark) == 2 and line.count(".") == 1: if line.index(".") == 0: board[0][0] = ai_mark return True elif line.index(".") == 1: board[1][1] = ai_mark return True elif line.index(".") == 2: board[2][2] = ai_mark return True if counter == 7: if line.count(ai_mark) == 2 and line.count(".") == 1: if line.index(".") == 0: board[0][2] = ai_mark return True elif line.index(".") == 1: board[1][1] = ai_mark return True elif line.index(".") == 2: board[2][0] = ai_mark return True counter += 1 return False
def get_aparc_aseg(files): """Return the aparc+aseg.mgz file""" for name in files: if 'aparc+aseg' in name: return name raise ValueError('aparc+aseg.mgz not found')
def body(prg): """ Code body """ return prg[2:]
def ihead(store, n=1): """Get the first item of an iterable, or a list of the first n items""" if n == 1: for item in iter(store): return item else: return [item for i, item in enumerate(store) if i < n]
def build_flavor_dict(flavor_list): """ Returns a dictionary of flavors. Key - flavor id, value - flavor object. :param flavor_list: a list of flavors as returned from nova client. :type flavor_list: list :return: Dictionary containing flavors. Key - flavor id, value - flavor object """ flavor_dict = {} for flavor in flavor_list: flavor_dict[flavor.id] = flavor return flavor_dict
def formset_model_name(value): """ Return the model verbose name of a formset """ try: return value.model._meta.verbose_name except AttributeError: return str(value.__class__.__name__)