content
stringlengths
42
6.51k
def shorten_to_len(text, max_len): """ Take a text of arbitrary length and split on new lines. Keep adding whole lines until max_len is reached or surpassed. Returns the new shorter text. """ shorter_text = '' text_parts = text.split("\n") while text_parts and len(shorter_text) < max_len: shorter_text += text_parts[0] + "\n" text_parts = text_parts[1:] return shorter_text.rstrip()
def av_len(ans): """ input:[[3, 4], 7, 9, 11, [11, 12, 13, 14], [12, 13, 14], [13, 14], 16, [16, 17, 18], [17, 18], 20, [20, 21]] output:[[3, 4], 7, 9, [11, 12, 13, 14], [16, 17, 18], [20, 21]] """ true_major = ans[:] for i in range(len(ans)): try: if len(ans[i]): for j in range(i+1,i+len(ans[i])-1): try: true_major.remove(ans[j]) except ValueError: pass except TypeError: pass az = true_major[:] for k in range(len(true_major)): try: if len(true_major[k])>1: try: az.remove(true_major[k+1]) except: pass except: pass return az
def _validate_manifest_download(expected_objs, download_results): """ Given a list of expected object names and a list of dictionaries of `SwiftPath.download` results, verify that all expected objects are in the download results. """ downloaded_objs = { r['object'] for r in download_results if r['success'] and r['action'] in ('download_object',) } return set(expected_objs).issubset(downloaded_objs)
def get_party_name(party): """ Normalize the AP party name to our format """ parties = { 'GOP': 'Republican', 'Dem': 'Democrat', 'Lib': 'Libertarian', 'Grn': 'Green' } return parties[party]
def asbool(value, true=(b'true', u'true'), false=(b'false', u'false')): """Return string as bool if possible, else raise TypeError. >>> asbool(b' False ') False """ value = value.strip().lower() if value in true: # might raise UnicodeWarning/BytesWarning return True if value in false: return False raise TypeError()
def parse_grid(lines): """Parse grid from lines to list of lists.""" return [list(line) for line in lines]
def board_spacing(edges, size): """Calculate board spacing""" space_x = (edges[1][0] - edges[0][0]) / float(size-1) space_y = (edges[1][1] - edges[0][1]) / float(size-1) return space_x, space_y
def _ord(of_int: int) -> str: """For Roam""" return str(of_int) + ( "th" if 4 <= of_int % 100 <= 20 else {1: "st", 2: "nd", 3: "rd"}.get(of_int % 10, "th") )
def task4(arg4): """ Last task that depends on the output of the third task. Does not return any results, as this is the last task. """ # Report results pass # End of tasks return False
def mouse_body_size_constants(body_scale = 1,use_old=False,use_experimental=False): """ Now, we make a function, which spits out the constants """ ## HIP is a prolate ellipsoid, centered along the x axis a_hip_min = 0.01/2 #m a_hip_max = 0.055/2 #m b_hip_min = 0.03/2 #m b_hip_max = 0.035/2 #m, was 0.046, which was too much d_hip = 0.019 #m # converting it to the new terminology a_hip_0 = body_scale*a_hip_min #m a_hip_delta = body_scale*(a_hip_max - a_hip_min) #m b_hip_0 = body_scale*b_hip_min #m b_hip_delta = body_scale*(b_hip_max - b_hip_min) #m ## NOSE is prolate ellipsoid, also along the head direction vector # here, there is no re-scaling a_nose = body_scale*0.045/2 #m was .04 b_nose = body_scale*0.025/2 #m d_nose = body_scale*0.016 #m if use_old: ## HIP is a prolate ellipsoid, centered along the x axis a_hip_min = 0.018 #m a_hip_max = 0.025 #m b_hip_min = 0.011 #m b_hip_max = 0.02 #m d_hip = 0.015 #m # converting it to the new terminology a_hip_0 = a_hip_min #m a_hip_delta = a_hip_max - a_hip_min #m b_hip_0 = b_hip_min #m b_hip_delta = b_hip_max - b_hip_min #m ## NOSE is prolate ellipsoid, also along the head direction vector # here, there is no re-scaling a_nose = 0.020 #m b_nose = 0.010 #m d_nose = 0.014 #m if use_experimental: ## HIP is a prolate ellipsoid, centered along the x axis a_hip_min = 0.01/2 #m a_hip_max = 0.1/2 #m b_hip_min = 0.03/2 #m b_hip_max = 0.035/2 #m, was 0.046, which was too much d_hip = 0.019 #m # converting it to the new terminology a_hip_0 = body_scale*a_hip_min #m a_hip_delta = body_scale*(a_hip_max - a_hip_min) #m b_hip_0 = body_scale*b_hip_min #m b_hip_delta = body_scale*(b_hip_max - b_hip_min) #m ## NOSE is prolate ellipsoid, also along the head direction vector # here, there is no re-scaling a_nose = body_scale*0.045/2 #m was .04 b_nose = body_scale*0.025/2 #m d_nose = body_scale*0.016 #m a_nose = 1e-30 b_nose = 1e-30 return a_hip_0,a_hip_delta,b_hip_0,b_hip_delta,d_hip,a_nose,b_nose,d_nose
def unpack_and_add(l, c): """Convenience function to allow me to add to an existing list without altering that list.""" t = [a for a in l] t.append(c) return(t)
def flatten(iterable): """Flatten a list, tuple, or other iterable so that nested iterables are combined into a single list. :param iterable: The iterable to be flattened. Each element is also an interable. :rtype: list """ iterator = iter(iterable) try: return sum(iterator, next(iterator)) except StopIteration: return []
def bytes_to_string (bytes): """ Convert a byte array into a string aa:bb:cc """ return ":".join(["{:02x}".format(int(ord(c))) for c in bytes])
def factorial(n): """Calculates factorial of a given number integer n>0.""" """Returns None if otherwise""" try: if n == 0: return 1 else: return n * factorial(n-1) except: return None
def _wrap_config_compilers_xml(inner_string): """Utility function to create a config_compilers XML string. Pass this function a string containing <compiler> elements, and it will add the necessary header/footer to the file. """ _xml_template = """<?xml version="1.0" encoding="UTF-8"?> <config_compilers> {} </config_compilers> """ return _xml_template.format(inner_string)
def convert_feature_coords_to_input_b_box(anchor_point_x_coord,anchor_point_y_coord,feature_to_input): """Convert feature map coordinates to a bounding box in the input space in a dictionary """ anchor_point_in_input_space = { "x_centre" : anchor_point_x_coord*feature_to_input["x_scale"] + feature_to_input["x_offset"] ,"y_centre" : anchor_point_y_coord*feature_to_input["y_scale"] + feature_to_input["y_offset"] } box_width = feature_to_input["x_scale"] box_height = feature_to_input["y_scale"] bounding_box = { "x1" : int(round(anchor_point_in_input_space["x_centre"] - box_width/2)) ,"y1" : int(round(anchor_point_in_input_space["y_centre"] - box_height/2)) ,"x2" : int(round(anchor_point_in_input_space["x_centre"] + box_width/2)) ,"y2" : int(round(anchor_point_in_input_space["y_centre"] + box_height/2)) } return bounding_box
def getPhaseEncoding(DWI,ADNI_boolean=True): """Returns 'AP' (the phase encoding for ADNI images). Eventually, code this to extract the PE direction from the input DWI.""" if ADNI_boolean: pe_dir = 'AP' else: # Extract the phase encoding direction from the DWI??? pe_dir = 'LR' return pe_dir
def _IndentString(source_string, indentation): """Indent string some number of characters.""" lines = [(indentation * ' ') + line for line in source_string.splitlines(True)] return ''.join(lines)
def class_from_module_path(module_path): """Given the module name and path of a class, tries to retrieve the class. The loaded class can be used to instantiate new objects. """ import importlib # load the module, will raise ImportError if module cannot be loaded if "." in module_path: module_name, _, class_name = module_path.rpartition('.') m = importlib.import_module(module_name) # get the class, will raise AttributeError if class cannot be found return getattr(m, class_name) else: return globals()[module_path]
def escape_quotes(my_string): """ convert " quotes in to \" :param my_value the string to be escaped :return: string with escaped """ data = my_string.split('"') new_string = "" for item in data: if item == data[-1]: new_string = new_string + item else: new_string = new_string + item + '\\"' # remove new line new_string2 = "" data = new_string.split('\n') for item in data: new_string2 = new_string2 + item # remove carrage return new_string3 = "" data = new_string2.split('\r') for item in data: new_string3 = new_string3 + item return new_string3
def vlq(value): """variable-len quantity as bytes""" bts = [value & 0x7f] while True: value = value >> 7 if not value: break bts.insert(0, 0x80 | value & 0x7f) return bytes(bts)
def insertion_sort(L): """Implementation of insertion sort.""" n = len(L) if n < 2: return L for i in range(1, n): tmp = L[i] j = i while j > 0 and tmp < L[j - 1]: L[j] = L[j - 1] j -= 1 L[j] = tmp
def retirement_plan (estimated_savings, state_costs): """filter out with states and their cost of living comfortably. args: estimated_savings(float): The customer's expected amount of savings. state_cost: The list of available states of where the users wants to live QUESTIONS TO ANSWER: "WHERE DO YOU WANT TO LIVE/ HOW MUCH DO YOU PLAN OF SAVING." Return: a list of available state depending on how much the customer has in savings """ state_approval_list=[] for state in state_costs: if estimated_savings >= float(state[2]): state_approval_list.append(state) return state_approval_list
def adjacency_to_edges(nodes, adjacency, node_source): """ Construct edges for nodes based on adjacency. Edges are created for every node in `nodes` based on the neighbors of the node in adjacency if the neighbor node is also in `node_source`. The source of adjacency information would normally be self.graph and self.nodes for `node_source`. However, `node_source may` also equal `nodes` to return edges for the isolated graph. :param nodes: nodes to return edges for :type nodes: list :param adjacency: node adjacency (self.graph) :type adjacency: dict :param node_source: other nodes to consider when creating edges :type node_source: list """ edges = [] for node in nodes: edges.extend([tuple([node, e]) for e in adjacency[node] if e in node_source]) return edges
def get_matrix38(): """ Return the matrix with ID 38. """ return [ [1.0000000, 0.5186014, 0.0000000], [0.5186014, 1.0000000, 0.0000000], [0.0000000, 0.0000000, 1.0000000], ]
def _count_chunks(matches): """ Counts the fewest possible number of chunks such that matched unigrams of each chunk are adjacent to each other. This is used to caluclate the fragmentation part of the metric. :param matches: list containing a mapping of matched words (output of allign_words) :return: Number of chunks a sentence is divided into post allignment :rtype: int """ i = 0 chunks = 1 while i < len(matches) - 1: if (matches[i + 1][0] == matches[i][0] + 1) and ( matches[i + 1][1] == matches[i][1] + 1 ): i += 1 continue i += 1 chunks += 1 return chunks
def get_ddy(tau, alpha_z, beta_z, g, y, dy, f): """ Equation [1] :param tau: time constant """ return (1.0 / tau**2) * (alpha_z * (beta_z * (g - y) - tau*dy) + f)
def is_hex_str(test_str): """Returns True if the string appears to be a valid hexidecimal string.""" try: return True except ValueError: pass return False
def get_diagonals(arr): """returns the diagonals for a given matrix """ d1, d2 = [], [] for row in range(len(arr)): forwardDiag = arr[row][row] d1.append(forwardDiag) backwardDiag = arr[row][len(arr[row]) - 1 - row] d2.append(backwardDiag) return d1, d2
def update_dependencies(new_dependencies, existing_dependencies): """Update the source package's existing dependencies. When a user passes additional dependencies from the command line, these dependencies will be added to the source package's existing dependencies. If the dependencies passed from the command line are existing dependencies, these existing dependencies are overwritten. Positional arguments: new_dependencies (List[str]) -- the dependencies passed from the command line existing_dependencies (List[str]) -- the dependencies found in the source package's index.json file """ # split dependencies away from their version numbers since we need the names # in order to evaluate duplication dependency_names = set(dependency.split()[0] for dependency in new_dependencies) index_dependency_names = set(index.split()[0] for index in existing_dependencies) repeated_packages = index_dependency_names.intersection(dependency_names) if len(repeated_packages) > 0: for index_dependency in existing_dependencies: for dependency in repeated_packages: if index_dependency.startswith(dependency): existing_dependencies.remove(index_dependency) existing_dependencies.extend(new_dependencies) return existing_dependencies
def get_map_data(year, loc_dict, years_dict): """ Returns data needed for map creation for given year as a list. :param year: integer, year :param loc_dict: dictionary, keys - location strings, values - geo data :param years_dict: dictionary, keys - years, values - film dictionaries :return map_data: list of tuples as (film, location, coordinates) :return len(map_data): integer, number of all films available for given year """ map_data = [] t = years_dict[year] for film in t: processed = [] for location in t[film]: if location in loc_dict: # check if coordinates of locat. available if location in processed: pass else: l = loc_dict[location] coordinates = [l[0]['geometry']['location']['lat'], l[0]['geometry']['location']['lng']] map_data.append((film, location, coordinates)) processed.append(location) else: pass return map_data, len(map_data)
def change_state(current_state, new_state): """ Change the current state dict to reflect state param: new_state return current_state """ current_state['/state'] = new_state print("New State Set to {0}".format(current_state)) return current_state
def cloudfront_access_control_allow_methods(access_control_allow_methods): """ Property: AccessControlAllowMethods.Items """ valid_values = ["GET", "DELETE", "HEAD", "OPTIONS", "PATCH", "POST", "PUT", "ALL"] if not isinstance(access_control_allow_methods, list): raise TypeError("AccessControlAllowMethods is not a list") for method in access_control_allow_methods: if method not in valid_values: raise ValueError( 'AccessControlAllowMethods must be one of: "%s"' % (", ".join(valid_values)) ) return access_control_allow_methods
def inv_pos_item_score(i): """Function returns the final rank as a simple inverse of the item position. Parameters ---------- i : int Item position. Returns ------- result : float Inverted position rank. """ result = 1 / i return result
def hamming(s1, s2): """Calculate the Hamming distance between two bit lists""" assert len(s1) == len(s2) return sum(c1 != c2 for c1, c2 in zip(s1, s2))
def rev(l): """ >>> rev([20, 13, 8, 19, 19, 4, 18, 19, 8, 18, 1, 4, 19, 19, 4, 17]) 'unittestisbetter' """ t = "" for c in l: t += chr(c + 97) return t
def get_digit_count(number): """ https://stackoverflow.com/questions/2189800/length-of-an-integer-in-python # Using log10 is a mathematician's solution # Using len(str()) is a programmer's solution # The mathematician's solution is O(1) [NOTE: Actually not O(1)?] # The programmer's solution in O(log10 n) # In fact, log10 probably performs in slower than O(log n) # for a faster O(log n) mathematical solution, # first approximate with b = int(n.bit_length() * math.log10(2)), # then round up if necessary by checking if n == 0 or abs(n) >= 10**b # My bad: technically floating-point math is greater than O(log n) # ...n.bit_length() * math.log10(2) is only very marginally faster than math.log10(n) # ...requires exponentiation for its check, (10**b), which takes up most of the time # math.log10(n) requires the same check at around 999999999999999 # Under 10**12, len(str(n)) is the fastest # Above 10**12, log10 is the fastest, but above 10**15, it is incorrect # Around 10**100 (~log10 with the 10**b check) begins to beat out len(str(n)) :rtype: boolean :param number: number :return: digit_count """ # Shall we count the negative sign on negative numbers? # Shall we count the decimal place symbol on decimals/floats? # Easy, sad option: convert the number to a string and count the characters # len(str(123)) # len(str(abs(v))) # # try: # # number = float(number) # # except ValueError: # # return None # if number > 0: # digit_count = int(math.log10(number)) + 1 # elif number == 0: # digit_count = 1 # elif number < 0: # digit_count = int(math.log10(-number)) + 2 # +1 if you do not want to count the '-' # else: # digit_count = None digit_count = len(str(number)) return digit_count
def build_resilient_url(host, port): """ build basic url to resilient instance :param host: host name :param port: port :return: base url """ if host.lower().startswith("http"): return "{0}:{1}".format(host, port) return "https://{0}:{1}".format(host, port)
def check_tag(tag_token, content) : """ Check tag of news not in content of the news :param tag_token: :param content: :return: list of tags satisfy exist in the content of news """ tag = tag_token.split(";") remove = [] for tg in tag : if tg.strip().lower().replace("_"," ") not in content.strip().replace("_"," ") : remove.append(tg) result = [tg for tg in tag if tg not in remove] print("check tag" , result) return result
def escape_html(text: str): """ return escaped text :param text: text to escape :return: """ return text.replace('<', '&lt;').replace('>', '&gt;')
def get_parent_directory_name(path: str) -> str: """:returns: the path of the containing directory""" return "/".join(path.rstrip("/").split("/")[:-1]) + "/"
def report_error(message, value): """ Returns: An error message about the given value. This is a function for constructing error messages to be used in assert statements. We find that students often introduce bugs into their assert statement messages, and do not find them because they are in the habit of not writing tests that violate preconditions. The purpose of this function is to give you an easy way of making error messages without having to worry about introducing such bugs. Look at the function draw_two_lines for the proper way to use it. Parameter message: The error message to display Precondition: message is a string Parameter value: The value that caused the error Precondition: NONE (value can be anything) """ return message+': '+repr(value)
def result_structure_is_valid(test_result_data): """ Check if the test result structure is valid. Takes a test result as input. 'name', 'value' and 'valuetype' fields are needed in the test result. If no 'reference' is supplied, the current reference for this test is used. If it does not exist, the 'reference' is None. The current reference will not be set automatically. If no 'margin' is supplied, the default margin of the 'valuetype' is used. """ needed_fields = ['name', 'value', 'valuetype'] for field in needed_fields: if field not in test_result_data: return False return True
def pascal_triangle(n): """ returns a list of lists of integers representing the Pascal's triangle of n """ if n <= 0: return [] res = [] l = [] for i in range(n): row = [] for j in range(i + 1): if i == 0 or j == 0 or i == j: row.append(1) else: row.append(l[j] + l[j - 1]) l = row res.append(row) return res
def lorentzian(x, height, center, width): """ defined such that height is the height when x==x0 """ halfWSquared = (width/2.)**2 return (height * halfWSquared) / ((x - center)**2 + halfWSquared)
def int_64_to_128(val1, val2): """Binary join 128 bit integer from two 64bit values. This is used for storing 128bit IP Addressses in integer format in database. Its easier to search integer values. Args: val1 (int): First 64Bits. val2 (int): Last 64Bits. Returns: int: IP integer value. """ return (val1 << 64) + val2
def div42by(divideBy): """ Divide 42 by a parameter. """ try: return 42 / divideBy except: print("Error! -- You tried to divide by Zero!")
def sample_nucleotide_diversity_entity(H, D): """ # ======================================================================== SAMPLE NUCLEOTIDE DIVERSITY (ENTITY-LEVEL) PURPOSE ------- Calculates the sample nucleotide diversity. INPUT ----- [INT] [H] The number of haplotypes. [2D ARRAY] [D] A distance matrix of haplotypes pair-wise genetic distances (fraction of nt differences). RETURN ------ [FLOAT] The entity-level sample nucleotide diversity. # ======================================================================== """ sum_substitutions = 0 for i in range(0, H): for j in range(0, H): sum_substitutions += D[i][j] diversity = float(sum_substitutions) / (float(H) * float(H - 1)) return diversity
def knapsack_matrix(items, limit): """ value matrix for knapsack problem items - list(name, weight, value) limit - maximum weight of knapsack return matrix NxM (N - len(item) + 1, M - limit + 1 ) """ # set zero matrix # rows equal limit weight, columns - items matrix = [[0] * (limit + 1) for _ in range(len(items) + 1)] # start from second row for i in range(1, len(items) + 1): # get name, weight and value for current item _, weight, value = items[i - 1] # start from second column for w in range(1, limit + 1): if weight > w: # copy value from previous item for current weight matrix[i][w] = matrix[i - 1][w] else: # choose the most valuable set # option 1: use value from previous item for current weight # option 2: from the previous item for the remaining weight # plus current value matrix[i][w] = max(matrix[i - 1][w], matrix[i - 1][w - weight] + value) return matrix
def gen_key_i(i, kappa, K): """ Create key value where key = kappa, except for bit i: key_(i mod n) = kappa_(i mod n) XOR K_(i mod n) Parameters: i -- integer in [0,n-1] kappa -- string K -- string Return: key -- list of bool """ # Transform string into list of booleans kappa = list(kappa) kappa = [bool(int(j)) for j in kappa] K = list(K) K = [bool(int(j)) for j in K] # Initialize new key value key = kappa.copy() # XOR at indice i key[i] = K[i] ^ kappa[i] return key
def filter_times(sorted_times, filter): """Filters the list of times by the filter keyword. If no filter is given the times are returned unfiltered. Parameters ----------- `sorted_times` : list Collection of already sorted items, e.g. pitstops or laptimes data. `filter` : str The type of filter to apply; 'slowest' - single slowest time 'fastest' - single fastest time 'top' - top 5 fastest times 'bottom' - bottom 5 slowest times Returns ------- list A subset of the `sorted_times` according to the filter. """ # Force list return type instead of pulling out single string element for slowest and fastest # Top/Bottom already outputs a list type with slicing # slowest if filter == 'slowest': return [sorted_times[len(sorted_times) - 1]] # fastest elif filter == 'fastest': return [sorted_times[0]] # fastest 5 elif filter == 'top': return sorted_times[:5] # slowest 5 elif filter == 'bottom': return sorted_times[len(sorted_times) - 5:] # no filter given, return full sorted results else: return sorted_times
def format_time(t: float) -> str: """ Format a time duration in a readable format. :param t: The duration in seconds. :return: A human readable string. """ hours, remainder = divmod(t, 3600) minutes, seconds = divmod(remainder, 60) return '%d:%02d:%02d' % (hours, minutes, seconds)
def str_to_bool(s): """ Convert multiple string sequence possibilities to a simple bool There are many strings that represent True or False connotation. For example: Yes, yes, y, Y all imply a True statement. This function compares the input string against a set of known strings to see if it can be construed as True. True strings: TRUE, True, true, 1, Y, y, YES, Yes, yes Args: s (string): String to convert into a bool Returns: bool: Returns True if the input string is one of the known True strings """ if s.strip() in ['TRUE', 'True', 'true', '1', 'Y', 'y', 'YES', 'Yes', 'yes']: return True else: return False
def __tuples(a): """map an array or list of lists to a tuple of tuples""" return tuple(map(tuple, a))
def insetRect(rect, dx, dy): """Inset a bounding box rectangle on all sides. Args: rect: A bounding rectangle expressed as a tuple ``(xMin, yMin, xMax, yMax)``. dx: Amount to inset the rectangle along the X axis. dY: Amount to inset the rectangle along the Y axis. Returns: An inset bounding rectangle. """ (xMin, yMin, xMax, yMax) = rect return xMin+dx, yMin+dy, xMax-dx, yMax-dy
def FormatTimedelta(delta): """Returns a string representing the given time delta.""" if delta is None: return None hours, remainder = divmod(delta.total_seconds(), 3600) minutes, seconds = divmod(remainder, 60) return '%02d:%02d:%02d' % (hours, minutes, seconds)
def backend_is_up(backend): """Returns whether a server is receiving traffic in HAProxy. :param backend: backend dict, like one of those returned by smartstack_tools.get_multiple_backends. :returns is_up: Whether the backend is in a state that receives traffic. """ return str(backend['status']).startswith('UP')
def mean(num_list): """ Return the average of a list of number. Return 0.0 if empty list. """ if not num_list: return 0.0 else: return sum(num_list) / float(len(num_list))
def calc_start(page, paginate_by, count): """Calculate the first number in a section of a list of objects to be displayed as a numbered list""" if page is not None: if page == 'last': return paginate_by * (count / paginate_by) + 1 else: return paginate_by * (int(page) - 1) + 1 else: return 1
def noamwd_decay(step, warmup_steps, model_size, rate=0.5, decay_steps=1000, start_step=500): """Learning rate schedule optimized for huge batches """ return ( model_size ** (-0.5) * min(step ** (-0.5), step * warmup_steps**(-1.5)) * rate ** (max(step - start_step + decay_steps, 0) // decay_steps))
def find_hexagon_through_edge(aHexagon_in, pEdge_in): """find the hexagons which contain an edge Args: aHexagon_in ([type]): [description] pEdge_in ([type]): [description] Returns: [type]: [description] """ nHexagon = len(aHexagon_in) aHexagon_out = list() for i in range(nHexagon): pHexagon = aHexagon_in[i] if pHexagon.has_this_edge(pEdge_in) ==1: aHexagon_out.append(pHexagon) pass else: pass return aHexagon_out
def get_unique_ptr(obj): """Read the value of a libstdc++ std::unique_ptr.""" return obj['_M_t']['_M_t']['_M_head_impl']
def average_housing(house_prices): """ Calculate the lowest average price of houses in given areas while also ignoring the null value (-9999). Parameters: house_prices: A dictionary containing locations and their list of house prices. Returns: The house location with the lowest average price when ignoring null values. >>> average_housing({'LA': [782900, 1368800, -9999, -9999], \ 'SD': [746600, 697100, 989900, 785000], \ 'BNY': 675000}) Traceback (most recent call last): ... AssertionError >>> average_housing({92122: [746600, 697100, 989900, 785000]}) Traceback (most recent call last): ... AssertionError >>> average_housing({'LA': [782900, 1368800, 599000, 750000], \ 'SD': [746600, 697100, 989900, 785000], \ 'BNY': [675000, 239000, 789000, 1049000]}) 'BNY' >>> average_housing({'LA': [782900, 1368800, -9999, -9999], \ 'SD': [746600, 697100, 989900, 785000], \ 'BNY': [675000, -9999, 789000, 1049000]}) 'SD' >>> average_housing({'Acorn Blvd': [0, 1, 2], \ 'Pine Ave': [4, 3, -9999], \ 'Maple Lane': [3, -9999, 3, 3]}) 'Acorn Blvd' # My doctests >>> average_housing({'LA': [782900, 1368800, 599000, 750000], \ 2: [746600, 697100, 989900, 785000], \ 'BNY': [675000, 239000, 789000, 1049000]}) Traceback (most recent call last): ... AssertionError >>> average_housing(47) Traceback (most recent call last): ... AssertionError >>> average_housing({'LA': [1, 4, 5, -2], 'SD': [1, 3, -9999], \ 'JOE': [1, 2, 3]}) 'JOE' >>> average_housing({'JOE': 124}) Traceback (most recent call last): ... AssertionError """ assert isinstance(house_prices, dict) assert all([isinstance(keys, str) for keys in house_prices.keys()]) assert all([isinstance(values, list) for values in house_prices.values()]) null_value = -9999 return min([(sum([i for i in values if i != null_value]) / \ len([i for i in values if i != null_value]), keys) \ for keys, values in house_prices.items()])[1]
def xyz_to_lab(c: float) -> float: """Converts XYZ to Lab :param c: (float) XYZ value :return: (float) Lab value """ if c > 216.0 / 24389.0: return pow(c, 1.0 / 3.0) return c * (841.0 / 108.0) + (4.0 / 29.0)
def split_unescape(value, delimiter = " ", max = -1, escape = "\\", unescape = True): """ Splits the provided string around the delimiter character that has been provided and allows proper escaping of it using the provided escape character. This is considered to be a very expensive operation when compared to the simple split operation and so it should be used carefully. :type value: String :param value: The string value that is going to be split around the proper delimiter value taking into account the escaping. :type delimiter: String :param delimiter: The delimiter character to be used in the split operation. :type max: int :param max: The maximum number of split operations that are going to be performed by this operation. :type escape: String :param escape: The "special" escape character that will allow the delimiter to be also present in the choices selection. :type unescape: bool :param unescape: If the final resulting string should be already unescaped (normalized). :rtype: List :return: The final list containing the multiple string parts separated by the delimiter character and respecting the escape sequences. """ result = [] current = [] iterator = iter(value) count = 0 for char in iterator: if char == escape: try: if not unescape: current.append(escape) current.append(next(iterator)) except StopIteration: if unescape: current.append(escape) elif char == delimiter and not count == max: result.append("".join(current)) current = [] count += 1 else: current.append(char) result.append("".join(current)) return result
def intoNum(s: str) -> float: """ Turns string into floats. NOTE: Fraction are automatically turned to percentages >>> intoNum("3") 3.0 >>> intoNum("3.5") 3.5 >>> intoNum("3/5") 60.0 >>> intoNum("3.1/10") 31.0 >>> intoNum("3.1/100.0") 3.1 """ if "/" in s: lst = s.split("/") return float(lst[0])/float(lst[1]) * 100 else: return float(s)
def filter_lowercase(data): """Converts text of all items to lowercase""" new_data = [] for d in data: d['article'] = d['article'].lower() new_data.append(d) data = new_data return data
def sum_squares2(n): """ Returns: sum of squares from 1 to n-1 Example: sum_squares(5) is 1+4+9+16 = 30 Parameter n: The number of steps Precondition: n is an int > 0 """ # Accumulator total = 0 print('Before while') x = 0 while x < n: print('Start loop '+str(x)) total = total + x*x x = x+1 print('End loop ') print('After while') return total
def dictlist(dict_): """ Convert dict to flat list """ return [item for pair in dict_.items() for item in pair]
def subst_string(s,j,ch): """ substitutes string 'ch' for jth element in string """ res = '' ls = list(s) for i in range(len(s)): if i == j: res = res + ch else: res = res + ls[i] return res
def feature_array_to_string(feature_array): """Transforms feature array into a single string. """ feature_array_str = [str(x) for x in feature_array] feature_array_str[0] = "\"" + feature_array_str[0] + "\"" # query feature_array_str[1] = "\"" + feature_array_str[1] + "\"" # target feature_array_str[2] = "\"" + feature_array_str[2] + "\"" # candidate feature_array_str[3] = "\"" + feature_array_str[3] + "\"" # mark return ','.join(feature_array_str)
def rivers_with_station(stations): """Find rivers which have monitoring stations Args: stations (list): list of MonitoringStation objects Returns: set: contains name of the rivers with a monitoring station """ river_set = set() for station in stations: river_set.add(station.river) return river_set
def find_tx_extra_field_by_type(extra_fields, msg, idx=0): """ Finds given message type in the extra array, or returns None if not found :param extra_fields: :param msg: :param idx: :return: """ cur_idx = 0 for x in extra_fields: if isinstance(x, msg): if cur_idx == idx: return x cur_idx += 1 return None
def from_rgb(rgb): """translates an rgb tuple of int to a tkinter friendly color code""" return "#%02x%02x%02x" % rgb
def D(f, x, N): """ takes a function f(x), a value x, and the number N and returns the sequence for 0,N """ sequence = [] for i in range(N): sequence.append((f(float(x)+(2.0**(-1 *float(i))))-f(x))/(2.0**(-1 *float(i)))) return sequence
def union_tag(obj): """Get the tag of a union object.""" return next(iter(obj))
def globalize_query(search_query): """ Take the bag parts out of a search query. """ query = ' '.join([part for part in search_query.split() if not part.startswith('bag:')]) return query
def numIslands(grid): """ :type grid: List[List[str]] :rtype: int """ def visit_island(grid,visit,i,j): if i >= len(grid): return if j >= len(grid[0]): return if grid[i][j] == "1" and not visit[i][j]: visit[i][j] = 1 visit_island(grid,visit,i+1,j) visit_island(grid,visit,i,j+1) visit = [[0]*len(grid[0]) for i in range(len(grid))] num = 0 for i in range(len(grid)): for j in range(len(grid[0])): if grid[i][j] == "1" and not visit[i][j]: visit_island(grid,visit,i,j) print (visit) num += 1 print (num) return num
def get_video_dimensions(lines): """Has it's own function to be easier to test.""" def get_width_height(video_type, line): dim_col = line.split(", ")[3] if video_type != "h264": dim_col = dim_col.split(" ")[0] return map(int, dim_col.split("x")) width, height = None, None video_types = ("SAR", "hevc", "h264") for line in lines: for video_type in video_types: if video_type in line: width, height = get_width_height(video_type, line) break else: # necessary to break out of nested loop continue break portrait = False portrait_triggers = ["rotation of", "DAR 9:16"] for line in lines: for portrait_trigger in portrait_triggers: if portrait_trigger in line: portrait = True if portrait: width, height = height, width return width, height
def count_genes_in_pathway(pathways_gene_sets, genes): """Calculate how many of the genes are associated to each pathway gene set. :param dict pathways_gene_sets: pathways and their gene sets :param set genes: genes queried :rtype: dict """ return { pathway: len(gene_set.intersection(genes)) for pathway, gene_set in pathways_gene_sets.items() }
def get_quantized_bits_dict(bits, ibits, sign=False, mode="bin"): """Returns map from floating values to bit encoding.""" o_dict = {} n_bits = bits for b in range(1 << (bits - sign)): v = (1.0 * b) * (1 << ibits) / (1 << bits) if mode == "bin": b_str = bin(b)[2:] b_str = "0" * (n_bits - len(b_str)) + b_str else: # mode == "dec": b_str = str(b) o_dict[v] = b_str if b > 0 and sign: if mode == "bin": b_str = bin(-b & ((1 << n_bits) - 1))[2:] else: # mode == "dec" b_str = str(-b) o_dict[-v] = b_str if sign: v = (1.0 * (1 << (bits - sign))) * (1 << ibits) / (1 << bits) if mode == "bin": b_str = bin(-(1 << (bits - sign)) & ((1 << bits) - 1))[2:] else: b_str = str(-(1 << (bits - sign))) o_dict[-v] = b_str return o_dict
def regularize_guest_names(guest_list): """Regularizes the names of guest. """ guest_list_cp = guest_list[:] number_of_guests = len(guest_list_cp) for i in range(number_of_guests): guest_list_cp[i].firstname = "Guest {}".format(i + 1) return guest_list_cp
def has_duplicates(t): """Checks whether any element appears more than once in a sequence. Simple version using a for loop. t: sequence """ d = {} for x in t: if x in d: return True d[x] = True return False
def listify(x): """Make x a list if it isn't.""" return [] if not x else (list(x) if isinstance(x, (tuple, list)) else [x])
def utilization_graph(utilization, warning_threshold=75, danger_threshold=90): """ Display a horizontal bar graph indicating a percentage of utilization. """ return { 'utilization': utilization, 'warning_threshold': warning_threshold, 'danger_threshold': danger_threshold, }
def epoch_time_standardization(epoch_time): """Convert the given epoch time to an epoch time in seconds.""" epoch_time_string = str(epoch_time) # if the given epoch time appears to include milliseconds (or some other level of precision)... # and does not have a decimal in it, add a decimal point if len(epoch_time_string) > 10 and '.' not in epoch_time_string: epoch_time = f'{epoch_time_string[:10]}.{epoch_time_string[10:]}' return epoch_time
def informacoes_formatada(comparacao): """ Exibe na tela os dados de maneira formatada""" comparacao_nome = comparacao["name"] comparacao_descricao = comparacao["description"] comparacao_pais = comparacao["country"] return f"{comparacao_nome}, {comparacao_descricao}, do {comparacao_pais}"
def intersection_list(*lists) -> list: """ Common elements in all given lists. """ l = list(set.intersection(*[set(lst) for lst in lists])) l.sort() return l
def repeat(s, exclaim): """ return string 's' repeated 3 times if exclaim is true ,and exclamation marks :param s: :param exclaim: :return: """ # result = s + s + s result = s * 3 if exclaim: result += "! ! !" return result
def convert_to_wkt(geotrace): """Converts a Geotrace string in JavaRosa format to a WKT LINESTRING. The JavaRosa format consists of points separated by semicolons, where each point is given as four numbers (latitude, longitude, altitude, accuracy) separated by spaces.""" wkt_points = [] for point in geotrace.split(';'): if point.strip(): lat, lon, alt, accuracy = map(float, point.split()) wkt_points.append('%.6f %.6f %d %.1f' % (lon, lat, alt, accuracy)) return wkt_points and 'LINESTRING ZM (%s)' % (', '.join(wkt_points)) or ''
def get_prod_name(product): """ this is just a terrible hack since folder containing this product and files have a slightly different name """ if product=='ASII': product = 'ASII-TF' return product
def orangePurchase2(m): """ Calculate how many oranges can be bought with a set amount of money. The first orange costs 1, and each subsequent exponentially costs more than the previous (the second costs 2, the third costs 4, and so on). :param m:total amount of money available (nb m<2,147,483,647) :return:total number of oranges which can be purchased """ if m in [0, 1]: return m total = 0 #first term in series value = 1 #calculate sum of Geometric sequence of prices until money limit is broken for number_of_oranges in range(0, m): total = total + value value = 2 ** number_of_oranges-1 if total == m: return number_of_oranges elif total>m: #Current total breaks the money limit, hence use previous orange count which didnt break limit return number_of_oranges-1
def check_for_empty_string(input_data): """ Checks if data presented by a user is empty. """ if input_data.strip() == "": return 'All fields are required' return None
def transpose_m2m(m2m_list): """ converts single line single column to multi line double column """ ds_list, fb_list = [], [] for entry in m2m_list: if entry == '': continue ds, fb = entry.split('\t') ds_list.append(ds.strip('|').split('|')) fb_list.append(fb.strip('|').split('|')) return ds_list, fb_list
def urlsplit(url): """ Splits a URL like "https://example.com/a/b?c=d&e#f" into a tuple: ("https", ["example", "com"], ["a", "b"], ["c=d", "e"], "f") A trailing slash will result in a correspondingly empty final path component. """ split_on_anchor = url.split("#", 1) split_on_query = split_on_anchor[0].split("?", 1) split_on_scheme = split_on_query[0].split("://", 1) if len(split_on_scheme) <= 1: # Scheme is optional split_on_scheme = [None] + split_on_scheme[:1] split_on_path = split_on_scheme[1].split("/") return { "scheme": split_on_scheme[0], "netloc": split_on_path[0].split("."), "path": split_on_path[1:], "query": split_on_query[1].split("&") if len(split_on_query) > 1 else None, "fragment": split_on_anchor[1] if len(split_on_anchor) > 1 else None, }
def get_config_value(config, key, default_value, value_types, required=False, config_name=None): """ Parameters ---------- config: dict Config dictionary key: str Config's key default_value: str Default value when key is absent in config value_types: Type or List of Types if not None, should check value belongs one value_types required: bool if the key is required in config config_name: str used for debug """ if config_name is not None: log_prefix = "[{}] ".format(config_name) else: log_prefix = "" if required and not key in config: raise ValueError("{}config={}, key={} is absent but it's required !!!".format(log_prefix, config, key)) elif not key in config: return default_value value = config[key] # value type check if value is not None: value_type_match = True if value_types is None: value_types = [] elif not isinstance(value_types, list): value_types = [value_types] for value_type in value_types: if not isinstance(value, value_type): value_type_match = False break if not value_type_match: raise ValueError("{}config={}, Value type not matched!!! key={}, value={}, value_types={}".format( log_prefix, config, key, value, value_types)) return value
def weaksauce_decrypt(text, password): """Decrypt weakly and insecurely encrypted text""" offset = sum([ord(x) for x in password]) decoded = ''.join( chr(max(ord(x) - offset, 0)) for x in text ) return decoded
def get_form_list(items): """ """ ret = [] for item in items: ret.append( (item.CodeKey, item.TextKey) ) return ret
def _BuildSettingsTargetForTargets(targets): """Returns the singular target to use when fetching build settings.""" return targets[0] if len(targets) == 1 else None
def command_clone(ctx, src, dest, bare=False): """ Take in ctx to allow more configurability down the road. """ bare_arg = "" if bare: bare_arg = "--bare" return "git clone %s '%s' '%s'" % (bare_arg, src, dest)