content
stringlengths
42
6.51k
def get_tin_npi_list(decoded_messages): """Decode messages and return lists of npis and tins.""" if not decoded_messages: return (None, None) return zip(*[(provider.get('tin'), provider.get('npi')) for provider in decoded_messages])
def get_pair(value=None, val_1_default=None, val2_default=None, name="value"): """ >>> v1, v2 = get_pair(9) >>> assert v1 == 9 >>> assert v2 == 9 >>> value = (8, 1) >>> v1, v2 = get_pair(value=value) >>> assert v1 == 8 >>> assert v2 == 1 >>> v1, v2 = get_pair(val_1_default=3, val2_default=4) >>> assert v1 == 3 >>> assert v2 == 4 >>> v1, v2 = get_pair((1, 2, 3)) Traceback (most recent call last): ... ValueError: value requires a tuple of length 2 Extend a single value to a 2-element tuple with the same values or just return the tuple: value. :param value: a number or a tuple :param val_1_default: default fist value :param val2_default: default second value :param name: the name of the value :return: the 2-element tuple """ if value is None: return val_1_default, val2_default if isinstance(value, type(0.0)) or isinstance(value, type(0)): return value, value elif isinstance(value, type(())) or isinstance(value, type([])): if len(value) == 2: return value else: raise ValueError(name + " requires a tuple of length 2")
def calc_beta_mode(a: int, b: int) -> float: """ This function calculate the mode (i.e. the peak) of the beta distribution. :param a: First shape parameter of the Beta distribution :param b: Second shape parameter of the Beta distribution :return: The mode """ return (a-1)/(a+b-2)
def dict_diff(d1, d2): """ Assumes dicts of dicts or tensors and that dicts have same structure. """ out = {} for k in d1.keys(): if isinstance(d1[k], dict): out[k] = dict_diff(d1[k], d2[k]) else: out[k] = d1[k] - d2[k] return out
def intersection(collection_a, collection_b): """ The intersection between two collections considered as sets (duplicated items will be removed). """ set_a = set(collection_a) set_b = set(collection_b) return set_a.intersection(set_b)
def _to_df(point, level=0): """Transfrom point to dataframe dict layout. Args: point (dict): Point level (int, optional): Defaults to 0. Level Returns: dict """ data = { 'Label': [point['label']], 'Time': [point['difference_time']], 'Memory': [point['difference_memory']], 'Peak Memory': [point['peak_memory']], 'Level': [level], 'Type': ['point'], 'ID': [point['id']], 'Key': ['{}_{}_{}'.format(point['id'], level, point['label'])] } for msg in point['messages']: data['Label'].append(msg[1]) data['Time'].append(msg[0]) data['Memory'].append(point['difference_memory']) data['Peak Memory'].append(point['peak_memory']) data['Level'].append(level) data['Type'].append('message') data['ID'].append(point['id']) data['Key'].append('{}_{}_{}'.format(point['id'], level, msg[1])) for subpoint in point['subpoints']: _point = subpoint.to_dict() result = _to_df(_point, level+1) data['Label'].extend(result['Label']) data['Time'].extend(result['Time']) data['Memory'].extend(result['Memory']) data['Peak Memory'].extend(result['Peak Memory']) data['Level'].extend(result['Level']) data['Type'].extend(result['Type']) data['ID'].extend(result['ID']) data['Key'].extend(result['Key']) return data
def count_communication_primitives(hlo_ir: str, ignore_scalar_all_reduce: bool = False): """Count the communication primitives in a HLO IR.""" total = hlo_ir.count("channel_id") all_reduce = hlo_ir.count("all-reduce(") + hlo_ir.count("all-reduce-start(") all_gather = hlo_ir.count("all-gather(") + hlo_ir.count("all-gather-start(") reduce_scatter = hlo_ir.count("reduce-scatter(") + hlo_ir.count( "reduce-scatter-start(") all_to_all = hlo_ir.count("all-to-all(") + hlo_ir.count("all-to-all-start(") if ignore_scalar_all_reduce: # Ignore allreduce of scalar values scalar_all_reduce = 0 scalar_all_reduce += hlo_ir.count("all-reduce(f32[]") scalar_all_reduce += hlo_ir.count("all-reduce-start(f32[]") scalar_all_reduce += hlo_ir.count("all-reduce(f16[]") scalar_all_reduce += hlo_ir.count("all-reduce-start(f16[]") total -= scalar_all_reduce all_reduce -= scalar_all_reduce return total, all_reduce, all_gather, reduce_scatter, all_to_all
def image_shape_to_hw(image_shape): """Extract the height and width of the image from HW, HWC or BHWC""" img_size = (-1, -1) if len(image_shape) == 2: img_size = image_shape elif len(image_shape) == 3: img_size = image_shape[:2] elif len(image_shape) == 4: img_size = image_shape[1:3] else: ValueError('image dimensions must be 2, 3, or 4') return img_size
def get_bytes_asset_dict( data: bytes, target_location: str, target_name: str, ): """Helper function to define the necessary fields for a binary asset to be saved at a given location. Args: data: the bytes to save target_location: sub-directory to which file will be written, relative to run directory root. Defaults to empty string (i.e. root of run directory). target_name: filename to which file will be written. Defaults to None, in which case source_name is used. Returns: dict: an asset dictionary """ return { "bytes": data, "target_location": target_location, "target_name": target_name, }
def volume_dialogs(context, request, volume=None, volume_name=None, instance_name=None, landingpage=False, attach_form=None, detach_form=None, delete_form=None): """Modal dialogs for Volume landing and detail page.""" ng_attrs = {'model': 'instanceId', 'change': 'getDeviceSuggestion()'} # If landing page, build instance choices based on selected volumes availability zone (see volumes.js) if landingpage: ng_attrs['options'] = 'k as v for (k, v) in instanceChoices' return dict( volume=volume, volume_name=volume_name, instance_name=instance_name, landingpage=landingpage, attach_form=attach_form, detach_form=detach_form, delete_form=delete_form, ng_attrs=ng_attrs, )
def month_letter(i): """Represent month as an easily graspable letter (a-f, o-t).""" # return ('abc' 'def' 'opq' 'rst')[i-1] # return ('abc' 'ijk' 'pqr' 'xyz')[i-1] return ('abc' 'def' 'uvw' 'xyz')[i-1]
def package_file(*args): """Return the filename of a file within this package.""" import os return os.path.join( os.path.dirname(__file__), *args )
def is_under_replicated(num_available, expected_count, crit_threshold): """Calculates if something is under replicated :param num_available: How many things are up :param expected_count: How many things you think should be up :param crit_threshold: Int from 0-100 :returns: Tuple of (bool, ratio) """ if expected_count == 0: ratio = 100 else: ratio = (num_available / float(expected_count)) * 100 if ratio < crit_threshold: return (True, ratio) else: return (False, ratio)
def _dump_filename(config): """Give the name of the file where the results will be dumped""" return (config['out'] + '/' + config['target']['name'] + '_' + str(config['target']['spectrum']) + '_' + str(int(0.5+config['time']['tmin'])) + '_' + str(int(0.5+config['time']['tmax'])) + '_' + str(int(0.5+config['energy']['emin'])) + '_' + str(int(0.5+config['energy']['emax'])) + "_"+ config['file']['tag'] + ".results")
def int2bin(n, digits=8): """ Integer to binary string """ return "".join([str((n >> y) & 1) for y in range(digits - 1, -1, -1)])
def strip(text): """ Strings a string of surrounding whitespace. """ return text.strip()
def get_order_category(order): """Given an order string, return the category type, one of: {"MOVEMENT, "RETREATS", "DISBANDS", "BUILDS"} """ order_type = order.split()[2] if order_type in ("X", "D"): return "DISBANDS" elif order_type == "B": return "DISBANDS" elif order_type == "R": return "RETREATS" else: return "MOVEMENT"
def parse_lines(s): """ parser for line-separated string fields :s: the input string to parse, which should be of the format string 1 string 2 string 3 :returns: tuple('string 1', ...) """ return tuple(map(lambda ss: ss.strip(), s.split('\n')))
def create_non_compliance_message(violations): """Create the Non Compliance Message.""" message = "Violation - The following EC2 IAM Role is in violation of security compliance \n\n" for violation in violations: message += violation + "\n" return message
def is_leap_year(year): """ Is the current year a leap year? Args: y (int): The year you wish to check. Returns: bool: Whether the year is a leap year (True) or not (False). """ if year % 4 == 0 and (year % 100 > 0 or year % 400 == 0): return True return False
def slugify(name): """ Derpi has some special slugifying rules. """ RULES = { ":": "-colon-", ".": "-dot-", } r = name for k, v in RULES.items(): r = r.replace(k, v) return r
def sum_even_fibonacci(limit: int) -> int: """ Sums even terms in the Fibonacci sequence. :param limit: Limit for the sequence, non-inclusive. :return: Sum of even terms in the Fibonacci sequence. """ term_a = 1 term_b = 2 result = 0 while term_b < limit: if not term_b % 2: result += term_b term_a, term_b = term_b, term_a + term_b return result
def dead_check(d_age): """Deze functie controleert of de tamagotchi dood is. Dit hangt af\ van de leeftijd van de tamagotchi.""" if -1 < d_age < 7: return 6 elif d_age < 14: return 12 elif d_age < 21: return 18 elif d_age < 25: return 24 else: return 24
def human_size(sz): """ Return the size in a human readable format """ if not sz: return False units = ('bytes', 'Kb', 'Mb', 'Gb', 'Tb') if isinstance(sz, str): sz=len(sz) s, i = float(sz), 0 while s >= 1024 and i < len(units)-1: s /= 1024 i += 1 return "%0.2f %s" % (s, units[i])
def line_p(x, p): """ Straight line: :math:`a + b*x` Parameters ---------- x : float or array_like of floats independent variable p : iterable of floats parameters (`len(p)=2`) - `p[0]` = a - `p[1]` = b Returns ------- float function value(s) """ return p[0]+p[1]*x
def convert_cfg_markdown(cfg): """Converts given cfg node to markdown for tensorboard visualization. """ r = "" s = [] def helper(cfg): s_indent = [] for k, v in sorted(cfg.items()): seperator = " " attr_str = " \n{}:{}{} \n".format(str(k), seperator, str(v)) s_indent.append(attr_str) return s_indent for k, v in sorted(cfg.items()): seperator = "&nbsp;&nbsp;&nbsp;" if isinstance(v, str) else " \n" val = helper(v) val_str = "" for line in val: val_str += line attr_str = "##{}:{}{} \n".format(str(k), seperator, val_str) s.append(attr_str) for line in s: r += " \n" + line + " \n" return r
def _create_vn_str(novice_status): """Creates varsity-novice status string from the integer pseudo-enum used by the model""" if novice_status is 0: return "varsity" if novice_status is 1: return "novice" return novice_status
def check_win(guess_word): """ Returns True if the player has won. The player has won if there are no underscores left to guess. Args: guess_word: the current state of the guess word Returns: True in case of win, False otherwise. """ return not "_" in guess_word
def checkEqual(lst): """ Utility function """ return lst[1:] == lst[:-1]
def namespacer(plugin_group, plugin, name): """ * `plugin_group` - `string`. The name of the plugin directory * `plugin` - `string`. The name of the plugin * `name` - `string`. An attribute key name A helper to enforce DRY. Used in the two places that namespace attribute keys which are appended to the attributes associated with the keys in the data set built by a sofine call. """ return plugin_group + '::' + plugin + '::' + name
def pickaparc(files): """Return the aparc+aseg.mgz file""" aparcs = [] for s in files: if 'aparc+aseg.mgz' in s: aparcs.append(s) if aparcs == []: raise Exception("can't find aparc") return aparcs[0]
def title(sen): """ Turn text into title case. :param sen: Text to convert :return: Converted text """ new_text = "" for i in range(0, len(sen)): if i == 1: new_text += sen[i].upper() continue if sen[i - 1] == " ": new_text += sen[i].upper() continue new_text += sen[i].lower() return new_text
def ceildiv(a, b): """ Ceiling division, used rounding up page size numbers :param a: numerator :param b: denominator :return: integer """ return -(-a // b)
def adjust(f, i, xs): """Applies a function to the value at the given index of an array, returning a new copy of the array with the element at the given index replaced with the result of the function application""" return [f(x) if i == ind else x for ind, x in enumerate(xs)]
def num_of_sample_of_different_label(training_samples): """ :param training_samples: data of all training samples, the format are shown in load_training_data function. :return num_of_each_label: number of samples of each kind of label, a dictionary. eg: {'good': 8, 'bad': 9} """ # get all possible values of label label_type = [] # list all possible values of label shown in the training samples for each_sample in training_samples: each_label = each_sample['label'] if each_label not in label_type: label_type.append(each_label) # initialize num_of_each_label num_of_each_label = {} for label in label_type: num_of_each_label[label] = 0 # get num_of_each_label for each_sample in training_samples: label = each_sample['label'] num_of_each_label[label] += 1 return num_of_each_label
def count_letters(data): """ The following function counts the number of letters in the string by applying isalpha method which returns true when the i'th' character of the particular string is an alphabet. """ countLetters = 0 for character in data: if (character.isalpha()): # check whether a character is alphabetical countLetters += 1 return countLetters
def knownvalues(caselen): """Insert known bad values""" values = [] values.append( ("01"*(caselen * 2))[:caselen] ) values.append( ("10"*(caselen * 2))[:caselen] ) return values
def robust_l1(x): """Robust L1 metric.""" return (x**2 + 0.001**2)**0.5
def isVideo(link): """ Returns True if link ends with video suffix """ suffix = ('.mp4', '.webm') return link.lower().endswith(suffix)
def check_number_validity(number, previous_numbers): """Return true if two numbers of previous_numbers sum up exactly to number""" for candidate in previous_numbers: if number - candidate in previous_numbers: return True return False
def find_first_tag(tags, entity_type, after_index=-1): """Searches tags for entity type after given index Args: tags(list): a list of tags with entity types to be compared to entity_type entity_type(str): This is he entity type to be looking for in tags after_index(int): the start token must be greater than this. Returns: ( tag, v, confidence ): tag(str): is the tag that matched v(str): ? the word that matched? confidence(float): is a measure of accuracy. 1 is full confidence and 0 is none. """ for tag in tags: for entity in tag.get('entities'): for v, t in entity.get('data'): if t.lower() == entity_type.lower() and \ (tag.get('start_token', 0) > after_index or \ tag.get('from_context', False)): return tag, v, entity.get('confidence') return None, None, None
def logstash_processor(_, __, event_dict): """ Adds @version field for Logstash. Puts event in a 'message' field. Serializes timestamps in ISO format. """ if 'message' in event_dict and 'full_message' not in event_dict: event_dict['full_message'] = event_dict['message'] event_dict['message'] = event_dict.pop('event', '') for key, value in event_dict.items(): if hasattr(value, 'isoformat') and callable(value.isoformat): event_dict[key] = value.isoformat() + 'Z' event_dict['@version'] = 1 event_dict['_type'] = event_dict['type'] = 'feedhq' return event_dict
def verify_gender(gender_input: str) -> bool: """ A helper function to make verifying gender strings easier Parameters ---------- gender_input: str The single letter gender string to be verified. Valid inputs are: 'm', 'f', 'o' Returns ---------- bool: Returns true if the gender string is a valid gender """ return bool( gender_input.lower() == "m" or gender_input.lower() == "f" or gender_input.lower() == "o" )
def remove_leading_number(string): """ Will convert 8 Alex Ovechkin to Alex Ovechkin, or Alex Ovechkin to Alex Ovechkin :param string: a string :return: string without leading numbers """ newstring = string while newstring[0] in {'1', '2', '3', '4', '5', '6', '7', '8', '9', '0'}: newstring = newstring[1:] return newstring.strip()
def check_state(state, max_len, pad_token): """Check state and left pad or trim if necessary. Args: state (list): list of of L decoder states (in_len, dec_dim) max_len (int): maximum length authorized pad_token (int): padding token id Returns: final (list): list of L padded decoder states (1, max_len, dec_dim) """ if state is None or max_len < 1 or state[0].size(1) == max_len: return state curr_len = state[0].size(1) if curr_len > max_len: trim_val = int(state[0].size(1) - max_len) for i, s in enumerate(state): state[i] = s[:, trim_val:, :] else: layers = len(state) ddim = state[0].size(2) final_dims = (1, max_len, ddim) final = [state[0].data.new(*final_dims).fill_(pad_token) for _ in range(layers)] for i, s in enumerate(state): final[i][:, (max_len - s.size(1)) : max_len, :] = s return final return state
def simplify_title(title: str): """ Takes in an anime title and returns a simple version. """ return ''.join( i for i in title if i.isalpha() or i==' ' ).lower().strip()
def apply_column_rule(row, rule): """ Given a cell value and a rule, return a format name. See `create_cell_formats` for more detail. """ rule_type = rule['type'] if rule_type == 'all': return rule['format'] if rule_type == 'boolean': if rule['function'](row): return rule['format'] else: return None if rule_type == 'conditional': return rule['function'](row) raise ValueError(f"Column rule type <{rule['type']}> not supported")
def _format_lineno(session, line): """Helper function to format line numbers properly.""" if session == 0: return str(line) return "%s#%s" % (session, line)
def specified_users(users_arg, users): """Parse a comma-separated list of users Check that all specified users are valid, and return them as a list Parameters ---------- users_arg : str Comma-separated list of users users : container Container of valid users Returns ------- list List of specified users """ if set(users_arg.split(',')) <= users: users = users_arg.split(',') return users else: raise Exception( 'Some of the specified users have not yet been inducted into the ' 'policy. Use minduct -u to induct them before continuing.' )
def euler_problem_2(n=4000000): """ Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms. """ # note that for every triple starting with (1, 2, 3), the middle value is even def new_triple(old_triple): _left, _mid, _right = old_triple left = _mid + _right mid = left + _right right = left + mid return (left, mid, right) retval = 0 current_triple = (1, 2, 3) while True: if current_triple[1] > n: break retval += current_triple[1] current_triple = new_triple(current_triple) return retval
def getSSC(rawEMGSignal, threshold): """ Number of times the slope of the EMG signal changes sign.:: SSC = sum(f( (x[i] - x[i-1]) X (x[i] - x[i+1]))) for i = 2 --> n-1 f(x){ 1 if x >= threshold 0 otherwise } * Input: * raw EMG Signal * Output: * number of Slope Changes :param rawEMGSignal: the raw EMG signal :type rawEMGSignal: list :param threshold: value to sum / substract to the zero when evaluating the crossing. :type threshold: int :return: Number of slope's sign changes :rtype: int """ N = len(rawEMGSignal) SSC = 0 for i in range(1, N - 1): a, b, c = [rawEMGSignal[i - 1], rawEMGSignal[i], rawEMGSignal[i + 1]] if (a + b + c >= threshold * 3): # computed only if the 3 values are above the threshold if (a < b > c or a > b < c): # if there's change in the slope SSC += 1 return (SSC)
def lagrange2(N, i, x, xi): """ Program to calculate Lagrange polynomial for order N and polynomial i [0, N] at location x at given collacation points xi (not necessarily the GLL-points) """ fac = 1 for j in range(-1, N): if j != i: fac = fac * ((x - xi[j + 1]) / (xi[i + 1] - xi[j + 1])) return fac
def calc_TS(Sal): """ Calculate total Sulphur Morris, A. W., and Riley, J. P., Deep-Sea Research 13:699-705, 1966: this is .02824.*Sali./35. = .0008067.*Sali """ a, b, c = (0.14, 96.062, 1.80655) return (a / b) * (Sal / c)
def isReplacementNeeded(config): """ Check if we need to clean some junk from the source code files path :param config: configuration of the flask app :return (should_replace_path, new_src_dir) """ should_replace_path = False if 'REPLACE_KERNEL_SRC' in config: should_replace_path = config['REPLACE_KERNEL_SRC'] new_src_dir = None if 'SOURCECODE_DIR' in config: new_src_dir = config['SOURCECODE_DIR'] return (should_replace_path, new_src_dir)
def is_alphanumeric(text:str) -> bool: """ whole string is a-z,A-Z,0-9 """ # ord values [48-57, 65-90, 97-122, ] # return all((48 <= ord(c) <= 57 or 65 <= ord(c) <= 90 or 97 <= ord(c) <= 122) for c in text) for c in text: o = ord(c) if not (48 <= o <= 57 or 65 <= o <= 90 or 97 <= o <= 122): return False return True
def stringList(listItems): """Convert a list into string list""" return [str(node) for node in listItems]
def key_with_maxval(d): """Get the key with maximum value in a dictionary Paramerers: d (dictionary) """ try: v=list(d.values()) k=list(d.keys()) return k[v.index(max(v))] except: return 9999
def endpoint(line, x=0, y=0): """ >>> endpoint('nwwswee') (0, 0) """ if line == "": return x, y if line.startswith("nw"): return endpoint(line[2:], x, y - 1) if line.startswith("ne"): return endpoint(line[2:], x + 1, y - 1) if line.startswith("sw"): return endpoint(line[2:], x - 1, y + 1) if line.startswith("se"): return endpoint(line[2:], x, y + 1) if line.startswith("w"): return endpoint(line[1:], x - 1, y) if line.startswith("e"): return endpoint(line[1:], x + 1, y) else: raise Exception
def validate_input(name): """Check that the user supplied name conforms to our standards. A name should be between 1-10 characters (inclusive) and composed of all alphabetic characters. Args: name (str): The name to be validated. Returns: An error message if the name is invalid, otherwise None. """ if name is None: return "You must supply a name!" if len(name) > 10: return "Your party name is too long!" if len(name) < 1: return "Your party name must be at least 1 letter!" if not name.isalpha(): return "Your party name must consist of alphabetic characters only!"
def float_if_not_none(value): """ Returns an float(value) if the value is not None. :param value: None or a value that can be converted to an float. :return: None or float(value) """ return None if value is None else float(value)
def deepmerge(source, destination): """ Merge the first provided ``dict`` into the second. :param dict source: The ``dict`` to merge into ``destination`` :param dict destination: The ``dict`` that should get updated :rtype: dict :returns: ``destination`` modified """ for key, value in source.items(): if isinstance(value, dict): # get node or create one node = destination.setdefault(key, {}) deepmerge(value, node) else: destination[key] = value return destination
def sublime_line_endings_to_serial(text, line_endings): """ Converts the sublime text line endings to the serial line ending given :param text: the text to convert line endings for :param line_endings: the serial's line endings setting: "CR", "LF", or "CRLF" :return: the new text """ if line_endings == "CR": return text.replace("\n", "\r") if line_endings == "CRLF": return text.replace("\n", "\r\n") return text
def scrapyd_url(ip, port): """ get scrapyd url :param ip: host :param port: port :return: string """ url = 'http://{ip}:{port}'.format(ip=ip, port=port) return url
def round_base(num, base=1): """ Returns a number *num* (*int* or *float*) rounded to an arbitrary *base*. Example: .. code-block:: python round_base(7, 3) # => 6 round_base(18, 5) # => 20 round_base(18., 5) # => 20. (float) """ return num.__class__(base * round(float(num) / base))
def calc_group_rel_ratios(rel_pow_low, rel_pow_high): """ Calculates relative ratio of power within two bands. Parameters ---------- rel_pow_low : float or list of floats Low band power or list of low band powers rel_pow_high : float or list of floats High band power or list of high band powers Outputs ------- res : list of float List of relative power ratio of given frequency range. """ res = [] if len(rel_pow_low) != len(rel_pow_high): raise ValueError("Size of lists do not match.") for low, high in zip(rel_pow_low, rel_pow_high): res.append(low / high) return res
def gender_similarity_scorer(gender_1: str, gender_2: str): """Compares two gender strings, returns 0 if they match, returns penalty of -1 otherwise. Conservative assumption: if gender is nil or empty string, consider it a match against the comparator. """ if gender_1 == gender_2: return 0 elif gender_1 is None or gender_2 is None: return 0 elif gender_1 == "" or gender_2 == "": return 0 else: return -1
def rotate(arr, n): """ Right side rotation of an array by n positions """ # Storing the length to avoid recalculation arr_len = len(arr) # Adjusting the value of n to account for Right side rotations and cases where n > length of the array n = arr_len - (n % arr_len) # Splitting the array into two parts and merging them again in reverse order (Second part + First part) return arr[n:] + arr[:n]
def brackets(string: str) -> str: """Wraps a string with a pair of matching brackets.""" if len(string) != 0: return "[" + string + "]" else: return ""
def checkOutputFormat(output_len): """check if output length is word count or percentage ratio of the original text""" if float(output_len) < 1: outputFormat = "ratio" else: outputFormat = "word_count" return outputFormat
def deep_sort(obj): """Recursively sort list or dict of nested lists.""" if isinstance(obj, dict): _sorted = dict() for key in sorted(obj): _sorted[key] = deep_sort(obj[key]) elif isinstance(obj, list): new_list = [] for val in obj: new_list.append(deep_sort(val)) _sorted = sorted(new_list) else: _sorted = obj return _sorted
def flatten(cmd, path="", fc={}, sep="."): """ Convert a nested dict to a flat dict with hierarchical keys """ fcmd = fc.copy() if isinstance(cmd, dict): for k, v in cmd.items(): k = k.split(":")[1] if ":" in k else k fcmd = flatten(v, sep.join((path, k)) if path else k, fcmd) else: fcmd[path] = ('"' + cmd + '"' if isinstance(cmd, str) else str(cmd)) return (fcmd)
def str2list(str): """Convert string to a list of strings.""" return str.split('\n')
def turn(n): """Formula from WIkipedia. n could be numpy array of integers """ return (((n & -n) << 1) & n) != 0
def period_to_int(period): """ Convert time series' period from string representation to integer. :param period: Int or Str, the number of observations per cycle: 1 or "annual" for yearly data, 4 or "quarterly" for quarterly data, 7 or "daily" for daily data, 12 or "monthly" for monthly data, 24 or "hourly" for hourly data, 52 or "weekly" for weekly data. First-letter abbreviations of strings work as well ("a", "q", "d", "m", "h" and "w", respectively). Additional reference: https://robjhyndman.com/hyndsight/seasonal-periods/. :return: Int, a time series' period. """ mapper = { "annual": 1, "a": 1, "quarterly": 4, "q": 4, "daily": 7, "d": 7, "monthly": 12, "m": 12, "hourly": 24, "h": 24, "weekly": 52, "w": 52, } if period not in mapper.keys(): raise ValueError(f"{period} is not a valid value for the 'period' argument.") return mapper[period]
def frames(string): """Takes a comma separate list of frames/frame ranges, and returns a set containing those frames Example: "2,3,4-7,10" => set([2,3,4,5,6,7,10]) """ def decode_frames(string): print('s', string) if '-' in string: a = string.split('-') start, end = int(a[0]), int(a[1]) for i in range(start, end + 1): yield i else: yield int(string) framesList = string.split(',') frames = set() for strFrames in framesList: for frameNumber in decode_frames(strFrames): frames.add(frameNumber) return frames
def validate_product_data(product): """ this funtion validates the product data """ # Check for empty product_name if product['product_name'] == '': return {'warning': 'product_name is a required field'}, 400 # Check for empty product_category elif product['product_category'] == '': return {'warning': 'product_category is a required field'}, 400 # check for a valid product_name if product['product_name'].strip(' ').isdigit(): return {'warning': 'Enter a non digit product_name'}, 400 if not product["product_name"].strip(): return {"warning": "Enter a valid product_name"}, 400 # check for valid product_category if product['product_category'].strip(' ').isdigit(): return {'warning': 'Enter non digit product_category'}, 400 if not product["product_category"].strip(): return {"warning": "Enter valid product_category"}, 400 # Check for large/long inputs if len(product['product_name']) > 50: return {'warning': 'product_name is too long'}, 400
def parse_people_data(data): """ Handle :PeopleData Reduces the length of the returned data somewhat. """ lines = data.split('\n') return '. '.join(lines[:min(len(lines), 3)])
def get_ssl(database): """ Returns SSL options for the selected engine """ # Set available keys per engine if database['engine'] == 'postgresql': keys = ['sslmode', 'sslcert', 'sslkey', 'sslrootcert', 'sslcrl', 'sslcompression'] else: keys = ['ssl_ca', 'ssl_capath', 'ssl_cert', 'ssl_key', 'ssl_cipher', 'ssl_check_hostname'] # Loop thru keys ssl = {} for key in keys: value = database.get(key, None) if value is not None: ssl[key] = value return ssl
def validate(config): """ Validate the beacon configuration """ if not isinstance(config, list): return False, ("Configuration for telegram_bot_msg beacon must be a list.") _config = {} list(map(_config.update, config)) if not all( _config.get(required_config) for required_config in ["token", "accept_from"] ): return ( False, ("Not all required configuration for telegram_bot_msg are set."), ) if not isinstance(_config.get("accept_from"), list): return ( False, ( "Configuration for telegram_bot_msg, " "accept_from must be a list of usernames." ), ) return True, "Valid beacon configuration."
def shouldIgnore(s): """Should we ignore the key s? (Right now, returns true if s takes the form "__xxxxx...", prepended by two '_' chars """ return len(s) > 1 and s[:2] == "__"
def get_nx_standard_epu_mode(mode): """ Define polarization as either cir. right, point of view of source, cir. left, point of view of source, or linear. If the linear case is selected, there is an additional value in degrees for the angle (number is meaningless if circular is chosen, or may not be filled in, I do not know). """ linear_lst = [2, 3, 4, 5] if (mode == 0): return (False, 'cir. left, point of view of source') elif (mode == 1): return (False, 'cir. right, point of view of source') elif (mode in linear_lst): return (True, 'linear') else: return (False, 'UNKNOWN')
def lowercase_first_segment(apitools_collection_guess): """First segment of collection should be lowercased, handle acronyms.""" acronyms = ['HTTPS', 'HTTP', 'SSL', 'URL', 'VPN', 'TCP'] found_acronym = False for acronym in acronyms: if apitools_collection_guess.startswith(acronym): apitools_collection_guess = apitools_collection_guess.replace( acronym, acronym.lower()) found_acronym = True if not found_acronym: apitools_collection_guess = apitools_collection_guess[0].lower( ) + apitools_collection_guess[1:] return apitools_collection_guess
def endpoint_not_found(e): """ Fallback request handler """ return "Endpoint not found.", 404
def nag_function_is_output(name): """ Check wether a NAG function name is of type output """ if name[0:1] == 'o': return True else: return False
def flatten_dictionary(dictionary): """ Input: a request's JSON dictionary output with nested dictionary Output: a flattened dictionary (format: key1.key2 = value2) """ flattenedDictionary = dict() for key, value in dictionary.items(): if isinstance(value, dict): for subkey, subvalue in value.items(): flattenedDictionary[key + '.' + subkey] = subvalue else: flattenedDictionary[key] = value return flattenedDictionary
def padBlock(block, dur): """Adjusts the block for the proper timing interval""" nBlock = [] for i, b in enumerate(block): if i == 0: nBlock.append(b) else: j = i - 1 prev = block[j] ev = b + dur + prev nBlock.append(ev) return nBlock
def qmag2(q): """ Returns the euclidean length or magnitude of quaternion q squared """ return (sum(e*e for e in q))
def attr_is_not_inherited(type_, attr): """ returns True if type_'s attr is not inherited from any of its base classes """ bases = type_.__mro__[1:] return getattr(type_, attr) not in (getattr(base, attr, None) for base in bases)
def traverse_table(time_step, beam_indx, back_pointers, elems_table, format_func=None): """ Walks back to construct the full hypothesis by traversing the passed table. :param time_step: the last time-step of the best candidate :param beam_indx: the beam index of the best candidate in the last time-step :param back_pointers: array [steps] :param elems_table: array of elements to traverse [steps, elements_count], e.g. vocabulary word ids :param format_func: a function to format elements :return: hypothesis list of the size 'time_step' """ hyp = [] for j in range(len(back_pointers[:time_step]) - 1, -1, -1): elem = elems_table[j + 1][beam_indx] elem = elem if format_func is None else format_func(elem) hyp.append(elem) beam_indx = back_pointers[j][beam_indx] elem = elems_table[0][beam_indx] elem = elem if format_func is None else format_func(elem) hyp.append(elem) return hyp[::-1]
def sanitize(string): """removes the added identification prefix 'caffe_layer_' """ return int(string[12:])
def api_file_url(url_or_id): """Converts the Google Drive file ID or "Get link" URL to an API URL. from https://drive.google.com/file/d/<ID>/view?usp=sharing to https://www.googleapis.com/drive/v3/files/<ID>?alt=media """ if '/' in url_or_id: gid = url_or_id.split('/')[-2] else: gid = url_or_id return f"https://www.googleapis.com/drive/v3/files/{gid}?alt=media"
def rename_to_text(file_path): """ Appends a .txt to all files run since some output files do not have an extension :param file_path: input file path :return: .txt appended to end of file name """ import os file = file_path.split('/')[-1] if file.endswith('.txt') is False: new_file_name = file_path+'.txt' os.rename(file_path, new_file_name) file_path = new_file_name filename = file return file_path, filename
def binding_string_to_dict(raw_value): """Convert comma-delimted kwargs argument into a normalized dictionary. Args: raw_value: [string] Comma-delimited key=value bindings. """ kwargs = {} if raw_value: for binding in raw_value.split(','): name, value = binding.split('=') if value.lower() == 'true': value = True elif value.lower() == 'false': value = False elif value.isdigit(): value = int(value) kwargs[name] = value return kwargs
def refMEMReplacements(tex): """ Searches through the tex for any reference that specifically points to the memory model and replaces that sentence with a hard-coded string. Processing the section that was in the original text is not an option because the reference the Latex file does not apply to the man pages. """ if (tex.find("\\ref{subsec:memory_model}") != -1): while(tex.find("\\ref{subsec:memory_model}") != -1): index = tex.find("\\ref{subsec:memory_model}") enter = 0 last = 0 while (enter < index): last = enter enter = tex.find("\n", enter + 1) period = tex.find(".", index) sentence = tex[last + 1: period + 1] tex = tex[:last + 1] + \ "Please refer to the subsection on the Memory Model for the" + \ " definition of the term \"remotely accessible\"." + \ tex[period + 1:] return tex
def merge(*objs): """ Create a ``dict`` merged with the key-values from the provided dictionaries such that each next dictionary extends the previous results. Examples: >>> item = merge({'a': 0}, {'b': 1}, {'b': 2, 'c': 3}, {'a': 1}) >>> item == {'a': 1, 'b': 2, 'c': 3} True Args: *objs (dict): Dictionary sources. Returns: dict """ result = {} for obj in objs: result.update(obj) return result
def sort_priority_use_nonlocal(numbers, group): """ add nonlocal keyword to assign outter value :param numbers: :param group: :return: """ found = False def helper(x): if x in group: nonlocal found found = True return 0, x return 1, x numbers.sort(key=helper) return found
def flatten(l): """ Flattens a list. Written by Bearophile as published on the www.python.org newsgroups. Pulled into Topographica 3/5/2005. """ if type(l) != list: return l else: result = [] stack = [] stack.append((l,0)) while len(stack) != 0: sequence, j = stack.pop(-1) while j < len(sequence): if type(sequence[j]) != list: k, j, lens = j, j+1, len(sequence) while j < len(sequence) and \ (type(sequence[j]) != list): j += 1 result.extend(sequence[k:j]) else: stack.append((sequence, j+1)) sequence, j = sequence[j], 0 return result
def string_to_boolean(value, true_values, false_values): """Find value in lists and return boolean, else returns the original value string. """ clean_value = value.strip().lower() if clean_value in true_values: return True if clean_value in false_values: return False return value
def get_dimensions(line): """ Parse and extract X, Y and Z dimensions from string Parameters ---------- full_prefix: string shot full prefix (e.g R8O3IL08C25_Y10Z15) returns: Tuple of (bool, string, string) True if ok, False and file name and SHA1 if signature mismatch :param line: line contains x, y, z dimensions """ split = line.split(" ") split = [x for x in split if x] # remove empty lines nx = int(split[0]) ny = int(split[1]) nz = int(split[2]) return (nx, ny, nz)
def encodeStop(sreg): """final step: returns the BCH code from the shift register state""" sreg ^= 0xFF # invert the shift register state sreg <<= 1 # make it the 7 most sign. bits return (sreg & 0xFE) # filter the 7 most sign bits