content
stringlengths
42
6.51k
def isStandard(x): """ Is this encoding required by the XML 1.0 Specification, 4.3.3? """ return x.upper() in ['UTF-8', 'UTF-16']
def _set_bool(val): """Helper to convert the given value to boolean.""" true_values = ['true', 'yes', 'y', 'on', '1'] return isinstance(val, str) and val.lower() in true_values
def count_occurences(column): """Part of the coincidence index of a message`s columns: the letters count process""" letters_count = {c: 0 for c in column} for c in column: letters_count[c] += 1 return letters_count
def intersection(lst1, lst2): """returns the intersection between two lists""" if (lst1 == None or lst2 == None): return [] lst3 = [value for value in lst1 if value in lst2] return lst3
def is_npy(s): """ Filter check for npy files :param str s: file path :returns: True if npy :rtype: bool """ if s.find(".npy") == -1: return False else: return True
def _get_baseline_value(baseline, key): """ We need to distinguish between no baseline mode (which should return None as a value), baseline mode with exceeded timeout (which is stored as None, but should return 0). """ if key in baseline: return 0 if baseline[key] is None else baseline[key]
def dsigmoid(x): """ Derivative of sigmoid function :param x: array-like shape(n_sample, n_feature) :return: derivative value (array like) """ return x * (1. - x)
def _escape(txt): """Basic html escaping.""" txt = txt.replace('&', '&amp;') txt = txt.replace('<', '&lt;') txt = txt.replace('>', '&gt;') txt = txt.replace('"', '&quot;') return txt
def computeF1(goldList, predictedList): """Assume all questions have at least one answer""" if len(goldList) == 0: if len(predictedList) == 0: return (1, 1, 1) else: return (0, 0, 0) # raise Exception("gold list may not be empty") """If we return an empty list recall is zero and precision is one""" if len(predictedList) == 0: return (0, 1, 0) """It is guaranteed now that both lists are not empty""" precision = 0 for entity in predictedList: if entity in goldList: precision += 1 precision = float(precision) / len(predictedList) recall = 0 for entity in goldList: if entity in predictedList: recall += 1 recall = float(recall) / len(goldList) f1 = 0 if precision + recall > 0: f1 = 2 * recall * precision / (precision + recall) return recall, precision, f1
def strfmt(value): """ Apply a format to a real value for writing out the data values. This routine is used to format an input real value either in exponential format or in floating point format depending on the magnitude of the input value. This works better for constant width columns than the Python g format. Parameters ---------- value : a real number value Returns ------- outstring : a format string segment """ if (abs(value) > 1.e+07) or (abs(value) < 0.001): outstring = '%14.7e ' % (value) if value == 0.: outstring = '%14.6f ' % (value) else: outstring = '%14.6f ' % (value) outstring = outstring.lstrip(' ') return outstring
def get_permission_names(perm_int): """Takes an integer representing a set of permissions and returns a list of corresponding permission names.""" pms = {'God': 16, 'Admin': 8, 'Builder': 2, 'Player': 1, 'DM': 4} perm_list = [] for key, value in pms.items(): if perm_int & value: perm_list.append(key) return perm_list
def Mreq(mg,deltaGcat): """ Computes the requested maintenance rate from mg the maintenance free energy trait and the catabolic energy **REF** """ return(-mg/deltaGcat)
def transpose_table(table): """ Transposes a table, turning rows into columns. :param table: A 2D string grid. :type table: [[``str``]] :return: The same table, with rows and columns flipped. :rtype: [[``str``]] """ if len(table) == 0: return table else: num_columns = len(table[0]) return [[row[i] for row in table] for i in range(num_columns)]
def num_to_num(nums): """Converts the numeric list to alphabetic list likewise, chr()reutrns the charactor from a number based on Unicode""" num_list = [chr(i -1 + ord('a')) for i in nums] return ''.join(num_list)
def limit_tag_output_to_id_and_name(attribute_dict, is_event_level): """ As tag list can be full of in unnecessary data, we want to limit this list to include only the ID and Name fields. In addition, returns set of the found tag ids. Some tags have a field called inherited. When it is set to 1 it says that it is an event's tag. Otherwise (if it is set to 0 or not exists) it says that it is an attribute's tag. If the data is event's (is_event_level = true) we would like to add to tag_set_ids all the tags (event ones and the event's attribute tags ones as it is part of the event scope). If the data is attribute's (is_event_level = false), and the tag is only related to an attribute we would like to add it to tag_set_ids. In any other case, we won't add the tag. Args: attribute_dict (dict): The dictionary that includes the tag list. is_event_level (bool): Whether the attribute_dict was received from an event object, meaning the tags are event's ones. Otherwise, the data is attribute's (attribute tags). """ output = [] tag_set_ids = set() tags_list = attribute_dict.get('Tag', []) for tag in tags_list: is_event_tag = tag.get('inherited', 0) # field doesn't exist when this is an attribute level, default is '0' tag_id = tag.get('id') if is_event_level: tag_set_ids.add(tag_id) else: # attribute level if not is_event_tag: tag_set_ids.add(tag_id) output.append({'ID': tag_id, 'Name': tag.get('name')}) return output, tag_set_ids
def int_to_bin(num_int, length): """convert int to binary string of given length""" num_str = bin(num_int)[2:] str_len = len(num_str) if length <= str_len: return num_str[str_len - length : str_len] else: return num_str.zfill(length)
def _search_node(key, tree): """Support function for search the tree for a node based on the key. This returns the node if found else None is returned. """ if not tree: return None elif key == tree.key: return tree elif key < tree.key: return _search_node(key, tree.left_child) else: return _search_node(key, tree.right_child)
def convert_dict_id_values_to_strings(dict_list): """This function ensures that the ``id`` keys in a list of dictionaries use string values. :param dict_list: List (or tuple) of dictionaries (or a single dictionary) containing API object data :type dict_list: list, tuple, dict, None :returns: A new dictionary list with properly formatted ``id`` values :raises: :py:exc:`TypeError` """ dict_list = [dict_list] if isinstance(dict_list, dict) else dict_list new_dict_list = [] for single_dict in dict_list: if not isinstance(single_dict, dict): raise TypeError("The 'dict_list' argument must be a dictionary or a list of dictionaries.") if 'id' in single_dict and not isinstance(single_dict.get('id'), str): single_dict['id'] = str(single_dict.get('id')) new_dict_list.append(single_dict) return new_dict_list
def lista_str(cadena): """Transforma una cadena a lista sin espacios cadena -- Cadena que se desea pasar a list """ lista = [] cadena = cadena.replace(' ', '', -1) for i in cadena: lista.append(i) return lista
def root() -> dict: """ Root Get """ return {"msg": "This is the Example API"}
def electric_source(data, meta): """ Fix up electricity for how much the Grids consume """ # flip sign because we consume the electricity E = -1.0 * meta['HERON']['activity']['electricity'] data = {'driver': E} return data, meta
def flatten(dict_item): """Flatten lists in dictionary values for better formatting.""" flat_dict = {} for k, v in dict_item.items(): flat_dict[k] = ",".join(v) if type(v) is list else v return flat_dict
def coordinateHashToXYTupleList(coordinateHash): """ Converts a coordinateHash to a list of tuples :param dict coordinateHash: a hash using {x1:[y1:True,y2:True..],x1:[y1:True,y2:True..]} format :return: list of (x,y) tuples. """ return [(x, y) for x, _y in coordinateHash.items() for y, _ in _y.items()]
def _extractDotSeparatedPair(string): """ Extract both parts from a string of the form part1.part2. The '.' used is the last in the string. Returns a pair (part1, part2). Useful for parsing machine.buildType filenames. """ i = string.rfind('.') return string[:i], string[i+1:]
def compute_intersection(arr_1, arr_2): """ Question 14.1: Compute the intersection of two sorted arrays """ idx_1 = 0 idx_2 = 0 intersection = [] while idx_1 < len(arr_1) and idx_2 < len(arr_2): if arr_1[idx_1] == arr_2[idx_2]: if not len(intersection) or arr_1[idx_1] != intersection[-1]: intersection.append(arr_1[idx_1]) idx_1 += 1 idx_2 += 1 elif arr_1[idx_1] < arr_2[idx_2]: idx_1 += 1 else: idx_2 += 1 return intersection
def normalize(collection): """ Normalize the value of all element in a collection each element will be divided by the sum """ if isinstance(collection, dict): total = 0 result = {} for key in collection: total += collection[key] if total == 0: return {} for key in collection: result[key] = collection[key] / total else: total = sum(collection) result = [0] * len(collection) if total == 0: return result for i in range(len(collection)): result[i] = collection[i] / total return result
def update_newton(yvals, y0): """Calculate the variable increment using Newton's method. Calculate the amount to increment the variable by in one iteration of Newton's method. The goal is to find the value of x for which y(x) = y0. `yvals` contains the values [y(x0), y'(x0), ...] of the function and its derivatives at the current estimate of x. The Newton update increment is dx = (y0 - y)/y'. Newton's method iterates by adding x += dx at each step. Arguments: yvals (iterable of float or array): The value of y(x) and its derivatives at the current estimate of x. Must contain at least 2 entries, for y and y'. y0 (float or array): The target value of y. Returns: dx (float or array): The update increment for x. """ dx = (y0 - yvals[0])/yvals[1] return dx
def splitter(h): """ Splits dictionary numbers by the decimal point.""" if type(h) is dict: for k, i in h.items(): h[k] = str(i).split('.'); if type(h) is list: for n in range(0, len(h)): h[n] = splitter(h[n]) return h
def get_next_slug(base_value, suffix, max_length=100): """ Gets the next slug from base_value such that "base_value-suffix" will not exceed max_length characters. """ suffix_length = len(str(suffix)) + 1 # + 1 for the "-" character if suffix_length >= max_length: raise ValueError("Suffix {} is too long to create a unique slug! ".format(suffix)) return '{}-{}'.format(base_value[:max_length - suffix_length], suffix)
def median_of_3(num1, num2, num3): """Utility functions to compute the median of 3 numbers""" return num1 + num2 + num3 - min(num1, num2, num3) - max(num1, num2, num3)
def _count_parenthesis(value): """Count the number of `(` and `)` in the given string.""" return sum([i for i, c in enumerate(value) if c in ["(", ")"]])
def create_scale(tonic, pattern, octave=1): """ Create an octave-repeating scale from a tonic note and a pattern of intervals Args: tonic: root note (midi note number) pattern: pattern of intervals (list of numbers representing intervals in semitones) octave: span of scale (in octaves) Returns: list of midi notes in the scale """ assert(sum(pattern)==12) scale = [tonic] note = tonic for o in range(octave): for i in pattern: note += i if note <= 127: scale.append(note) return scale
def dict_to_list(states, dictionary): """ :param states: no. of states :param dictionary: input distribution :return: a list of values for each states """ rows = [] for i in states: rows.append(list(dictionary[i].values())) return rows.copy()
def is_hex(s): """check if string is all hex digits""" try: int(s, 16) return True except ValueError: return False
def flatten_list(l): """Flattens a nested list """ return [x for nl in l for x in nl]
def change_fmt(val, fmt): """ """ if val > 0: return "+" + fmt(val) else: return fmt(val)
def _sparql_var(_input): """Add the "?" if absent""" return _input if _input.startswith('?') else '?' + _input
def normpath(pathname): """Make sure no illegal characters are contained in the file name.""" from sys import platform illegal_chars = ":?*" for c in illegal_chars: # Colon (:) may in the path after the drive letter. if platform == "win32" and c == ":" and pathname[1:2] == ":": pathname = pathname[0:2]+pathname[2:].replace(c,"") else: pathname = pathname.replace(c,".") return pathname
def find_sum(inputs, target): """ given a list of input integers, find the (first) two numbers which sum to the given target, and return them as a 2-tuple. Return None if the sum could not be made. """ for i in inputs: if i < target // 2 + 1: if target - i in inputs: return (i, target - i)
def rec_multiply(a_multiplier, digit, carry): """Function to multiply a number by a digit""" if a_multiplier == '': return str(carry) if carry else '' prefix = a_multiplier[:-1] last_digit = int(a_multiplier[-1]) this_product = last_digit * digit + carry this_result = this_product % 10 this_carry = this_product // 10 return rec_multiply(prefix, digit, this_carry) + str(this_result)
def sec2hms(seconds): """Seconds to hours, minutes, seconds""" hours, seconds = divmod(seconds, 60**2) minutes, seconds = divmod(seconds, 60) return (int(hours), int(minutes), seconds)
def total_takings(monthly_takings): """ A regular flying circus happens twice or three times a month. For each month, information about the amount of money taken at each event is saved in a list, so that the amounts appear in the order in which they happened. The months' data is all collected in a dictionary called monthly_takings. For this quiz, write a function total_takings that calculates the sum of takings from every circus in the year. Here's a sample input for this function: monthly_takings = {'January': [54, 63], 'February': [64, 60], 'March': [63, 49], 'April': [57, 42], 'May': [55, 37], 'June': [34, 32], 'July': [69, 41, 32], 'August': [40, 61, 40], 'September': [51, 62], 'October': [34, 58, 45], 'November': [67, 44], 'December': [41, 58]} """ sum_total_takings_in_year = 0 for key_month in monthly_takings: takings_in_month = monthly_takings[key_month] sum_takings_in_month = sum(takings_in_month) sum_total_takings_in_year += sum_takings_in_month return sum_total_takings_in_year
def safe_lookup(dictionary, *keys, default=None): """ Recursively access nested dictionaries Args: dictionary: nested dictionary *keys: the keys to access within the nested dictionaries default: the default value if dictionary is ``None`` or it doesn't contain the keys Returns: None if we can't access to all the keys, else dictionary[key_0][key_1][...][key_n] """ if dictionary is None: return default for key in keys: dictionary = dictionary.get(key) if dictionary is None: return default return dictionary
def _is_eqsine(opts): """ Checks to see if 'eqsine' option is set to true Parameters ---------- opts : dict Dictionary of :func:`pyyeti.srs.srs` options; can be empty. Returns ------- flag : bool True if the eqsine option is set to true. """ if "eqsine" in opts: return opts["eqsine"] return False
def clean_requirement(requirement): """Return only the name portion of a Python Dependency Specification string the name may still be non-normalized """ return ( requirement # the start of any valid version specifier .split("=")[0] .split("<")[0] .split(">")[0] .split("~")[0] .split("!")[0] # this one is poetry only .split("^")[0] # quoted marker .split(";")[0] # start of any extras .split("[")[0] # url spec .split("@")[0] .strip() )
def gyroWordToFloat(word): """Converts the 16-bit 2s-complement ADC word into appropriate float. Division scaling assumes +-250deg/s full-scale range. Args: word - 16-bit 2's-complement ADC word. Return: float """ if word & 0x8000: return float((word ^ 0xffff) + 1) / 131 * -1 else: return float(word) / 131
def normalize_str(name: str) -> str: """ return normalized string for paths and such """ return name.strip().replace(' ', '_').lower()
def build_search_filter(search_params: dict): """ Build a search filter for the django ORM from a dictionary of query params Args: search_params: Returns: """ search_filter = { 'hide': False } if 'species' in search_params: search_filter['species__in'] = search_params['species'].split(',') if 'west' in search_params: search_filter['longitude__gte'] = search_params['west'] if 'east' in search_params: search_filter['longitude__lte'] = search_params['east'] if 'south' in search_params: search_filter['latitude__gte'] = search_params['south'] if 'north' in search_params: search_filter['latitude__lte'] = search_params['north'] if 'start' in search_params: search_filter['recorded_at_iso__gte'] = search_params['start'] if 'end' in search_params: search_filter['recorded_at_iso__lte'] = search_params['end'] return search_filter
def version_tuple_to_str(version): """Join version tuple to string.""" return '.'.join(map(str, version))
def MergePList(plist1, plist2): """Merges |plist1| with |plist2| recursively. Creates a new dictionary representing a Property List (.plist) files by merging the two dictionary |plist1| and |plist2| recursively (only for dictionary values). List value will be concatenated. Args: plist1: a dictionary representing a Property List (.plist) file plist2: a dictionary representing a Property List (.plist) file Returns: A new dictionary representing a Property List (.plist) file by merging |plist1| with |plist2|. If any value is a dictionary, they are merged recursively, otherwise |plist2| value is used. If values are list, they are concatenated. """ result = plist1.copy() for key, value in plist2.items(): if isinstance(value, dict): old_value = result.get(key) if isinstance(old_value, dict): value = MergePList(old_value, value) if isinstance(value, list): value = plist1.get(key, []) + plist2.get(key, []) result[key] = value return result
def font_color_helper(background_color, light_color=None, dark_color=None): """Helper function to determine which font color to use""" light_color = light_color if light_color is not None else "#FFFFFF" dark_color = dark_color if dark_color is not None else "#000000" tmp_color = background_color.strip().strip('#') tmp_r = int(tmp_color[:2], 16) tmp_g = int(tmp_color[2:4], 16) tmp_b = int(tmp_color[4:], 16) font_color_code = dark_color if ((tmp_r * 0.299) + (tmp_g * 0.587) + (tmp_b * 0.114)) > 186 else light_color return font_color_code
def trade(first, second): """Exchange the smallest prefixes of first and second that have equal sum. >>> a = [1, 1, 3, 2, 1, 1, 4] >>> b = [4, 3, 2, 7] >>> trade(a, b) # Trades 1+1+3+2=7 for 4+3=7 'Deal!' >>> a [4, 3, 1, 1, 4] >>> b [1, 1, 3, 2, 2, 7] >>> c = [3, 3, 2, 4, 1] >>> trade(b, c) 'No deal!' >>> b [1, 1, 3, 2, 2, 7] >>> c [3, 3, 2, 4, 1] >>> trade(a, c) 'Deal!' >>> a [3, 3, 2, 1, 4] >>> b [1, 1, 3, 2, 2, 7] >>> c [4, 3, 1, 4, 1] """ m, n = 1, 1 "*** YOUR CODE HERE ***" if not first or not second: return 'No deal!' suma, sumb = first[0], second[0] while suma != sumb and m < len(first) and n < len(second): if suma < sumb: suma, m = suma + first[m], m + 1 else: sumb, n = sumb + second[n], n + 1 if suma == sumb: # change this line! first[:m], second[:n] = second[:n], first[:m] return 'Deal!' else: return 'No deal!'
def add_addon_extra_info(ret, external_account, addon_name): """add each add-on's account information""" if addon_name == 'dataverse': ret.update({ 'host': external_account.oauth_key, 'host_url': 'https://{0}'.format(external_account.oauth_key), }) return ret
def get_experiment_type(filename): """ Get the experiment type from the filename. The filename is assumed to be in the form of: '<reliability>_<durability>_<history kind>_<topic>_<timestamp>' :param filename: The filename to get the type. :return: A string where the timesptamp is taken out from the filename. """ file_type = '' filename = filename.split('/')[-1] elements = filename.split('_') for i in range(0, len(elements) - 3): file_type += '{}_'.format(elements[i]) file_type = file_type[:-1] return file_type
def worth_to_put_in_snippet(code_line: str) -> bool: """Check if a line of source code is worth to be in a code snippet""" if "async " in code_line or "def " in code_line: return True if code_line.strip().startswith("assert"): return True return False
def letter_to_color(letter): """ Transfer a letter into a color A corresponds to red. B corresponds to yellow. C corresponds to green. D corresponds to blue. :param letter: an input letter :type letter: string :return: a color :rtype: string """ if letter == "A": return "rgb(230,0,0)" elif letter == "B": return "rgb(252,251,52)" elif letter == "C": return "rgb(0,175,0)" elif letter == "D": return "rgb(25,128,255)"
def _parse_yaml_boolean(value: str) -> bool: """ Parse string according to YAML 1.2 boolean spec: http://yaml.org/spec/1.2/spec.html#id2803231 :param value: YAML boolean string :return: bool if string matches YAML boolean spec """ value = str(value) if value == 'true': return True elif value == 'false': return False else: raise ValueError(f'Passed string: {value} is not valid YAML boolean.')
def is_binary_string(string_): """ detect if string is binary (https://stackoverflow.com/a/7392391) :param string_: `str` to be evaluated :returns: `bool` of whether the string is binary """ if isinstance(string_, str): string_ = bytes(string_, 'utf-8') textchars = (bytearray({7, 8, 9, 10, 12, 13, 27} | set(range(0x20, 0x100)) - {0x7f})) return bool(string_.translate(None, textchars))
def _get_transition_attr(trans_prod, transition_attr_operations): """Return the attribute of a transition constructed by taking the product of transitions in trans_prod. @type trans_prod: `list` of `Transitions` objects @type transition_attr_operations: `dict` whose key is the transition attribute key and value is the operation to be performed for this transition attribute. For an attribute whose operation is not specified, a tuple of attribute values from all models will be used. """ trans_attr = {} for idx, trans in enumerate(trans_prod): for trans_attr_key, trans_attr_value in trans[2].items(): if trans_attr_key not in trans_attr: trans_attr[trans_attr_key] = [None for i in range(len(trans_prod))] trans_attr[trans_attr_key][idx] = trans_attr_value for key, val in trans_attr.items(): operation = transition_attr_operations.get(key, None) if operation is None: trans_attr[key] = tuple(val) else: trans_attr[key] = operation(*val) return trans_attr
def get_type_name(obj): """ Given an object, return the name of the type of that object. If `str(type(obj))` returns `"<class 'threading.Thread'>"`, this function returns `"threading.Thread"`. """ try: return str(type(obj)).split("'")[1] except Exception: return str(type(obj))
def concat_track_data(tags, audio_info): """Combine the tag and audio data into one dictionary per track.""" track_data = {} for k, v in audio_info.items(): track_data[k] = {**v, "t": tags[k]} return track_data
def num2int(num): """ >>> num2int('1,000,000') 1000000 """ return int(num.replace(',', ''))
def notification_event(events): """ Property: NotificationConfig.NotificationEvents """ valid_events = ["All", "InProgress", "Success", "TimedOut", "Cancelled", "Failed"] for event in events: if event not in valid_events: raise ValueError( 'NotificationEvents must be at least one of: "%s"' % (", ".join(valid_events)) ) return events
def isprime(n): """Returns True if n is prime. O(sqrt(n))""" if n < 2: return False if n == 2 or n == 3: return True if n % 2 == 0 or n % 3 == 0: return False i = 5 w = 2 while i * i <= n: if n % i == 0: return False i += w w = 6 - w return True
def remove_prefix(string, prefix): """ Removes a prefix from the string, if it exists. """ if string.startswith(prefix): return string[len(prefix):] else: return string[:]
def _clear_return(element, *return_values): """Return Results after Clearing Element.""" element.clear() if len(return_values) == 1: return return_values[0] return return_values
def split_by_lines(text, remove_empty=False): """ Split text into lines. Set <code>remove_empty</code> to true to filter out empty lines @param text: str @param remove_empty: bool @return list """ lines = text.splitlines() return remove_empty and [line for line in lines if line.strip()] or lines
def color_text(color_enabled, color, string): """Return colored string.""" if color_enabled: # LF should not be surrounded by the escape sequence. # Otherwise, additional whitespace or line-feed might be printed. return '\n'.join([ '\033[' + color + 'm' + s + '\033[0m' if s else '' for s in string.split('\n') ]) else: return string
def cmp_func(y: float, behavior: str, f, x: float) -> bool: """Decide whether y < f(x), but where "<" can be specified. :param y: number to compare to f(x) :param behavior: string that can be 'less' or 'greater' :param f: function of 1 variable :param x: number at which to evaluate f, and then compare to y :return: boolean, whether or not y > f(x) or y < f(x) etc. """ if behavior == 'less': return y < f(x) elif behavior == 'greater': return y > f(x) else: raise ValueError("behavior must be 'less' or 'greater'. Got %s " % behavior)
def shebang_command(path_to_file): """Get the shebang line of that file Which is the first line, if that line starts with #! """ try: first_line = open(path_to_file).readlines()[0] if first_line.startswith('#!'): return first_line[2:].strip() except (IndexError, IOError, UnicodeDecodeError): return ''
def nonrigid_rotations(spc_mod_dct_i): """ dtermine if a nonrigid rotation model is specified and further information is needed from the filesystem """ rot_model = spc_mod_dct_i['rot']['mod'] return bool(rot_model == 'vpt2')
def project(atts, row, renaming={}): """Create a new dictionary with a subset of the attributes. Arguments: - atts is a sequence of attributes in row that should be copied to the new result row. - row is the original dictionary to copy data from. - renaming is a mapping of names such that for each k in atts, the following holds: - If k in renaming then result[k] = row[renaming[k]]. - If k not in renaming then result[k] = row[k]. renaming defauts to {} """ res = {} for c in atts: if c in renaming: res[c] = row[renaming[c]] else: res[c] = row[c] return res
def northing_and_easting(dictionary): """ Retrieve and return the northing and easting strings to be used as dictionary keys Parameters ---------- dictionary : dict Returns ------- northing, easting : tuple """ if not 'x' and 'y' in dictionary.keys(): northing = 'latitude' easting = 'longitude' else: northing = 'x' easting = 'y' return northing, easting
def byte2str(e): """Return str representation of byte object""" return e.decode("utf-8")
def calculate_map(aps): """ Prints the average precision for each class and calculates micro mAP and macro mAP. @param aps: average precision for each class @param dictionary: mapping between label anc class name @return: micro mAP and macro mAP """ total_instances = [] precisions = [] for label, (average_precision, num_annotations) in aps.items(): total_instances.append(num_annotations) precisions.append(average_precision) if sum(total_instances) == 0: print('No test instances found.') return 0, 0 micro_ap = sum([a * b for a, b in zip(total_instances, precisions)]) / sum(total_instances) macro_ap = sum(precisions) / sum(x > 0 for x in total_instances) print('Micro mAP : {:.4f}'.format(micro_ap)) print('Macro mAP: {:.4f}'.format(macro_ap)) return micro_ap, macro_ap
def doc_arg(name, brief): """argument of doc_string""" return " :param {0}: {1}".format(name, brief)
def parse_option_settings(option_settings): """ Parses option_settings as they are defined in the configuration file """ ret = [] for namespace, params in option_settings.items(): for key, value in params.items(): ret.append((namespace, key, value)) return ret
def get_session_id_to_name(db, ipython_display): """Gets a dictionary that maps currently running livy session id's to their names Args: db (dict): the ipython database where sessions dict will be stored ipython_display (hdijupyterutils.ipythondisplay.IpythonDisplay): the display that informs the user of any errors that occur while restoring sessions Returns: session_id_to_name (dict): a dictionary mapping session.id -> name If no sessions can be obtained from previous notebook sessions, an empty dict is returned. """ try: session_id_to_name = db['autorestore/' + 'session_id_to_name'] return session_id_to_name except KeyError: db['autorestore/' + 'session_id_to_name'] = dict() return dict() except Exception as caught_exc: ipython_display.writeln("Failed to restore session_id_to_name from a previous notebook "\ f"session due to an error: {str(caught_exc)}. Cleared session_id_to_name.") return dict()
def fact(n): """Return the factorial of the given number.""" r = 1 while n > 0: r = r * n n = n - 1 return r
def is_square(apositiveint): """ Checks if number is a square Taken verbatim from https://stackoverflow.com/questions/2489435/how-could-i-check-if-a-number-is-a-perfect-square """ x = apositiveint // 2 seen = set([x]) while x * x != apositiveint: x = (x + (apositiveint // x)) // 2 if x in seen: return False seen.add(x) return True
def is_sorted(items): """Return a boolean indicating whether given items are in sorted order. Running time: O(n) because we are using a loop to traverse through each item in the list Memory usage: O(1) because we aren't creating any additional data structures in the function""" # Check that all adjacent items are in order, return early if so for i in range(len(items) - 1): current = items[i] nextItem = items[i + 1] if nextItem < current: return False return True
def merge_dicts(*dict_args): """ Given any number of dicts, shallow copy and merge into a new dict. If the same key appars multiple times, priority goes to key/value pairs in latter dicts. """ result = {} for dictionary in dict_args: result.update(dictionary) return result
def season_id(x): """takes in 4-digit years and returns API formatted seasonID Input Values: YYYY Used in: """ if len(str(x)) == 4: try: return "".join(["2", str(x)]) except ValueError: raise ValueError("Enter the four digit year for the first half of the desired season") else: raise ValueError("Enter the four digit year for the first half of the desired season")
def groupByReactionCenter(transformationCenter): """ returns: A Dictionary with 'reactionCenter' keys. """ centerDict = {} # extract rules with teh same reaction center for idx, rule in enumerate(transformationCenter): # print rule element = [tuple(x.elements()) for x in rule if len(x) > 0] # print element # for element in rule: # if element != set([]): if tuple(element) not in centerDict: centerDict[tuple(element)] = set([]) centerDict[tuple(element)].add(idx) return centerDict
def _get_n_top(n_top, folder): """ Get path and name of topology file :param str n_top: None or path and file name of topology file. :param str folder: None or folder containing one topology file. :return: path to the topology file :rtype: str :raises ValueError: This is raised if more than one topology is found in the given folder. """ if n_top is None: if folder is None: raise InputError("None", "Either folder or n_top must be " "specified") with cd(folder): n_top = glob.glob("*.top") if len(n_top) != 1: raise ValueError( "Found {} .top files in {}\n".format(len(n_top), folder) + "Only can deal with 1" ) else: n_top = os.path.abspath(n_top[0]) return n_top
def count_any_question_yes(group_input: str) -> int: """count questions any group member answered with yes""" return len(set("".join([line.strip() for line in group_input.split("\n")])))
def string_serializer(obj): """ Helper Function to Serialize Objects. Keeps List / Dict Structure, but will Convert everything else to String. """ if type(obj) in [list, tuple]: return list(map(string_serializer, obj)) if type(obj) == dict: copy = {} for k, v in obj.items(): copy[k] = string_serializer(v) return copy return str(obj)
def files_data_generation(candidates, namesmeasures): """Select all possible files that are related with the given measures.""" selected = [] for name in namesmeasures: sele_name = [] for i in range(len(candidates)): if name in candidates[i]: sele_name.append(candidates[i]) selected.append(sele_name) return selected
def get_release_date(data): """Get release date.""" date = data.get("physicalRelease") if not date: date = data.get("inCinemas") return date
def get_url_attrs(url, url_attr): """Return dict with attrs for url.""" if isinstance(url, str): return {url_attr: url} return url.copy()
def pole_increment(x,y,t): """This provides a small increment to a pole located mid stream For use with variable elevation data """ z = 0.0*x if t<10.0: return z # Pole 1 id = (x - 12)**2 + (y - 3)**2 < 0.4**2 z[id] += 0.1 # Pole 2 id = (x - 14)**2 + (y - 2)**2 < 0.4**2 z[id] += 0.05 return z
def extract_layout_switch(dic, default=None, do_pop=True): """ Extract the layout and/or view_id value from the given dict; if both are present but different, a ValueError is raised. Futhermore, the "layout" might be got (.getLayout) or set (.selectViewTemplate); thus, a 3-tuple ('layout_id', do_set, do_get) is returned. """ if do_pop: get = dic.pop else: get = dic.get layout = None layout_given = False set_given = 'set_layout' in dic set_layout = get('set_layout', None) get_given = 'get_layout' in dic get_layout = get('get_layout', None) keys = [] for key in ( 'layout', 'view_id', ): val = get(key, None) if val is not None: if layout is None: layout = val elif val != layout: earlier = keys[1:] and tuple(keys) or keys[0] raise ValueError('%(key)r: %(val)r conflicts ' '%(earlier)r value %(layout)r!' % locals()) keys.append(key) layout_given = True if layout is None: layout = default if set_layout is None: set_layout = bool(layout) return (layout, set_layout, get_layout)
def fix_template_expansion(content, replacements): """ fix template expansion after hook copy :param content: the duplicated hook content :param replacements: array of dictionaries cookiecutter_key => template key expanded """ for replacement in replacements: for key, to_be_replaced in replacement.items(): replacement = chr(123) + chr(123) + \ 'cookiecutter.' + key + chr(125) + chr(125) content = content.replace(to_be_replaced, replacement) return content
def _expand_xyfvc(x, y): """ Undo _redux_xyfvc() transform """ c = 3000.0 return (x+1)*c, (y+1)*c
def build_index(interactors): """ Build the index (P x D) -> N for all interactors of the current protein. """ index = dict() # P x D -> N sorted_interactors = sorted(list(interactors)) for p, d in sorted_interactors: index[(p, d)] = sorted_interactors.index((p, d)) return index
def long_hex(number): """ converts number to hex just like the inbuilt hex function but also pads zeroes such that there are always 8 hexidecimal digits """ value_hex = hex(number) # pad with 0's. use 10 instead of 8 because of 0x prefix if(len(value_hex) < 10): value_hex = value_hex[0:2] + '0'*(10-len(value_hex)) + value_hex[2:] return value_hex
def normalize(frame): """ Return normalized frame """ frame -= 128.0 frame /= 128.0 return frame
def scalarmult(scalar, list1): """scalar multiply a list""" return [scalar * elt for elt in list1]
def collapse_array_repr(value): """ The full repr representation of PVT model takes too much space to print all values inside a array. Making annoying to debug Subjects that has a PVT model on it, due to seventy-four lines with only numbers. """ import re return re.sub(r"array\(\[.*?\]\)", "array([...])", repr(value), flags=re.DOTALL)
def comment_troll_name(results): """ The same as troll_name """ name = results['by'] return name