content
stringlengths
42
6.51k
def keys_as_sorted_list(dict): """ Given a dictionary, get the keys from it, and convert it into a list, then sort the list of keys """ return sorted(list(dict.keys()))
def resolve_dotted_attribute(obj, attr, allow_dotted_names=True): """resolve_dotted_attribute(a, 'b.c.d') => a.b.c.d Resolves a dotted attribute name to an object. Raises an AttributeError if any attribute in the chain starts with a '_'. If the optional allow_dotted_names argument is false, dots are not supported and this function operates similar to getattr(obj, attr). """ if allow_dotted_names: attrs = attr.split('.') else: attrs = [ attr] for i in attrs: if i.startswith('_'): raise AttributeError('attempt to access private attribute "%s"' % i) else: obj = getattr(obj, i) return obj
def deep_list(x): """Convert tuple recursively to list.""" if isinstance(x, tuple): return map(deep_list, x) return x
def merge_dict(main_dict, enhance_dict): """Merges dictionaries by keys. Function call itself if value on key is again dictionary. Args: main_dict (dict): First dict to merge second one into. enhance_dict (dict): Second dict to be merged. Returns: dict: Merged result. .. note:: does not overrides whole value on first found key but only values differences from enhance_dict """ for key, value in enhance_dict.items(): if key not in main_dict: main_dict[key] = value elif isinstance(value, dict) and isinstance(main_dict[key], dict): main_dict[key] = merge_dict(main_dict[key], value) else: main_dict[key] = value return main_dict
def deep(m, dflt, *pth): """Access to props in nested dicts / Creating subdicts by *pth Switch to create mode a bit crazy, but had no sig possibilit in PY2: # thats a py3 feature I miss, have to fix like that: if add is set (m, True) we create the path in m Example: deep(res, True), [], 'post', 'a', 'b').append(r['fid']) creates in res dict: {'post': {'a': {'b': []}}} (i.e. as list) and appends r['fid'] to it in one go create because init True was set """ m, add = m if isinstance(m, tuple) else (m, False) keys = list(pth) while True: k = keys.pop(0) get = m.setdefault if add else m.get v = dflt if not keys else {} m = get(k, v) if not keys: return m
def selection_sort(l): """ :param l - a list :return a sorted list """ for i in range(len(l)): min_index = i for j in range(i, len(l)): if l[j] < l[min_index]: min_index = j l[i], l[min_index] = l[min_index], l[i] return l
def unique(lst): """ Identify the unique elements of a list (the elements that do not appear anywhere else in the list) """ un_lst = [] for i,v in enumerate(lst): if i == len(lst) - 1: continue if v != lst[i-1] and v != lst[i+1]: un_lst.append(i) return un_lst
def queryEscape(query): """Certain chars need to be escaped """ bad_chars = [ ("&quot;", '"') ] for char, replacement in bad_chars: query = query.replace(char, replacement) return query
def task_simulation(): """ Runs the parametrized fenics 'poission' example for a convergence plot and a field plot """ return { "file_dep": ["computation/poisson.py"], "targets": [ "computation/poisson_convergence_Ns.npy", "computation/poisson_convergence_errors.npy", "computation/poisson.h5", "computation/poisson.xdmf", ], "actions": ["python3 computation/poisson.py"], "clean": True, }
def palindrom_reverse(s): """Check palindrome by inverse slicing. Time complexity: O(n). Space complexity: O(n). """ return s == s[::-1]
def __to_upper(val): """Convert val into ucase value.""" try: return val.upper() except (ValueError, TypeError): return val
def maprange(a, b, s): """remap values linear to a new range""" (a1, a2), (b1, b2) = a, b return b1 + ((s - a1) * (b2 - b1) / (a2 - a1))
def clean_text(text): """Cleans text. Only cleans superfluous whitespace at the moment. """ return ' '.join(text.split()).strip()
def lim_z(depth, thick, val): """ limits for depth """ return (depth - val * thick, depth + val * thick)
def checkunique(data): """Quickly checks if a sorted array is all unique elements.""" for i in range(len(data) - 1): if data[i] == data[i + 1]: return False return True
def has_special_character(password: str) -> bool: """ checks if password has at least one special character """ return any(char for char in password if not char.isalnum() and not char.isspace())
def tryParse(text): """ A convenience function for attempting to parse a string as a number (first, attempts to create an integer, and falls back to a float if the value has a decimal, and finally resorting to just returning the string in the case where the data cannot be converted). @ In, text, string we are trying to parse @ Out, value, int/float/string, the possibly converted type """ ## FIXME is there anything that is a float that will raise an ## exception for int? ## Yes, inf and nan do not convert well to int, but would you ## ever have these in an input file? - dpm 6/8/16 try: value = int(text) except ValueError: try: value = float(text) except ValueError: value = text ## If this tag exists, but has no internal text, then it is most likely ## a boolean value except TypeError: return True return value
def strings_contain_each_other(first_str, second_str): """ Checks if two strings contain each other. Returns (the bool value that says if they are containing each other, the string that includes, the string that is included) """ first_count = second_str.count(first_str) second_count = first_str.count(second_str) are_containing = bool(first_count + second_count) if not bool(second_count) and are_containing: first_str, second_str = second_str, first_str return are_containing, first_str, second_str
def parseOperator(value): """ Returns a search operator based on the type of the value to match on. :param value: to match in the search. :return: operator to use for the type of value. """ if type(value) == str: return " LIKE " else: return "="
def user_subscribe_event(msg): """ user subscribe event """ return msg['MsgType'] == 'event' and msg['Event'] == 'subscribe'
def _isfloat(string): """ Checks if a string can be converted into a float. Parameters ---------- value : str Returns ------- bool: True/False if the string can/can not be converted into a float. """ try: float(string) return True except ValueError: return False
def convert_dashes(dash): """ Converts a Matplotlib dash specification bokeh.core.properties.DashPattern supports the matplotlib named dash styles, but not the little shorthand characters. This function takes care of mapping those. """ mpl_dash_map = { "-": "solid", "--": "dashed", ":": "dotted", "-.": "dashdot", } # If the value doesn't exist in the map, then just return the value back. return mpl_dash_map.get(dash, dash)
def get_angle_difference(angle, difference=90): """Given an azimuth angle (0-360), it will return the two azimuth angles (0-360) as a tuple that are perpendicular to it.""" angle_lower, angle_higher = (angle + difference) % 360, (angle - difference) % 360 return (angle_lower, angle_higher)
def check_line(line: str): """ A funtion that checks if a string passed to this function contains key words that need to be processed further Parameters ---------- line : str\n a string that needs to be checked if it contains key words Returns ------- list\n a list of words found in the string 'line', if the word is a keyword,then instead of only the word, a tuple in the form of (True, word) is added """ key_words = ['src', 'href', 'url'] out = list() for word in key_words: if line.__contains__(word): out.append((True, word)) # Check if output list is not empty if len(out) == 0: # If list is empty return None return None else: return out
def split_neo_dict(neo_dict: dict) -> list: """ Convert NEO dictionary into a list of NEOs Args: neo_dict (dict): NEO dictionary pulled from NEO feed Returns: [list]: List of NEOs """ return [i for v in neo_dict.items() for i in v]
def normalize_dot_bracket(bracket: str) -> str: """ Return a normalized version of the dot bracket. First pseudoknot pair always starts with a parenthesis. ``` normalize_dot_bracket("..((..[[[..)).]]].") == "..((..[[[..)).]]]." normalize_dot_bracket("..[[..(((..]].))).") == "..((..[[[..)).]]]." ``` """ if "[" not in bracket or "(" not in bracket: return bracket if bracket.index("[") > bracket.index("("): return bracket return ( bracket.replace("[", "A") .replace("]", "B") .replace("(", "[") .replace(")", "]") .replace("A", "(") .replace("B", ")") )
def comp_dict(d1, d2): """ Compare the structure of two dictionaries to see if they are identical return True if same schema, False if not """ if d1.keys() != d2.keys(): return False else: same = True for key in d1.keys(): # both sets of keys are the same if dict == type(d1[key]) == type(d2[key]): same = same and comp_dict(d1[key], d2[key]) return same
def map_int(x, in_min, in_max, out_min, out_max): """ Map input from one range to another. """ return int((x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min);
def check_nuvs_file_type(file_name: str) -> str: """ Get the NuVs analysis file type based on the extension of given `file_name` :param file_name: NuVs analysis file name :return: file type """ if file_name.endswith(".tsv"): return "tsv" if file_name.endswith(".fa"): return "fasta" if file_name.endswith(".fq"): return "fastq" raise ValueError("Filename has unrecognized extension")
def results_to_dict(movie_id: int, props_movie: dict): """ Function that returns vector of dictionaries with the results from the dbpedia to insert into data frame of all movie properties :param movie_id: movie id of the movie :param props_movie: properties returned from dbpedia :return: vector of dictionaries with the results from the dbpedia """ filter_props = [] for p in props_movie["results"]["bindings"]: dict_props = {'movie_id': movie_id, "prop": p["prop"]["value"], "obj": p["obj"]["value"]} filter_props.append(dict_props) return filter_props
def match_videos_and_captions(videos, sentences): """Maps captions to videos and splits the data into train/valid/test. arguments: videos: a list of dicts, where each dict describes a video sentences: a list of dicts, where each dict describes a sentence returns: a dict that maps from split name to a list of videos, where each video is a dict that contains a field "url" that is the video's url, and a field "captions", a list of strings where each string is a possible caption of the video. """ dataset_metadata = {} video_id_to_split_index_pair = {} for video in videos: split = video["split"] id_ = video["video_id"] if split not in dataset_metadata: dataset_metadata[split] = [] video["captions"] = [] video_id_to_split_index_pair[id_] = ( split, len(dataset_metadata[split]) ) dataset_metadata[split].append(video) for sentence in sentences: caption_text = sentence["caption"] video_id = sentence["video_id"] video_split, video_index = video_id_to_split_index_pair[video_id] video = dataset_metadata[video_split][video_index] video["captions"].append(sentence["caption"]) return dataset_metadata
def get_resource_node(platform, executable_name, base_destination_node): """ Gets the path to where resources should be placed in a package based on the platform. :param platform: The platform to get the resource location for :param executable_name: Name of the executable that is being packaged :param base_destination_node: Location where the platform speicific package is going to be placed :return: The path to where resources should be packaged. May be the same as base_destination_node :rtype: Node """ if 'darwin' in platform: return base_destination_node.make_node(executable_name + ".app/Contents/Resources/") elif 'ios' in platform: return base_destination_node.make_node(executable_name + ".app/Contents/") else: return base_destination_node
def deny(target, actuator, modifier): """ Note: return values are sent as the response to an OpenC2 cmd """ return "Blocking domain {}".format(target['URI'])
def new_filename(file, ntype, snr): """Append noise tyep and power at the end of wav filename.""" return file.replace(".WAV", ".WAV.{}.{}dB".format(ntype, snr))
def pascal(row, column): """Returns the value of the item in Pascal's Triangle whose position is specified by row and column. >>> pascal(0, 0) 1 >>> pascal(0, 5) # Empty entry; outside of Pascal's Triangle 0 >>> pascal(3, 2) # Row 3 (1 3 3 1), Column 2 3 >>> pascal(4, 2) # Row 4 (1 4 6 4 1), Column 2 6 """ "*** YOUR CODE HERE ***" if column > row: return 0 if row == 0: return 1 if column == 0: return 1 return pascal(row - 1, column) + pascal(row - 1, column - 1)
def two_pad(in_time): """ Takes in a number of 1 or 2 digits, returns a string of two digits. """ assert isinstance(in_time,int) assert (in_time < 100 and in_time >= 0) return "0" + str(in_time) if str(in_time).__len__() == 1 else str(in_time)
def gcd(x, y): """ assume always x > y :param x: :param y: :return: gcd value """ if x < y: z = x x = y y = z if y == 0: print(f'gcd = {x}') return x else: print(f'{x} = {(x - x % y) / y}*{y} + {x % y}') return gcd(y, x % y)
def map_range(x, x_min, x_max, y_min, y_max): """ Linear mapping between two ranges of values """ x = float(x) x_range = x_max - x_min y_range = y_max - y_min xy_ratio = x_range / y_range y = ((x - x_min) / xy_ratio + y_min) return int(y)
def split(string, sep): """Return the string split by sep. Example usage: {{ value|split:"/" }} """ return string.split(sep)
def _to_hass_brightness(brightness): """Convert percentage to Home Assistant brightness units.""" return int(brightness * 255)
def gen_data_dict(data, columns): """Fill expected data tuple based on columns list """ return tuple(data.get(attr, '') for attr in columns)
def get_modifications(old, new, attributes): """ Create a dictionary containing the old values when they are different from the new ones at given attributes. Does not consider other attributes than the array given in parameter. :param old: a dictionary containing the old values :param new: a dictionary containing the new values :param attributes: the attributes to check between new and old :return: a dict containing the old values when different from new ones at given attributes """ ret = {} for a in attributes: if old[a] != new[a]: ret[a] = old[a] return ret
def stringify(vals): """ return a string version of vals (a list of object implementing __str__) return type: 'val1_val2_val3_ ... _valn' """ return '_'.join([str(e) for e in vals])
def matrix_divided(matrix, div): """ Function that divides all elements of a matrix. Args: matrix (list): the square matrix div (int or float): the number that divide Returns: new matrix """ if type(div) is not int and type(div) is not float: raise TypeError("div must be a number") elif div == 0: raise ZeroDivisionError("division by zero") if matrix is None or len(matrix) == 0: raise TypeError("matrix must be a matrix (list of lists) of " + "integers/floats") if type(matrix) == tuple or type(matrix) == set: raise TypeError("matrix must be a matrix (list of lists) of " + "integers/floats") l = len(matrix[0]) for row in matrix: if type(row) == tuple or type(row) == set: raise TypeError("matrix must be a matrix (list of lists) " + "of integers/floats") if len(row) != l: raise TypeError("Each row of the matrix must have the same size") for col in row: if type(col) is not int and type(col) is not float: raise TypeError("matrix must be a matrix (list of lists) " + "of integers/floats") new = list(map(lambda row: list(map(lambda col: round(col / div, 2), row)), matrix)) return new
def flatten(lst): """Flatten a list. See http://stackoverflow.com/questions/952914/\ making-a-flat-list-out-of-list-of-lists-in-python """ return [item for sublist in lst for item in sublist]
def quicksort(l): """Sort list using quick sort. Complexity: O(n log n). Worst: O(n2) @param l list to sort. @returns sorted list. """ if len(l) <= 1: return l pivot = l[0] less = [] equal = [] greater = [] for e in l: if e < pivot: less.append(e) elif e == pivot: equal.append(e) else: greater.append(e) return quicksort(less) + equal + quicksort(greater)
def tail(real_iter, n_th): """Returns the last nth elements of an iterable. Takes any iterable and returns its lasth nth items from the iterable/list. Args: real_iter: an interable or a list (iterable or list) n_th: nth number of items to return (int) Returns: A list containing the last nth items """ if n_th <= 0: return [] real_list = list(real_iter) start = len(real_list)-n_th if n_th < len(real_list) else 0 return real_list[start:]
def calc_epsilon(sample_parent, model_parent): """Calculates the epsilon value, given the sample parent and model parent composition. Parameters ---------- sample_parent : float Measured parent composition. model_parent : float Model parent composition. (Typically CHUR or DM for example.) Returns ------- float The epsilon value. Raises ------ None. """ return ((sample_parent - model_parent) / model_parent) * 10**4
def get_column_as_list(matrix, column_no): """ Retrieves a column from a matrix as a list """ column = [] num_rows = len(matrix) for row in range(num_rows): column.append(matrix[row][column_no]) return column
def limit_x(x, limit): """ This module limits the values to the range of [0,limit] """ x_gr_limit = x > limit x_le_limit = x_gr_limit * limit + (1 - x_gr_limit) * x x_gr_zero = x > 0.0 x_norm = x_gr_zero * x_le_limit return x_norm
def parseData(data): """ Parse a dict of dicts to generate a list of lists describing the fields, and an array of the corresponding data records :param dict data: a dict of dicts with field names as keys, and each sub-dict containing keys of 'Type', 'Length', 'Precision' and 'Data'. :returns: fields, records :rtype: list """ fields = [] records = [] for k in list(data.keys()): t = data[k]['Type'] l = data[k]['Length'] if t == 0: nt = 'C' p = 0 elif t == 1: nt = 'N' p = 0 elif t == 2: nt = 'N' p = data[k]['Precision'] else: nt = t p = 0 fields.append([k, nt, l, p]) records.append([data[k]['Data']]) return fields, records
def calc_number_neighbours(num_electrons: int) -> int: """ Calculates the number of neighbours to distort by considering \ the number of extra/missing electrons. If the change in the number of defect electrons is equal or lower than 4, then we distort \ that number of neighbours. If it is higher than 4, then the number of neighbours to distort is 8-(change_in_number_electrons). Args: num_electrons (int): number of missing/extra electrons in defect Returns: number of neighbours to distort (int) """ if num_electrons < -4 or num_electrons > 4 : # if number of missing/extra e- higher than 4, then distort a number of neighbours \ # given by (8 - num_electrons) num_neighbours = abs(8 - abs(num_electrons) ) else: num_neighbours = abs(num_electrons) return abs(num_neighbours)
def fibRecursive(n): """[summary] Computes the n-th fibonacci number recursive. Problem: This implementation is very slow. approximate O(2^n) Arguments: n {[int]} -- [description] Returns: [int] -- [description] """ # precondition assert n >= 0, 'n must be a positive integer' if n <= 1: return n else: return fibRecursive(n-1) + fibRecursive(n-2)
def is_collection(obj): """ Return whether the object is a array-like collection. """ for typ in (list, set, tuple): if isinstance(obj, typ): return True return False
def iterable(arg): """ Simple list typecast """ if not isinstance(arg, (list, tuple)): return [arg] else: return arg
def lengthOfLIS(nums): """ :type nums: List[int] :rtype: int """ if len(nums) == 0: return 0 dp = [1] for i in range(1,len(nums)): maxx = 0 for j in range(i): if nums[j] < nums[i]: maxx = max(maxx, dp[j]) dp.append(maxx+1) return max(dp)
def convertNodeTextToFloatList(nodeText, sep=None): """ Convert space or comma separated string to list of float @ In, nodeText, str, string from xml node text @ Out, listData, list, list of floats """ listData = None if sep is None: if ',' in nodeText: listData = list(float(elem) for elem in nodeText.split(',')) else: listData = list(float(elem) for elem in nodeText.split()) else: listData = list(float(elem.strip()) for elem in nodeText.split(sep)) return listData
def invalid_resource(message, response_code=400): """ Returns the given message, and sets the response code to given response code. Defaults response code to 400, if not provided. """ return {"message": message, "code": response_code}
def set_new_rb_kpi_dictionary(region_names): """ Generates an empty dictionary which collects the parameters KPI-5, KPI-6, KPI-7, KPI-8 and KPI-9 for each region. It defined as 'Region Based KPI Dictionary'. """ rb_kpi_dict = dict() for region_name in region_names: rb_distance_travelled = float(0.0) rb_total_time = float(0.0) rb_idle_time = float(0.0) rb_motion_time = float(0.0) rb_efficiency = float(0.0) rb_kpi_dict[region_name] = { 'kpi5': rb_distance_travelled, 'kpi6': rb_total_time, 'kpi7': rb_idle_time, 'kpi8': rb_motion_time, 'kpi9': rb_efficiency } return rb_kpi_dict
def ucfirst(string): """Implementation of ucfirst and \ u in interpolated strings: uppercase the first char of the given string""" return string[0:1].upper() + string[1:]
def get_iterable(in_dict, in_key): """ Similar to <dict>.get(), but if value is None, False, ..., An empty tuple is returned instead :param in_dict: a dictionary :param in_key: the key to look for at in_dict :return: in_dict[in_var] or () if it is None or not present """ if not in_dict.get(in_key): return () return in_dict[in_key]
def clean_cases(text): """ Makes text all lowercase. :param text: the text to be converted to all lowercase. :type: string :return: lowercase text :type: string """ return text.lower()
def safe_get(obj, attr, sentinel=None): """ Returns sentinel value if attr isn't in obj, otherwise attr's value """ try: return getattr(obj, attr) except AttributeError: return sentinel
def qualified_name_to_object(qualified_name: str, default_module_name='builtins'): """ Convert a fully qualified name into a Python object. It is true that ``qualified_name_to_object(object_to_qualified_name(obj)) is obj``. >>> qualified_name_to_object('unittest.TestCase') <class 'unittest.case.TestCase'> See also :py:func:`object_to_qualified_name`. :param qualified_name: fully qualified name of the form [<module>'.'{<name>'.'}]<name> :param default_module_name: default module name to be used if the name does not contain one :return: the Python object :raise ImportError: If the module could not be imported :raise AttributeError: If the name could not be found """ parts = qualified_name.split('.') if len(parts) == 1: module_name = default_module_name else: module_name = parts[0] parts = parts[1:] value = __import__(module_name) for name in parts: value = getattr(value, name) return value
def public_download_url(name, version, registry='https://registry.npmjs.org'): """ Return a package tarball download URL given a name, version and a base registry URL. """ return '%(registry)s/%(name)s/-/%(name)s-%(version)s.tgz' % locals()
def mean_squared_error_implementation(y_true, y_pred): """Calculate MSE Arguments: y_true {list} -- real numbers, true values y_pred {list} -- real numbers, predicted values """ # intialize error at 0 error_ = 0 # loop over all samples in the true and predicted list for yt, yp in zip(y_true, y_pred): # calculate the absolute error and add to the error value error_ += (yt - yp) ** 2 # return MAE return error_ / len(y_true)
def checkGuid(guid): """ Checks whether a supplied GUID is of the correct format. The guid is a string of 36 characters long split into 5 parts of length 8-4-4-4-12. INPUT: guid - string to be checked . OPERATION: Split the string on '-', checking each part is correct length. OUTPUT: Returns 1 if the supplied string is a GUID. Returns 0 otherwise. """ guidSplit = guid.split('-') if len(guid) == 36 \ and len(guidSplit[0]) == 8 \ and len(guidSplit[1]) == 4 \ and len(guidSplit[2]) == 4 \ and len(guidSplit[3]) ==4 \ and len(guidSplit[4]) == 12: return True else: return False
def process_index(item): """Process and normalize the index.""" if not isinstance(item, (slice, tuple)): if not isinstance(item, int): raise ValueError('The index should be a integer.') item = (item,) if not isinstance(item, tuple): item = tuple([item]) starts, sizes = [], [] for i, ele in enumerate(item): if isinstance(ele, slice): if ele.start is None: starts.append(0) else: starts.append(ele.start) if ele.stop is None: sizes.append(-1) else: sizes.append(ele.stop - starts[-1]) if sizes[-1] == 0: raise ValueError( 'The starts and ends of axis {} can not be equal, got {}:{}.' .format(i, starts[-1], ele.stop)) if ele.step is not None: raise NotImplementedError elif isinstance(ele, int): starts.append(ele) sizes.append(0) else: raise TypeError('Unsupported type of index: {}'.format(type(ele))) return starts, sizes
def convert_min_to_sec(time_min): """Function to convert time in mins to secs""" ans = time_min * 60 return ans
def upper_keys(d): """Returns a new dictionary with the keys of `d` converted to upper case and the values left unchanged. """ return dict(zip((k.upper() for k in d.keys()), d.values()))
def probabilities (X) -> dict: """ This function maps the set of outcomes found in the sequence of events, 'X', to their respective probabilty of occuring in 'X'. The return value is a python dictionary where the keys are the set of outcomes and the values are their associated probabilities.""" # The set of outcomes, denoted as 'C', and the total events, denoted as 'T'. C, T = set(X), len(X) return {c: X.count(c) / T for c in C}
def parameter_dict_merge(log, param_dicts): """ Merge the param dicts into a single one. If fail, return None """ merged_dict = {} for param_dict in param_dicts: for key, value in param_dict.items(): if key not in merged_dict: merged_dict[key] = value continue if merged_dict[key] != value: log.cl_error("ambiguous values for key [%s] in parameters", key) return None return merged_dict
def checkvars(myvars): """ Check variables to see if we have a COOP or DCP site """ for v in myvars: # Definitely DCP if v[:2] in ["HG"]: return False if v[:2] in ["SF", "SD"]: return True if v[:3] in ["PPH"]: return False return False
def day_of_year (yr, mn, dy) : """ day serial number in year, Jan 01 as 1 args: yr: year, 2 or 4 digit year mn: month, 1 to 12 dy: day, 1 to 31, extended days also acceptable returns: day number in the year """ md = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] # days in month dofy = sum(md[0:mn]) + dy # day of year if yr % 4 == 0 and mn > 2 : dofy += 1 # leap year return dofy
def make_a_level_list(N_colours): """ Makes a list of levels for plotting """ list_of_levels = [] for i in range(N_colours): list_of_levels.append(float(i)) return list_of_levels
def encode_request(resource_request, module): """Structures the request as accountId + rest of request""" account_id = resource_request['name'].split('@')[0] del resource_request['name'] return {'accountId': account_id, 'serviceAccount': resource_request}
def function_star(list): """Call a function (first item in list) with a list of arguments. The * will unpack list[1:] to use in the actual function """ fn = list.pop(0) return fn(*list)
def clean(text, split=True): """cleans user input and returns as a list""" if text: if isinstance(text, str): text = text.strip().lower() if split: text = text.split() return text else: return [""]
def cat_from(strlist, v, suf): """ Concatenate sublist of strings :param strlist: list of strings :param v: sublist starting position :param suf: glue string :return: concatenated string """ # return ''.join(map(lambda s: s + suf, strlist[v:])) return suf.join(strlist[v:])
def t(string): """ add \t """ return (string.count(".")) * "\t" + string
def fi(x, y, z, i): """The f1, f2, f3, f4, and f5 functions from the specification.""" if i == 0: return x ^ y ^ z elif i == 1: return (x & y) | (~x & z) elif i == 2: return (x | ~y) ^ z elif i == 3: return (x & z) | (y & ~z) elif i == 4: return x ^ (y | ~z) else: assert False
def add_array(arr1, arr2): """ function to add arrays """ return [i + j for i, j in zip(arr1, arr2)]
def remove_important_elements(config_dict: dict) -> dict: """ Important elements are removed from the config file so that you can't mistakenly set them to false. Note: Some can still be sorted out, this will be done in the following versions. """ for key in ['BitsAllocated', 'BitsStored', 'HighBit ', 'SmallestImagePixelValue', 'LargestImagePixelValue', 'PixelData', 'ImagedNucleus', 'PixelSpacing', 'AcquisitionMatrix', 'dBdt', 'WindowWidth', 'WindowCenterWidthExplanation', 'WindowCenter', 'VariableFlipAngleFlag', 'SliceLocation', 'SequenceVariant', 'SamplesPerPixel', 'PixelRepresentation', 'SeriesNumber', 'PixelBandwidth', 'PercentPhaseFieldOfView', 'NumberOfPhaseEncodingSteps', 'ImagePositionPatient', 'ImageOrientationPatient']: try: config_dict.pop(key) except KeyError: pass return config_dict
def parser_args(argv): """ Parse Alfred Arguments """ args = {} # determine search mode if(argv[0].lower() == "--clipboard"): args["mode"] = "clipboard" args["query"] = argv[1].lower() return args
def _set_default_contact_form_id(contact_form_id: int, subcategory_id: int) -> int: """Set the default contact foem ID for switches. :param contact_form_id: the current contact form ID. :param subcategory_id: the subcategory ID of the switch with missing defaults. :return: _contact_form_id :rtype: int """ if contact_form_id > 0: return contact_form_id try: return { 1: 2, 5: 3, }[subcategory_id] except KeyError: return 0
def recurring_2(strg): """Hash map solution O(n).""" counts = {} for c in strg: if c in counts: return c else: counts[c] = 1 return None
def bin_to_num(binstr): """ Convert a little endian byte-ordered binary string to an integer or long. """ # this will cast to long as needed num = 0 for charac in binstr: # the most significant byte is a the start of the string so we multiply # that value by 256 (e.g. <<8) and add the value of the current byte, # then move to next byte in the string and repeat num = (num << 8) + ord(charac) return num
def _same_target(node1, node2, gens): """ Calcs fitness based on the fact that two nodes should share same target. """ shared_tg = None for src in gens: if shared_tg is None and src in [node1, node2]: shared_tg = gens[src] elif shared_tg is not None and gens[src] != shared_tg: return 10.0 return 0.0
def _cinterval(start,stop,step,center,balanced): """find start,stop,step to make a centered range or slice""" if stop is None: start,stop = 0,start if center is None: center = (start + stop)//2 #offset start to hit center start += center - range(start,center,step)[-1] if balanced: #how many elements before & after center l = len(range(start,center,step)) r = len(range(center,stop,step)) - 1 if l < r: # cut off right side stop = range(center,stop,step)[l+1] elif r < l: #cut off left side start = range(start,center,step)[-r] return (start,stop,step)
def patch_get_deferred_fields(model): """ Django >= 1.8: patch detecting deferred fields. Crucial for only/defer to work. """ if not hasattr(model, 'get_deferred_fields'): return old_get_deferred_fields = model.get_deferred_fields def new_get_deferred_fields(self): sup = old_get_deferred_fields(self) if hasattr(self, '_fields_were_deferred'): sup.update(self._fields_were_deferred) return sup model.get_deferred_fields = new_get_deferred_fields
def sort_012(arr): """ Given an input array consisting on only 0, 1, and 2, sort the array in a single traversal. Args: arr(list): List to be sorted Returns: (None) """ n = len(arr) pos0 = 0 pos2 = n - 1 i = 0 while i <= pos2: if arr[i] == 0: arr[pos0], arr[i] = arr[i], arr[pos0] pos0 += 1 i += 1 elif arr[i] == 2: arr[pos2], arr[i] = arr[i], arr[pos2] pos2 -= 1 else: i += 1 return arr
def extract_dependencies(reg, assignments): """Return a list of all registers which directly depend on the specified register. Example: >>> extract_dependencies('a', {'a': 1}) [] >>> extract_dependencies('a', {'a': 'b', 'b': 1}) [] >>> extract_dependencies('a', {'a': 1, 'b': 'a'}) ['b'] >>> extract_dependencies('a', {'a': 1, 'b': 'a', 'c': 'a'}) ['b', 'c'] """ # sorted() is only for determinism return sorted([k for k,v in assignments.items() if v == reg])
def addToInventory(inventory, addedItems): """ Add Items to inventory Args: inventory (dict): Inventory containing items and their counts addedItems (list): Items to add to inventory Returns: updatedInventory (dict): Inventory containing updated items and their counts """ """ Procedure: - Ensure that the parameter passed is a dictionary - Loop through the items in the list and :. - If the list item does not exist, add it to the dictionary and attach a value of 0 to it - If it exists, increase the count of that particular item """ updatedInventory = dict(inventory) # your code goes here for item in addedItems: updatedInventory.setdefault(item, 0) updatedInventory[item] += 1 return updatedInventory
def falkner_skan_differential_equation(eta, f, beta): """ The governing differential equation of the Falkner-Skan boundary layer solution. :param eta: The value of eta. Not used; just set up like this so that scipy.integrate.solve_ivp() can use this function. :param f: A vector of 3 elements: f, f', and f''. :param beta: The Falkner-Skan beta parameter (beta = 2 * m / (m + 1) ) :return: The derivative w.r.t. eta of the input vector, expressed as a vector of 3 elements: f', f'', and f'''. """ dfdeta = [ f[1], f[2], -f[0] * f[2] - beta * (1 - f[1] ** 2) ] return dfdeta
def reduced_energy(temperature, potential): """Calculates reduced energy. Arguments: temperature - replica temperature potential - replica potential energy Returns: reduced energy of replica """ kb = 0.0019872041 # check for division by zero if temperature != 0: beta = 1. / (kb*temperature) else: beta = 1. / kb return float(beta * potential)
def havriliak_negami(x, de, logtau0, a, b, einf): """1-d HN: HN(x, logf0, de, a, b, einf)""" return de / ( 1 + ( 1j * x * 10**logtau0 )**a )**b + einf
def kill_procs(pids): """ Kill a list of processes using their PIDs Parameters ---------- pids : list A list of process id's (processes that ought to be killed) """ return ' '.join( ['kill -9'] + [ str(pid) for pid in pids ] )
def sol2(arr): """ This comes out of the editorial. Complexity is n """ n = len(arr) v = [-1 for i in range(256)] m = 1 clen = 1 v[ord(arr[0])] = 0 for i in range(1, n): lastIndex = v[ord(arr[i])] if lastIndex == -1 or i-clen > lastIndex: clen+=1 else: m = max(m, clen) clen = i - lastIndex v[ord(arr[i])] = i m = max(m, clen) return m
def calc_rate(rate, rate_long, maturity): """Approximate a current interest rate. Permforms linear interpolation based on the current 1-year and 10-year rates and the maturity of the bond. Parameters ---------- rate : float 1-year interest rate. rate_long : float 10-year interest rate. maturity : int Maturity of the bond in years. Returns ------- float Approximated interest rate. """ return rate + (rate_long - rate)*(maturity - 1) / 9
def correct_size_password(MAX_LEN): """Make sure that the password has a minimum of 5 character""" if MAX_LEN < 5: MAX_LEN = 5 else: MAX_LEN = MAX_LEN return MAX_LEN