content
stringlengths
42
6.51k
def dicts_union(a, b): """ Function calculates some kind of sum of two dictionaries :param a: Dictionary in form { (i, a) => [(coefficient_A, p_A)] } :param b: Dictionary in form { (i, a) => [(coefficient_B, p_b)] } :return: Dictionary in form { (i, a) => [(coefficient_A, p_A), (coefficient_B, p_B)] } """ result = {k: [] for k in a.keys() | b.keys()} for k in a: result[k] += a[k] for k in b: result[k] += b[k] return result
def _greater_than_equal(input, values): """Checks if the given input is >= the first value in the list :param input: The input to check :type input: int/float :param values: The values to check :type values: :func:`list` :returns: True if the condition check passes, False otherwise :rtype: bool """ try: return input >= values[0] except IndexError: return False
def pretty_format_args(*args, **kwargs): """ Take the args, and kwargs that are passed them and format in a prototype style. """ args = list([repr(a) for a in args]) for key, value in kwargs.items(): args.append("%s=%s" % (key, repr(value))) return "(%s)" % ", ".join([a for a in args])
def _mro(cls): """ Return the method resolution order for ``cls`` -- i.e., a list containing ``cls`` and all its base classes, in the order in which they would be checked by ``getattr``. For new-style classes, this is just cls.__mro__. For classic classes, this can be obtained by a depth-first left-to-right traversal of ``__bases__``. """ if isinstance(cls, type): return cls.__mro__ else: mro = [cls] for base in cls.__bases__: mro.extend(_mro(base)) return mro
def format_arg(arg: str, **kwargs): """apply pythons builtin format function to a string""" return arg.format(**kwargs)
def get_separators(clique_list, unique=True): """ :param clique_list list(set(int)): A list of cliques satisfying the running intersection property. :param unique (bool): Whether the returned list of separators should have no duplicates (True) or allow duplicates (False). :return sep_list (list(int)): The list of separators. """ seen = clique_list.pop(0) sep_list = [] for clique in clique_list: sep = clique.intersection(seen) seen = seen.union(clique) sep_list.append(frozenset(sep)) if unique: return list(set(sep_list)) else: return sep_list
def add_matrix(matrix1, matrix2): """ Adds matrix2 to matrix1 in place """ size = len(matrix1) for i in range(size): for j in range(size): matrix1[i][j] += matrix2[i][j] return matrix1
def currentTurn(turn): """ Simply returns the string version of whose turn it is as opposed to adding if/else everywhere """ if turn == 0: return "Red Team" elif turn == 1: return "Blue Team"
def JD2epochJulian(JD): #--------------------------------------------------------------------- """ Convert a Julian date to a Julian epoch :param JD: Julian date :type JD: Floating point number :Returns: Julian epoch :Reference: Standards Of Fundamental Astronomy, http://www.iau-sofa.rl.ac.uk/2003_0429/sofa/epj.html :Notes: e.g. ``2445700.5 converts into 1983.99863107`` Assuming years of exactly 365.25 days, we can calculate a Julian epoch from a Julian date. Expression corresponds to IAU SOFA routine 'epj' """ #---------------------------------------------------------------------- return 2000.0 + (JD - 2451545.0)/365.25
def make_object(type, data): """:return: bytes resembling an uncompressed object""" odata = "blob %i\0" % len(data) return odata.encode("ascii") + data
def _byte_string(s): """Cast a string or byte string to an ASCII byte string.""" return s.encode('ASCII')
def no_coords_same(coords): """ input: list of coords output: bool """ takenList=[{coord} for coord in coords] s=set() for taken in takenList: s= s.symmetric_difference(taken) u=set() for taken in takenList: u= u.union(taken) if s!= u: #notTooClose = False return False return True
def longestIncreasing(array): """ return N (length), path(list) as a tuple describing the subsequence O(n log n) memo[j] stores the position k of the smallest value X[k] such that there is an increasing subsequence of length j ending at X[k] on the range k <= i prev[k] stores the position of the predecessor of X[k] in the longest increasing subsequence ending at X[k]. """ memo = [0] prev = [0] * len(array) prev[0] = -1 for i in range(1, len(array)): # if next one is greater, add into the sequence if array[memo[-1]] < array[i]: prev[i] = memo[-1] memo.append(i) continue # binary search for the best update point low = 0 high = len(memo) - 1 while low < high: mid = (low + high) // 2 if array[memo[mid]] < array[i]: low = mid + 1 else: high = mid # update if the new value is smaller if array[i] < array[memo[low]]: if low > 0: prev[i] = memo[low - 1] memo[low] = i path = [] p = memo[-1] N = len(memo) for i in range(N): path.append(array[p]) p = prev[p] path.reverse() return N, path
def decodeFontName(font_name): """ Presume weight and style based on the font filename. """ name = font_name.split('-')[0] font_name = font_name.lower() weight = 400 style = 'regular' weights = {'light': 300, 'extralight': 200, 'bold': 700, 'semibold': 600, 'extrabold': 800, } for weight_item in weights.keys(): if weight_item in font_name: weight = str(weights[weight_item]) if 'italic' in font_name: style = 'italic' return (name, style, str(weight))
def is_balanced(text, brackets = "()[]{}<>"): """ >>> is_balanced("[]asdasdd()aqwe<asd>") True """ counts = {} left_for_right = {} for left, right in zip(brackets[::2], brackets[1::2]): assert left != right, "The brackets must be differ" counts[left] = 0 left_for_right[right] = left for c in text: if c in counts: counts[c] += 1 elif c in left_for_right: left = left_for_right[c] if counts[left] == 0: return False counts[left] -= 1 return not any(counts.values())
def IsEven(i): """Returns a Z3 condition for if an Int is even""" return i % 2 == 0
def included(combination, exclude): """ Checks if the combination of options should be included in the Travis testing matrix. @param exclude: A list of options to be avoided. """ return not any(excluded in combination for excluded in exclude)
def find_executable(name): """ Is the command 'name' available locally? :param name: command name (string). :return: full path to command if it exists, otherwise empty string. """ from distutils.spawn import find_executable return find_executable(name)
def qs2 (array): """ another longer version""" less = [] equal = [] greater = [] if len(array) > 1: pivot = array[0] for x in array: if x < pivot: less.append(x) if x == pivot: equal.append(x) if x > pivot: greater.append(x) return qs2(less)+equal+qs2(greater) else: return array
def agg_event_role_tpfpfn_stats(pred_records, gold_records, role_num): """ Aggregate TP,FP,FN statistics for a single event prediction of one instance. A pred_records should be formated as [(Record Index) ((Role Index) argument 1, ... ), ... ], where argument 1 should support the '=' operation and the empty argument is None. """ role_tpfpfn_stats = [[0] * 3 for _ in range(role_num)] if gold_records is None: if pred_records is not None: # FP for pred_record in pred_records: assert len(pred_record) == role_num for role_idx, arg_tup in enumerate(pred_record): if arg_tup is not None: role_tpfpfn_stats[role_idx][1] += 1 else: # ignore TN pass else: if pred_records is None: # FN for gold_record in gold_records: assert len(gold_record) == role_num for role_idx, arg_tup in enumerate(gold_record): if arg_tup is not None: role_tpfpfn_stats[role_idx][2] += 1 else: # True Positive at the event level # sort predicted event records by the non-empty count # to remove the impact of the record order on evaluation pred_records = sorted( pred_records, key=lambda x: sum(1 for a in x if a is not None), reverse=True, ) gold_records = list(gold_records) while len(pred_records) > 0 and len(gold_records) > 0: pred_record = pred_records[0] assert len(pred_record) == role_num # pick the most similar gold record _tmp_key = lambda gr: sum( [1 for pa, ga in zip(pred_record, gr) if pa == ga] ) best_gr_idx = gold_records.index(max(gold_records, key=_tmp_key)) gold_record = gold_records[best_gr_idx] for role_idx, (pred_arg, gold_arg) in enumerate( zip(pred_record, gold_record) ): if gold_arg is None: if pred_arg is not None: # FP at the role level role_tpfpfn_stats[role_idx][1] += 1 else: # ignore TN pass else: if pred_arg is None: # FN role_tpfpfn_stats[role_idx][2] += 1 else: if pred_arg == gold_arg: # TP role_tpfpfn_stats[role_idx][0] += 1 else: # tzhu: pred and gold are not None, and pred != gold, then this is a FP and FN condition role_tpfpfn_stats[role_idx][1] += 1 role_tpfpfn_stats[role_idx][2] += 1 del pred_records[0] del gold_records[best_gr_idx] # remaining FP for pred_record in pred_records: assert len(pred_record) == role_num for role_idx, arg_tup in enumerate(pred_record): if arg_tup is not None: role_tpfpfn_stats[role_idx][1] += 1 # remaining FN for gold_record in gold_records: assert len(gold_record) == role_num for role_idx, arg_tup in enumerate(gold_record): if arg_tup is not None: role_tpfpfn_stats[role_idx][2] += 1 return role_tpfpfn_stats
def coco_split_class_ids(split_name): """Return the COCO class split ids based on split name and training mode. Args: split_name: The name of dataset split. Returns: class_ids: a python list of integer. """ if split_name == 'all': return [] elif split_name == 'voc': return [ 1, 2, 3, 4, 5, 6, 7, 9, 16, 17, 18, 19, 20, 21, 44, 62, 63, 64, 67, 72 ] elif split_name == 'nonvoc': return [ 8, 10, 11, 13, 14, 15, 22, 23, 24, 25, 27, 28, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 65, 70, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 84, 85, 86, 87, 88, 89, 90 ] else: raise ValueError('Invalid split name {}!!!'.format(split_name))
def getRow(rowIndex): """ :type rowIndex: int :rtype: List[int] """ if rowIndex == 0: return [1] if rowIndex == 1: return [1,1] current_row = [1,1] for i in range(rowIndex-1): next_row = [1]+[current_row[i]+current_row[i+1] for i in range(len(current_row)-1)]+[1] current_row = next_row return current_row
def rotate(nums, k: int) -> None: """ Do not return anything, modify nums in-place instead. """ # nums = nums[k + 1:] + nums[:k + 1] for i in range(k): nums.insert(0, nums[-1]) nums.pop() return nums
def treelist_to_dict(treelist): """ take list with entries (nodenumber, qname, lbranch_node_number, rbranch_node_number) return dict with dict entries nodenumber: {"question": qname, "no_branch": lb, "yes_branch": rb} """ treelist = [(node, {"question": qname, "no_branch": no_branch,\ "yes_branch": yes_branch}) \ for (node, qname, no_branch, yes_branch) in treelist] tree_dict = dict(treelist) return tree_dict
def extractOutput(queryResults): """convenience function to extract results from active query object""" if not queryResults: return None try: return [x.toDict() if x else None for x in queryResults] except TypeError: return queryResults.toDict() return None
def get_configurations(configs): """Builds a list of all possible configuration dictionary from one configuration dictionary that contains all values for a key Args: configs (dict[str: List[any]]): a dictionary of configurations Returns: List: A list of configuration """ if type(configs) == list: return configs all_configs = [] config_keys = list(configs.keys()) def recursive_config_list_builder(param_type_index, current_param_dict, param_list): if param_type_index == len(param_list): all_configs.append(current_param_dict) else: if type(configs[config_keys[param_type_index]]) == list: for val in configs[param_list[param_type_index]]: temp = current_param_dict.copy() temp[param_list[param_type_index]] = val recursive_config_list_builder(param_type_index+1, temp, param_list) else: temp = current_param_dict.copy() temp[param_list[param_type_index]] = configs[ config_keys[param_type_index]] recursive_config_list_builder(param_type_index+1, temp, param_list) recursive_config_list_builder(0, dict(), config_keys) return all_configs
def _to_seconds(raw_time): """ Converts hh:mm:ss,ms time format to seconds. """ hours, mins, secs = raw_time.split(':') return int(hours) * 3600 + int(mins) * 60 + float(secs.replace(',', '.'))
def _splitstrip(string): """Split string at comma and return the stripped values as array.""" return [ s.strip() for s in string.split(u',') ]
def str2bool(stringToConvert): """Convert a string to a boolean. Args: * *stringToConvert* (str): The following string values are accepted as ``True``: "true", "t", "yes", "y", "on", "1". The following string values are accepted as ``False``: "false", "f", "no", "n", "off", "0". Input string evaluation is always case insensitive. Returns: ``True`` or ``False``, depending on input value. Raises: :exc:`TypeError<python:exceptions.TypeError>`: If input string is not one of the accepted values. """ if stringToConvert.lower() in ("true", "t", "yes", "y", "on", "1"): return True if stringToConvert.lower() in ("false", "f", "no", "n", "off", "0"): return False raise TypeError("The value '%s' is not considered a valid boolean in this context." % stringToConvert)
def _nested_reduce(f, x): """Fold the function f to the nested structure x (dicts, tuples, lists).""" if isinstance(x, list): return f([_nested_reduce(f, y) for y in x]) if isinstance(x, tuple): return f([_nested_reduce(f, y) for y in x]) if isinstance(x, dict): return f([_nested_reduce(f, v) for (_, v) in x.items()]) return x
def get_reverse_endian(bytes_array): """ Reverse endianness in arbitrary-length bytes array """ hex_str = bytes_array.hex() hex_list = ["".join(i) for i in zip(hex_str[::2], hex_str[1::2])] hex_list.reverse() return bytes.fromhex("".join(hex_list))
def get_s3_video_path(user_id: int, video_id: int) -> str: """Gets s3 video path path structure: users/<user_id>/videos/<video_id> Args: user_id: user_id video_id: video_id Returns: string url """ return f"users/{user_id}/videos/{video_id}"
def dict_loudassign(d, key, val): """ Assign a key val pair in a dict, and print the result """ print(key + ": " + str(val), flush=True) d[key] = val return d
def remove_brackets_from_end_of_url(url_: str) -> str: """ Removes square brackets from the end of URL if there are any. Args: url_ (str): URL to remove the brackets from. Returns: (str): URL with removed brackets, if needed to remove, else the URL itself. """ return url_[:-1] if url_[-1] in ['[', ']'] else url_
def get_next_page_link(links, index=1): """ Get the next page url of github from the response header returns none if the response do not contain next page """ link_list = links.split(',') for link in link_list: if 'rel="next"' in link: next_link= link.split('>;')[0][index:] return next_link return None
def linear(x, out=None): """ Linear function. Parameters ---------- x : numpy array Input data. out : numpy array, optional Array to hold the output data. Returns ------- numpy array Unaltered input data. """ if out is None or x is out: return x out[:] = x return out
def clamp(val, mini, maxi): """ Returns val, unless val > maxi in which case mini is returned or val < mini in which case maxi is returned """ return max(mini, min(maxi, val))
def _card(item): """Handle card entries Returns: title (append " - Card" to the name, username (Card brand), password (card number), url (none), notes (including all card info) """ notes = item.get('notes', "") or "" # Add card info to the notes notes = notes + ("\n".join([f"{i}: {j}" for i, j in item.get('card', "").items()])) return f"{item['name']} - Card", \ item.get('card', {}).get('brand', '') or "", \ item.get('card', {}).get('number', "") or "", \ "", \ notes
def split_token(tdata, seplist=[':','*']): """ like str.split(), but allow a list of separators, and return the corresponding list of separators (length should be one less than the length of the value list) along with the list of elements, i.e. return [split values] [separators] """ # deal with empty token or no separators first if len(tdata) == 0: return [''], [] toks = [] seps = [] start = 0 # start position for next token for posn in range(len(tdata)): if tdata[posn] in seplist: toks.append(tdata[start:posn]) seps.append(tdata[posn]) start = posn + 1 # and append the final token toks.append(tdata[start:]) return toks, seps
def unique( List ): """ return a compact set/list (only unique elements) of input list :List """ Res = [List[0]] for x in List: if x not in Res: Res.append(x) return Res
def should_cache_download(*args, **kwargs) -> bool: # pragma: no cover """ Determine whether this specific result should be cached. Here, we don't want to cache any files containing "-latest-" in their filenames. :param args: Arguments of decorated function. :param kwargs: Keyword arguments of decorated function. :return: When cache should be dimissed, return False. Otherwise, return True. """ url = args[0] if "-latest-" in url: return False return True
def apply_perm(values, perm): """Apply the permutation perm to the values.""" return [values[pi] for pi in perm]
def search_for_attr_value(obj_list, attr, value): """ Finds the first object in a list where it's attribute attr is equal to value. Finds the first (not necesarilly the only) object in a list, where its attribute 'attr' is equal to 'value'. Returns None if none is found. :param list obj_list: list of objects to search :param str attr: attribute to search for :param value: value that should be searched for :return: obj, from obj_list, where attribute attr matches value **returns the *first* obj, not necessarily the only """ return next((obj for obj in obj_list if getattr(obj, attr, None) == value), None)
def _splitshortoptlist(shortoptlist): """Split short options list used by getopt. Returns a set of the options. """ res = set() tmp = shortoptlist[:] # split into logical elements: one-letter that could be followed by colon while tmp: if len(tmp) > 1 and tmp[1] is ':': res.add(tmp[0:2]) tmp = tmp[2:] else: res.add(tmp[0]) tmp = tmp[1:] return res
def is_nullable_list(val, vtype): """Return True if list contains either values of type `vtype` or None.""" return (isinstance(val, list) and any(isinstance(v, vtype) for v in val) and all((isinstance(v, vtype) or v is None) for v in val))
def is_valid(sentString, recvString): """Check to see if the value recieved has the command inside of it.String is received directly from arduino. Rule: string must be in this format: [1,2,3]{4,5,6} """ if sentString in recvString: return True else: return False
def get_frequency(text): """ """ if text[-1].isdigit(): freq = float(text[:-1]) elif text[-1] == "M": freq = float(text[:-1])*1e6 else: raise RuntimeError("Unknown FROV suffix %s", text[-1]) return freq
def _calculate_total_mass_(elemental_array): """ Sums the total weight from all the element dictionaries in the elemental_array after each weight has been added (after _add_ideal_atomic_weights_()) :param elemental_array: an array of dictionaries containing information about the elements in the system :return: the total weight of the system """ return sum(a["weight"] for a in elemental_array)
def cut(value,arg): """ this cut all values of arg from string """ return value.replace(arg,'')
def get_loss(current_hospitalized, predicted) -> float: """Squared error: predicted vs. actual current hospitalized.""" return (current_hospitalized - predicted) ** 2.0
def is_palindrome3(w): """iterate from start and from end and compare, without copying arrays""" for i in range(0,round(len(w)/2)): if w[i] != w[-(i+1)]: return False return True # must have been a Palindrome
def font_style(keyword): """``font-style`` descriptor validation.""" return keyword in ('normal', 'italic', 'oblique')
def fix_census_date(x): """Utitlity function fixing the last census date in file with country info Parameters ---------- x : str Year or Year with adnotations Returns ------- str Year as string """ x = str(x) if x == "Guernsey: 2009; Jersey: 2011.": return "2009" elif len(x)>4: return x[:4] else: return x
def _get_rn_trail(trail, reactions): """Returns a textual representation of the CoMetGeNe trail using R numbers instead of the default internal KGML reaction IDs. :param trail: CoMetGeNe trail :param reactions: dict of dicts storing reaction information (obtained by parsing a KGML file) :return: textual representation of R numbers representing the CoMetGeNe trail in terms of R numbers instead of internal KGML reaction IDs """ rn_trail = list() for vertex in trail: if len(reactions[vertex]['reaction']) == 1: rn_trail.append(reactions[vertex]['reaction'][0]) else: rn_trail.append( '{' + ', '.join(reactions[vertex]['reaction']) + '}') return rn_trail
def rayleight_range(w0, k): """ doc """ return k * w0**2
def calculate_speeds(times, distances): """ :param times: A list of datetime objects which corresponds to the timestamps on transmissions :param distances: A list of calculated distances. Each I distance corresponds to location difference between I and I+1 Description: Takes a list of times and distances and returns the speed in KPH for the river node. """ speeds=[] for i in range (0, len(distances)-1): deltaTime = times[i] - times[i+1] #calculate time difference here calc_speed = distances[i]/(deltaTime.total_seconds()) #Right now returns the speed in meters per second if(calc_speed >10.0): #Added if check to remove speeds >10m/s. speeds.append(0) else: speeds.append(calc_speed) return speeds
def is_pingdom_recovery(data): """Determine if this Pingdom alert is of type RECOVERY.""" return data["current_state"] in ("SUCCESS", "UP")
def get_ip_sn_fabric_dict(inventory_data): """ Maps the switch IP Address/Serial No. in the multisite inventory data to respective member site fabric name to which it was actually added. Parameters: inventory_data: Fabric inventory data Returns: dict: Switch ip - fabric_name mapping dict: Switch serial_no - fabric_name mapping """ ip_fab = {} sn_fab = {} for device_key in inventory_data.keys(): ip = inventory_data[device_key].get('ipAddress') sn = inventory_data[device_key].get('serialNumber') fabric_name = inventory_data[device_key].get('fabricName') ip_fab.update({ip: fabric_name}) sn_fab.update({sn: fabric_name}) return ip_fab, sn_fab
def square_n(n): """Returns the square of a number""" return int(n * n)
def sort_proxy_stats_rows(proxy_stats, column): """ Sorts proxy statistics by specified column. Args: proxy_stats: A list of proxy statistics. column: An int representing a column number the list should be sorted by. Returns: A list sorted by specified column. """ return sorted(proxy_stats, key=lambda p: p[column], reverse=False)
def get_sfdc_conn(**p_dict): """ Args: dictionary with SFDC connection credentials Returns: SFDC connection string required by Simple-salesforce API Syntax SFDC connection: sf = Salesforce(username='', password='', security_token='') """ sfdc_conn = "Salesforce(username='" + p_dict['username'] + "', password='" + p_dict['password'] + "', security_token='" + p_dict['security_token']+"')" return sfdc_conn
def restore(segments, original_segments, invalid_segments, merged_segments): """ Replaces invalid segments with earlier segments. Parameters ---------- segments : list of segments The current wall segments. original_segments : list of segments The wall segments before any merging took place. invalid_segments : list of int The indices of the segments which have a higher error than the given max error. merged_segments : list of list of int The indices of the segments that were merged grouped together in lists. removed_segments : list of int The indices of the segments that got removed. Returns ------- segments : list of segments The segments with the original segments restored in place of the invalid segments. """ offset = 0 for invalid in invalid_segments: restore_segments = [original_segments[i] for i in merged_segments[invalid]] segments[invalid+offset:invalid+offset+1] = restore_segments offset += len(restore_segments)-1 return segments
def format_condition_value(conditions): """ @summary: ['111', '222'] -> ['111', '222'] ['111', '222\n333'] -> ['111', '222', '333'] ['', '222\n', ' 333 '] -> ['222', '333'] @param conditions: @return: """ formatted = [] for val in conditions: formatted += [item for item in val.strip().split('\n') if item] return formatted
def apply_matrix(src, mtx): """ src: [3] mtx: [3][3] """ a = src[0] * mtx[0][0] + src[1] * mtx[0][1] + src[2] * mtx[0][2] b = src[0] * mtx[1][0] + src[1] * mtx[1][1] + src[2] * mtx[1][2] c = src[0] * mtx[2][0] + src[1] * mtx[2][1] + src[2] * mtx[2][2] return a, b, c
def get_non_conflicting_name(template, conflicts, start=None, get_next_func=None): """ Find a string containing a number that is not in conflict with any of the given strings. A name template (containing "%d") is required. You may use non-numbers (strings, floats, ...) as well. In this case you need to override "start" and "get_next_func". @value template: a string template containing "%d" (e.g. "Object %d") @type template: basestr @value conflicts: a list of strings that need may not be used @type conflicts: list(basestr) @value start: optional initial value (default: len(conflicts) + 1) @type start: undefined @value get_next_func: function used for determining the next value to be tested. This function defaults to "lambda value: value + 1". @returns: a usable name that was not found in "conflicts" @rtype: basestr """ index = 1 if start is None else start if get_next_func is None: get_next_func = lambda current: current + 1 while (template % index) in conflicts: index = get_next_func(index) return template % index
def get_sstl(l, f): """space-separated token list""" token_list = [] for node in l: if token_list: token_list.append(' ') token = f(node) token_list.extend(token) return token_list
def update_inc(initial, key, count): """Update or create a dict of `int` counters, for StatsDictFields.""" initial = initial or {} initial[key] = count + initial.get(key, 0) return initial
def str_to_bool(value): """Represents value as boolean. :param value: :rtype: bool """ value = str(value).lower() return value in ('1', 'true', 'yes')
def make_dict(v: list) -> dict: """Make an alphabetically sorted dictionary from a list :param v<list>: list of an attribute type :return <dict>: in format {1: v[0], 2: v[1], ...} """ k = list(range(1, len(v) + 1)) return dict(zip(k, sorted(v)))
def grow_utopian_tree(n): """ :type n: int :rtype: int """ # height = 1 # for i in range(n): # height = height * 2 if i % 2 == 0 else height + 1 height = 2 ** ((n + 3) // 2) - 2 + (n + 1) % 2 return height
def withinEpsilon(x, y, epsilon): """x,y,epsilon floats. epsilon > 0.0 returns True if x is within epsilon of y""" return abs(x - y) <= epsilon
def is_already_latest_version(version: str) -> bool: """Returns ``True`` if the version is already the latest version""" try: with open('VERSION', 'r') as fp: other = fp.read().strip() except OSError: return False else: lhs = tuple(map(int, version.split('.'))) rhs = tuple(map(int, other.split('.'))) return lhs <= rhs
def both_positive(x, y): """ Returns True if both x and y are positive. >>> both_positive(-1, 1) False >>> both_positive(1, 1) True """ "*** YOUR CODE HERE ***" return x > 0 and y > 0
def linode_does_not_exist_for_operation(op, linode_id): """ Creates an error message when Linodes are unexpectedly not found for some operation :param op: operation for which a Linode does not exist :param linode_id: id that we expected to find :return: a snotty message """ return "Attempted to {0} a linode with id '{1}', but no \ such Linode exists in the system.".format(op, linode_id)
def my_function(x, y): """ A simple function to divide x by y """ print('my_function in') solution = x / y print('my_function out') return solution
def filter_overrides(overrides): """ :param overrides: overrides list :return: returning a new overrides list with all the keys starting with hydra. fitlered. """ return [x for x in overrides if not x.startswith("hydra.")]
def get_paths(level=15): """ Generates a set of paths for modules searching. Examples ======== >>> get_paths(2) ['ISPy/__init__.py', 'ISPy/*/__init__.py', 'ISPy/*/*/__init__.py'] >>> get_paths(6) ['ISPy/__init__.py', 'ISPy/*/__init__.py', 'ISPy/*/*/__init__.py', 'ISPy/*/*/*/__init__.py', 'ISPy/*/*/*/*/__init__.py', 'ISPy/*/*/*/*/*/__init__.py', 'ISPy/*/*/*/*/*/*/__init__.py'] """ wildcards = ["/"] for i in range(level): wildcards.append(wildcards[-1] + "*/") p = ["ISPy" + x + "__init__.py" for x in wildcards] return p
def format_pattern(bit, pattern): """Return a string that is formatted with the given bit using either % or .format on the given pattern.""" try: if "%" in pattern: return pattern % bit except: pass try: return pattern.format(bit) except: return pattern
def verifid_output(cmd_op): """vefifies if command output is in valid state. Multiline string are splits with CR. and retuns as list. if input is a list, it will be returned as is. any other input will throw error. Args: cmd_op (list, str): Either list or Multiline string of output Raises: TypeError: Raise error if input is other than string or list. Returns: list: output in list format """ if isinstance(cmd_op, str): cmd_op = cmd_op.split("\n") if not isinstance(cmd_op, list): raise TypeError("Invalid Command Output Received.\n" f"Expected either multiline-string or list, received {type(cmd_op)}.") return cmd_op
def _isNumeric(j): """ Check if the input object is a numerical value, i.e. a float :param j: object :return: boolean """ try: x = float(j) except ValueError: return False return True
def remove_more_info(dictionary): """ Removes the compilation information from the ACFGS : for each source function, transforms the map compilation option -> ACFG into a list containing only the ACFGs. """ return {filename: list(other_map.values()) for filename, other_map in dictionary.items()}
def convert_month_to_sec(time_month): """Function to convert time in months to secs""" ans = time_month * 30 * 24 * 60 * 60 return ans
def combine_extensions(lst): """Combine extensions with their compressed versions in a list. Valid combinations are hardcoded in the function, since some extensions look like compressed versions of one another, but are not. Parameters ---------- lst : list of str Raw list of extensions. Returns ------- new_lst : list of str List of extensions, with compressed and uncompressed versions of the same extension combined. """ COMPRESSION_EXTENSIONS = [".gz"] new_lst = [] items_to_remove = [] for item in lst: for ext in COMPRESSION_EXTENSIONS: if item.endswith(ext) and item.replace(ext, "") in lst: temp_item = item.replace(ext, "") + "[" + ext + "]" new_lst.append(temp_item) items_to_remove.append(item) items_to_remove.append(item.replace(ext, "")) continue items_to_add = [item for item in lst if item not in items_to_remove] new_lst += items_to_add return new_lst
def buildn(s): """ >>> buildn(4) 4 >>> buildn(10) 19 >>> buildn(20) 299 >>> buildn(21) 399 """ n, d = 0, 0 while s > 9: n = 10 * n + 9 s -= 9 d += 1 if s != 0: if n != 0: n = s * (10 ** d) + n else: n = s return n
def _prep_certificate(certificate): """ Append proper prefix and suffix text to a certificate. There is no standard way for storing certificates. OpenSSL expects the demarcation text. This method makes sure that the text the markers are present. :type text: :class:`str` :param text: The certificate of the service user. :rtype: :class:`str` :return: Normalized certificate """ if not certificate.startswith('-----BEGIN CERTIFICATE-----'): return """-----BEGIN CERTIFICATE----- %s -----END CERTIFICATE-----""" % certificate return certificate
def _get_info_names(profile): """Get names of infos of tasks.""" info_names = sorted(set().union(*(set(val) for val in profile.values()))) return info_names
def envelope_square(t, t_pulse, t_start=0, **not_needed_kwargs): """ Envelope for a square pulse (1 or 0). Parameters ---------- t : float Time at which the value of the envelope is to be returned. t_pulse : float The total duration of the pulse. t_start : float, default=0 Time at which the pulse starts. Returns ------- float The value of the envelope at a given time (1 or 0). See Also -------- derenv_square """ if t < t_start or t > t_start + t_pulse: return 0 else: return 1
def label_to_onehot(labels): """ Convert label to onehot . Args: labels (string): sentence's labels. Return: outputs (onehot list): sentence's onehot label. """ label_dict = {'THEORETICAL': 0, 'ENGINEERING':1, 'EMPIRICAL':2, 'OTHERS':3} onehot = [0,0,0,0] for l in labels.split(): onehot[label_dict[l]] = 1 return onehot
def parse_import_path(import_path: str): """ Takes in an import_path of form: [subdirectory 1].[subdir 2]...[subdir n].[file name].[attribute name] Parses this path and returns the module name (everything before the last dot) and attribute name (everything after the last dot), such that the attribute can be imported using "from module_name import attr_name". """ nodes = import_path.split(".") if len(nodes) < 2: raise ValueError( f"Got {import_path} as import path. The import path " f"should at least specify the file name and " f"attribute name connected by a dot." ) return ".".join(nodes[:-1]), nodes[-1]
def infer_missing_dims(frame_size, ref_size): """Infers the missing entries (if any) of the given frame size. Args: frame_size: a (width, height) tuple. One or both dimensions can be -1, in which case the input aspect ratio is preserved ref_size: the reference (width, height) Returns: the concrete (width, height) with no negative values """ width, height = frame_size kappa = ref_size[0] / ref_size[1] if width < 0: if height < 0: return ref_size width = int(round(height * kappa)) elif height < 0: height = int(round(width / kappa)) return width, height
def ignoreRead(chr_l, loc_l, chr_r, loc_r, chrHash): """Check if a fragment aligned in particular location is to be excluded from analysis Inputs: chr_l: chr name of left alignment chr_r: chr name of right alignment loc_l: left alignment 'arrow-tip' location loc_r: right alignment 'arrow-tip' location Outputs: boolean indicating whether alignment is to be excluded (True) or not (False) """ if chr_l in chrHash and chrHash[chr_l][loc_l] == 1: return True if chr_r in chrHash and chrHash[chr_r][loc_r] == 1: return True return False
def validate_signature(public_key, signature, message): """Verifies if the signature is correct. This is used to prove it's you (and not someone else) trying to do a transaction with your address. Called when a user tries to submit a new transaction. """ return True # public_key = (base64.b64decode(public_key)).hex() # signature = base64.b64decode(signature) # vk = ecdsa.VerifyingKey.from_string(bytes.fromhex(public_key), curve=ecdsa.SECP256k1) # # Try changing into an if/else statement as except is too broad. # try: # return vk.verify(signature, message.encode()) # except: # return False
def is_year_leap(year): """Determines whether a year is a leap year""" if year % 4 == 0 and year % 100 != 0: return True elif year % 400 == 0: return True else: return False
def declare_draw_if_no(player_one, player_two): """ Return True to continue """ if player_one.find('no') > 1: return None elif player_two.find('no') > 1: return None else: return True
def truncate_msg(msg, max_len=2000): """ Truncate a message string so it doesn't get lost (todo: automatically do this in realtime logger class) """ if len(msg) <= max_len: return msg else: trunc_info = '<log message truncated to fit buffer>' assert len(trunc_info) < max_len return msg[:max_len-len(trunc_info)] + trunc_info
def _python3_selectors(read_fds, timeout): """ Use of the Python3 'selectors' module. NOTE: Only use on Python 3.5 or newer! """ import selectors # Inline import: Python3 only! sel = selectors.DefaultSelector() for fd in read_fds: sel.register(fd, selectors.EVENT_READ, None) events = sel.select(timeout=timeout) try: return [key.fileobj for key, mask in events] finally: sel.close()
def _pick_align_split_size(total_size, target_size, target_size_reads, max_splits): """Do the work of picking an alignment split size for the given criteria. """ # Too many pieces, increase our target size to get max_splits pieces if total_size // target_size > max_splits: piece_size = total_size // max_splits return int(piece_size * target_size_reads / target_size) else: return int(target_size_reads)
def oversampled(semibmaj, semibmin, x=30): """ It has been identified that having too many pixels across the restoring beam can lead to bad images, however further testing is required to determine the exact number. :param Semibmaj/semibmin: describe the beam size in pixels :returns: True if beam is oversampled, False otherwise """ return semibmaj > x or semibmin > x
def get_out_type(string: str): """Return SCPI representation of voltage, current, or resistance.""" string = str(string)[0].upper() return ('VOLT' if 'V' in string else ('CURR' if 'C' in string else ('RES' if 'R' in string else 'ERR')))
def square_area(side): """Returns the area of a square""" # You have to code here # REMEMBER: Tests first!!! return pow(side, 2)