content
stringlengths
42
6.51k
def _get_list_feat_names(idx_feat_dict, num_pair): """Creates flattened list of (repeated) feature names. The indexing corresponds with the flattened list of T values and the flattened list of p-values obtained from _get_list_signif_scores(). Arguments: idx_feat_dict: {int: string} dictionary mapping feature indices to faetures num_class: int number of classes Returns: list_feat_names: [string] list of feature names with length num_feature * num_pair """ num_feature = len(idx_feat_dict) return [idx_feat_dict[feat_idx] for feat_idx in range(num_feature)] \ * num_pair
def _number_channels(rgb: bool) -> int: """Determines the number of channels corresponding to a RGB flag.""" if rgb: return 3 else: return 1
def vector_add(vec1, vec2): """ Returns the vector addition of the two vectors""" (px1, py1), (px2, py2) = vec1, vec2 return (px1 + px2, py1 + py2)
def parse_size(s): """ s: <number>[<k|m|g|t>] Returns the number of bytes. """ try: if s[-1].isdigit(): return int(s) n, unit = float(s[0:-1]), s[-1].lower() if unit == 'k': return int(n * 1024) if unit == 'm': return int(n * 1024 * 1024) if unit == 'g': return int(n * 1024 * 1024 * 1024) if unit == 't': return int(n * 1024 * 1024 * 1024 * 1024) except (IndexError, ValueError): pass # continue to next line and throw error raise ValueError('Invalid size: %s, expected <number>[<k|m|g|t>]' % s)
def split(text, delimiter=','): """ Split a comma-separated list of strings. :param text: The text to split (a string). :param delimiter: The delimiter to split on (a string). :returns: A list of zero or more nonempty strings. Here's the default behavior of Python's built in :func:`str.split()` function: >>> 'foo,bar, baz,'.split(',') ['foo', 'bar', ' baz', ''] In contrast here's the default behavior of the :func:`split()` function: >>> from humanfriendly.text import split >>> split('foo,bar, baz,') ['foo', 'bar', 'baz'] Here is an example that parses a nested data structure (a mapping of logging level names to one or more styles per level) that's encoded in a string so it can be set as an environment variable: >>> from pprint import pprint >>> encoded_data = 'debug=green;warning=yellow;error=red;critical=red,bold' >>> parsed_data = dict((k, split(v, ',')) for k, v in (split(kv, '=') for kv in split(encoded_data, ';'))) >>> pprint(parsed_data) {'debug': ['green'], 'warning': ['yellow'], 'error': ['red'], 'critical': ['red', 'bold']} """ return [token.strip() for token in text.split(delimiter) if token and not token.isspace()]
def Precipitation(prec, temp, tt, rfcf, sfcf): """ ======================================================== Precipitation (temp, tt, prec, rfcf, sfcf) ======================================================== Precipitaiton routine of the HBV96 model. If temperature is lower than TT [degree C], all the precipitation is considered as snow. If the temperature is higher than tt, all the precipitation is considered as rainfall. Parameters ---------- temp : float Measured temperature [C] tt : float Lower temperature treshold [C] prec : float Precipitation [mm] rfcf : float Rainfall corrector factor sfcf : float Snowfall corrector factor Returns ------- rf : float Rainfall [mm] sf : float Snowfall [mm] """ if temp <= tt: # if temp <= lower temp threshold rf = 0.0 #no rainfall all the precipitation will convert into snowfall sf = prec*sfcf else : #temp >= tt: # if temp > upper threshold rf = prec*rfcf # no snowfall all the precipitation becomes rainfall sf = 0.0 return rf, sf
def get_key_value_from_line( string ): """Takes a string, splits by the FIRST equal sign and sets it equal to key, value aws_session_token=1234ASDF=B returns ("aws_session_token", "1234ASDF=B") """ split_by_equal = string.split('=') key = split_by_equal[0] if len(split_by_equal) > 1: value = '='.join( split_by_equal[1:] ) else: value = None return key, value
def is_archive(filepath): """Determines whether the given filepath has an archive extension from the following list: `.zip`, `.rar`, `.tar`, `.tar.gz`, `.tgz`, `.tar.bz`, `.tbz`. Args: filepath: a filepath Returns: True/False """ return filepath.endswith( (".zip", ".rar", ".tar", ".tar.gz", ".tgz", ".tar.bz", ".tbz") )
def helper(x): """prints help""" print(x) return x
def get_input_file_dictionary(indata): """ Return an input file dictionary. Format: {'guid': 'pfn', ..} Normally use_turl would be set to True if direct access is used. :param indata: list of FileSpec objects. :return: file dictionary. """ ret = {} for fspec in indata: ret[fspec.guid] = fspec.turl if fspec.status == 'remote_io' else fspec.lfn # correction for ND and mv # in any case use the lfn instead of pfn since there are trf's that have problems with pfn's if not ret[fspec.guid]: # this case never works (turl/lfn is always non empty), deprecated code? ret[fspec.guid] = fspec.lfn return ret
def get_log(name=None): """Return a console logger. Output may be sent to the logger using the `debug`, `info`, `warning`, `error` and `critical` methods. Parameters ---------- name : str Name of the log. References ---------- .. [1] Logging facility for Python, http://docs.python.org/library/logging.html """ import logging if name is None: name = 'skimage' else: name = 'skimage.' + name log = logging.getLogger(name) return log
def normalize(value): """ Function normalizes value by replacing periods, commas, semi-colons, and colons. :param value: Raw value :rtype: String with punctuations removed """ if value: return value.replace('.', '').strip(',:/; ')
def limited(x, z, limit): """Logic that is common to invert and change.""" if x != 0: return min(z, limit) else: return limit
def cipher(text, shift, encrypt=True): """ Encrypts a given input alphabetical text string. Parameters ---------- text : str This is the input text data sent to be ciphered (should be English). shift : int This is the ficed number that each letter is replaced by a letter some fixed number of positions down the alphabet. It can be any integers, both positive and negative. encrypt : bool If encrypt is True (default value), each alphabet character will be replaced by another alphabet character; the extent of this shift will be dependent on the shift parameter. If encrypt is False, a similar process will happen, and the extent is also dependent on shift. However, when encrypt is False, it also enables decryption, if some output generated by the cipher function is re-entered as input into the cipher function. Returns ------- str The string after ciphered is the output. Examples -------- >>> from cipher_tz2372 import cipher_tz2372 >>> cipher_tz2372.cipher('abc', 1) #encrypt is True by default 'bcd' >>> from cipher_tz2372 import cipher_tz2372 >>> cipher_tz2372.cipher('bcd', -1) #encrypt is True by default 'abc' """ alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' new_text = '' for c in text: index = alphabet.find(c) if index == -1: new_text += c else: new_index = index + shift if encrypt == True else index - shift new_index %= len(alphabet) new_text += alphabet[new_index:new_index+1] return new_text
def add_dicts(*args, **kwargs): """ Utility to "add" together zero or more dicts passed in as positional arguments with kwargs. The positional argument dicts, if present, are not mutated. """ result = {} for d in args: result.update(d) result.update(kwargs) return result
def getDatasetName(token, channel_list, colors, slice_type): """Return a dataset name given the token, channel, colors and slice_type""" if colors is not None: channel_list = ["{}:{}".format(a,b) for a,b in zip(channel_list, colors)] return "{}-{}-{}".format(token, ','.join(channel_list), slice_type)
def format_tune_scores(results): """ Creates a tune_results dict from the output of get_tune_output_dol applied to the results output by fit_and_score. This creates the proper score names e.g. train_score, test_score, etc. It also formats the tune parameter list. Parameters ---------- results: dict of lists The dict of list version of the results from fit_and_score() Output ------ results; dict of lists The formated results. """ new_results = {} if 'params' in results: new_results['params'] = results.pop('params') kinds = ['train', 'test', 'fit'] for kind in kinds: for metric, value in results[kind].items(): new_key = '{}_{}'.format(kind, metric) new_results[new_key] = value return new_results
def galois_multiply(a, b): """Galois Field multiplicaiton for AES""" p = 0 while b: if b & 1: p ^= a a <<= 1 if a & 0x100: a ^= 0x1b b >>= 1 return p & 0xff
def __insert_color(txt,s,c): """insert HTML span style into txt. The span will change the color of the text located between s[0] and s[1]: txt: txt to be modified s: span of where to insert tag c: color to set the span to""" return txt[:s[0]]+'<span style="color: {0};">'.format(c)+\ txt[s[0]:s[1]]+'</span>'+txt[s[1]:]
def _UTMLetterDesignator(lat): """ This routine determines the correct UTM letter designator for the given latitude returns 'Z' if latitude is outside the UTM limits of 84N to 80S. Written by Chuck Gantz- chuck.gantz@globalstar.com """ if 84 >= lat >= 72: return 'X' elif 72 > lat >= 64: return 'W' elif 64 > lat >= 56: return 'V' elif 56 > lat >= 48: return 'U' elif 48 > lat >= 40: return 'T' elif 40 > lat >= 32: return 'S' elif 32 > lat >= 24: return 'R' elif 24 > lat >= 16: return 'Q' elif 16 > lat >= 8: return 'P' elif 8 > lat >= 0: return 'N' elif 0 > lat >= -8: return 'M' elif -8> lat >= -16: return 'L' elif -16 > lat >= -24: return 'K' elif -24 > lat >= -32: return 'J' elif -32 > lat >= -40: return 'H' elif -40 > lat >= -48: return 'G' elif -48 > lat >= -56: return 'F' elif -56 > lat >= -64: return 'E' elif -64 > lat >= -72: return 'D' elif -72 > lat >= -80: return 'C' else: return 'Z' # if the latitude is outside the UTM limits
def lcm(x, y): """ Compute the least common multiple of x and y. This function is used for running statistics. """ greater = max(x, y) while True: if (greater % x == 0) and (greater % y == 0): lcm = greater break greater += 1 return lcm
def _default_function(l, default, i): """ EXAMPLES:: sage: from sage.combinat.integer_vector import _default_function sage: import functools sage: f = functools.partial(_default_function, [1,2,3], 99) sage: f(-1) 99 sage: f(0) 1 sage: f(1) 2 sage: f(2) 3 sage: f(3) 99 """ try: if i < 0: return default return l[i] except IndexError: return default
def prime_sampler_state(n, exclude): """ Initialize state to be used in fast sampler. Helps ensure excluded items are never sampled by placing them outside of sampling region. """ # initialize typed numba dicts state = {n: n} state.pop(n) track = {n: n} track.pop(n) n_pos = n - len(state) - 1 # reindex excluded items, placing them in the end for i, item in enumerate(exclude): pos = n_pos - i x = track.get(item, item) t = state.get(pos, pos) state[x] = t track[t] = x state.pop(pos, n) track.pop(item, n) return state
def translate(num_list, transl_dict): """ Translates integer list to number word list (no error handling!) Args: num_list: list with interger items. transl_dict: dictionary with integer keys and number word values. Returns: list of strings which are the translated numbers into words. """ return [transl_dict[item] for item in num_list]
def snake_to_camel_case(snake_text): """ Converts snake case text into camel case test_path --> testPath :param snake_text:str :return: str """ components = snake_text.split('_') # We capitalize the first letter of each component except the first one with # the 'title' method and join them together. return components[0] + ''.join(x.title() for x in components[1:])
def list_rar (archive, compression, cmd, verbosity, interactive): """List a RAR archive.""" cmdlist = [cmd] if verbosity > 1: cmdlist.append('v') else: cmdlist.append('l') if not interactive: cmdlist.extend(['-p-', '-y']) cmdlist.extend(['--', archive]) return cmdlist
def get_free_residents(resident_prefs, matching): """ Return a list of all residents who are currently unmatched but have a non-empty preference list. """ return [ resident for resident in resident_prefs if resident_prefs[resident] and not any([resident in match for match in matching.values()]) ]
def qualify_raw_term(term): """Does some qualification on the unprocessed term. """ try: if "__" in term: return False if "--" in term: return False except Exception: return False return True
def ConfigName(deployment, name): """Returns the name of the config. Args: deployment: the name of the deployment. name: the "tag" used to differentiate this config from others. Returns: The name of the config. """ return "{}-config-{}".format(deployment, name)
def sem(e): """Church numbers semantics""" return e(lambda x: x + 1)(0)
def ishappy(n): """ Takes an input of a number to check if it is happy Returns bool values True for a happy number and False for unhappy numbers """ cache=[1, 7, 10, 13, 19, 23, 28, 31, 32, 44, 49, 68, 70, 79, 82, 86, 91, 94, 97, 100, 103, 109, 129, 130, 133, 139, 167, 176, 188, 190, 192, 193, 203, 208, 219, 226, 230, 236, 239, 262, 263, 280, 291, 293, 301, 302, 310, 313, 319, 320, 326, 329, 331, 338, 356, 362, 365, 367, 368, 376, 379, 383, 386, 391, 392, 397, 404, 409, 440, 446, 464, 469, 478, 487, 490, 496, 536, 556, 563, 565, 566, 608, 617, 622, 623, 632, 635, 637, 638, 644, 649, 653, 655, 656, 665, 671, 673, 680, 683, 694, 700, 709, 716, 736, 739, 748, 761, 763, 784, 790, 793, 802, 806, 818, 820, 833, 836, 847, 860, 863, 874, 881, 888, 899, 901, 904, 907, 910, 912, 913, 921, 923, 931, 932, 937, 940, 946, 964, 970, 973, 989, 998, 1000] #static cache used as a lookup table # It was found that a dynamically appended list of happy numbers to # check against was much slower (about 3-5 times slower) why the first 1000? because you need a 13 digit number # (9,999,999,999,996) to get over 1000 when you apply the algorithm seeing as performing the algorithm on the # first 10^11 numbers would take about 25 hours it seems like a good break point #This while loop will perform the happy number algorithm while True: n = sum(int(i)**2 for i in str(n)) if n in cache: return True elif n>1000: #if the algorithm spits out a number larger than 1000 it basically performs it again to get below 1000 and therefore uses the lookup table n = sum(int(i) ** 2 for i in str(n)) else: return False
def josephus_survivor(n, k): """ Finds the last survivor given an integer of the sum of people and an integer for the amount of steps to take. :param n: an integer of people. :param k: an integer of steps. :return: the lone survivor. """ r = 0 for x in range(1, n + 1): r = (r + k) % x return r + 1
def find_journal(issn, journal_dictionary): """ Given an issn, and a journal_dictinary, find the journal in VIVO with that UFID. Return True and URI if found. Return False and None if not found """ try: uri = journal_dictionary[issn] found = True except: uri = None found = False return [found, uri]
def edges_intersect(a1, a2, b1, b2): """ The algorithm for determining whether two lines intersect or not: https://www.geometrictools.com/Documentation/IntersectionLine2Circle2.pdf This one is the same, with visualization: http://geomalgorithms.com/a05-_intersect-1.html a and b are vector representation of the received edges and u is the vector from point a1 to point b1 """ a = {'x': a2[0] - a1[0], 'y': a2[1] - a1[1]} b = {'x': b2[0] - b1[0], 'y': b2[1] - b1[1]} u = {'x': a1[0] - b1[0], 'y': a1[1] - b1[1]} a_dot_b = (b['y'] * a['x']) - (b['x'] * a['y']) if a_dot_b == 0: return False b_dot_u = (b['x'] * u['y']) - (b['y'] * u['x']) a_dot_u = (a['x'] * u['y']) - (a['y'] * u['x']) ua = b_dot_u / a_dot_b ub = a_dot_u / a_dot_b return 0 <= ua <= 1 and 0 <= ub <= 1
def standard_time_display(cur_time): """Covert time with second format into hour:minute:second format. Inputs: cur_time: current time(s), type(int) Returns: stand_time: standard time(h:m:s), type(char) """ assert type(cur_time) is float # ms if cur_time < 1: msecond = round(cur_time * 1000) stand_time = '{}ms'.format(msecond) length = 4 # >=1min elif 60 <= cur_time < 3600: second = round(cur_time % 60) minute = round(cur_time / 60) stand_time = '{:02d}:{:02d}'.format(minute, second) length = 5 # >=1h elif 3600 <= cur_time < 86400: second = round((cur_time % 3600) % 60) minute = round((cur_time % 3600) / 60) hour = round(cur_time / 3600) stand_time = '{:02d}:{:02d}:{:02d}'.format(hour, minute, second) length = 8 # >=1day elif cur_time >= 86400: minute = round(((cur_time % 86400) % 3600) / 60) hour = round((cur_time % 86400) / 3600) day = round(cur_time / 86400) stand_time = '{:02d}d{:02d}h{:02d}min'.format(day, hour, minute) length = 11 # 1s>= and <1min else: second = round(cur_time) stand_time = '00:{:02d}'.format(second) length = 5 return stand_time, length
def isNumber(s): """Checks if s is number""" if s is None: return False try: float(s) return True except ValueError: return False
def not_found_pretty(needle, lines): """ Returns a pretty-print assert message. """ return 'Not found in settings: %(needle)s\n' \ '---------------\n' \ '%(lines)s' % { 'needle': needle, 'lines': '\n'.join(lines) }
def merge_dicts(x, y): """A function to merge two dictionaries, making it easier for us to make modality specific queries for dwi images (since they have variable extensions due to having an nii.gz, bval, and bvec file) Parameters ---------- x : dict dictionary you want merged with y y : dict dictionary you want merged with x Returns ------- dict combined dictionary with {x content,y content} """ z = x.copy() z.update(y) return z
def add_alpha_to_rgb(color_code: str) -> str: """ @brief Add the alpha part to a valid RGB color code (#RGB, #RRGGBB, #RRGGBBAA) @param color_code The color code @return The color code in the form of #RRGGBBAA """ if not color_code: return "" rgb = color_code[1:9] # strip "#" and possible extra chars # RGB to RRGGBB if len(rgb) == 3: rgb = rgb[0] * 2 + rgb[1] * 2 + rgb[2] * 2 return "#" + (rgb + "ff")[:8].lower()
def FormatToMinDP(val, max_dp): """ Format val as a string with the minimum number of required decimal places, up to a maximum of max_dp. """ num_dp = 0 while True: pow = -1 * num_dp if val % (10 ** pow) == 0.0 or num_dp == max_dp: break num_dp += 1 return "{{0:.{0}f}}".format(num_dp).format(val)
def _inject_args(sig, types): """ A function to inject arguments manually into a method signature before it's been parsed. If using keyword arguments use 'kw=type' instead in the types array. sig the string signature types a list of types to be inserted Returns the altered signature. """ if '(' in sig: parts = sig.split('(') sig = '{}({}{}{}'.format( parts[0], ', '.join(types), (', ' if parts[1].index(')') > 0 else ''), parts[1]) else: sig = '{}({})'.format(sig, ', '.join(types)) return sig
def _make_memoryview(size): """ Create a new ``memoryview`` wrapped around a ``bytearray`` of the given size. """ return memoryview(bytearray(size))
def requeue_list(obj, idx): """ Returns the element at index after moving it to the beginning of the queue. :param obj: list :param idx: index :return: list """ obj.insert(0, obj.pop(idx)) return obj
def is_single_bool(val): """ Checks whether a variable is a boolean. Parameters ---------- val The variable to check. Returns ------- bool True if the variable is a boolean. Otherwise False. """ return type(val) == type(True)
def list_of_ints(st1, blk): """function to process a comma seperated list of ints.""" st1 = st1.split(',') return st1
def get_wiki_arxiv_url(wiki_dump_url, href): """Return a full URL from the href of a .bz2 archive.""" return '{}/{}'.format(wiki_dump_url, href)
def clean_ingredients(dish_name, dish_ingredients): """ :param dish_name: str :param dish_ingredients: list :return: tuple of (dish_name, ingredient set) This function should return a `tuple` with the name of the dish as the first item, followed by the de-duped `set` of ingredients as the second item. """ ingredient_set = set(dish_ingredients) mydish = (dish_name, ingredient_set) return mydish
def get_last_names(_lst): """Return list of creator last names""" names = [x.split(', ') for x in _lst] _res = [n[0] for n in names] return _res
def list2dict(data): """ convert list to dict :param data: :return: """ data = {data[i]: i for i in range(len(data))} return data
def getPerson(replace=None, delete=None): """Generate valid Person.""" return { 'name': 'Teppo', 'email': 'email@example.com', 'identifier': 'person_identifier' }
def getChars( data ): """Generates a set of all characters in the data set.""" chars = set([]) for i in range( len(data) ): chars.update( set( data["text"][i] ) ) return chars
def _ag_checksum(data): """ Compute a telegram checksum. """ sum = 0 for c in data: sum ^= c return sum
def split_era_year(galatic_date): """Separate the Galatic date into era (e.g., BBY, ABY) and year. Parameters: galatic_date (str): Galatic year and era (e.g., 19BBY) Returns: tuple: era, year """ return galatic_date[-3:], float(galatic_date[:-3])
def template_email_link(text_body, html_body, attachment_html, link): """ Template text and html body text assumes that static template placeholder {{link}} exists in attachment link Args: textBody: plain text version of email htmlBody: html version of email attachmentHtml: surrounding html to use for S3 link link: file url, if None then replace template string with '' Returns: (text_body, html_body) tuple of formatted text """ if link: text_body += '\n\n' + link html_body += attachment_html.replace('{{link}}', link) return (text_body, html_body)
def ship_size(data, coordinates): """ (data, tuple) -> (tuple) A function based on read data and cell coordinates (for example ("J", 1) or ("A", 10)) defines the size of the ship, part of which is in this cell. """ size = 1 let_num = {"A": 0, "B": 1, "C": 2, "D": 3, "E": 4, "F": 5, "G": 6, "H": 7, "I": 8, "J": 9} try: assert (0 <= int(coordinates[1]) - 1 <= 9) assert (coordinates[0] in let_num) except AssertionError: return 0, 0 # Checks ship vertically if (0 <= int(coordinates[1]) <= 9) and data[int(coordinates[1])][let_num[coordinates[0]]] == "*": size += 1 # Size = 2 if (0 <= int(coordinates[1]+1) <= 9) and data[int(coordinates[1]+1)][let_num[coordinates[0]]] == "*": size += 1 # Size = 3 if (0 <= int(coordinates[1]+2) <= 9) and data[int(coordinates[1]+2)][let_num[coordinates[0]]] == "*": size += 1 # Size = 4 if (0 <= int(coordinates[1]-2) <= 9) and data[int(coordinates[1]-2)][let_num[coordinates[0]]] == "*": size += 1 # Size = 2 if (0 <= int(coordinates[1]-3) <= 9) and data[int(coordinates[1]-3)][let_num[coordinates[0]]] == "*": size += 1 # Size = 3 if (0 <= int(coordinates[1]-4) <= 9) and data[int(coordinates[1]-4)][let_num[coordinates[0]]] == "*": size += 1 # Size = 4 if size > 1: return 1, size # Checks ship horizontally if (0 <= let_num[coordinates[0]]+1 <= 9) and data[int(coordinates[1]-1)][let_num[coordinates[0]]+1] == "*": size += 1 # Size = 2 if (0 <= let_num[coordinates[0]]+2 <= 9) and data[int(coordinates[1]-1)][let_num[coordinates[0]]+2] == "*": size += 1 # Size = 3 if (0 <= let_num[coordinates[0]]+3 <= 9) and data[int(coordinates[1]-1)][let_num[coordinates[0]]+3] == "*": size += 1 # Size = 4 if (0 <= let_num[coordinates[0]]-1 <= 9) and data[int(coordinates[1]-1)][let_num[coordinates[0]]-1] == "*": size += 1 # Size = 2 if (0 <= let_num[coordinates[0]]-2 <= 9) and data[int(coordinates[1]-1)][let_num[coordinates[0]]-2] == "*": size += 1 # Size = 3 if (0 <= let_num[coordinates[0]]-3 <= 9) and data[int(coordinates[1]-1)][let_num[coordinates[0]]-3] == "*": size += 1 # Size = 4 if size > 1: return size, 1 return 1, 1
def _find_slice_interval(f, r, x, u, D, w=1.): """Given a point u between 0 and f(x), returns an approximated interval under f(x) at height u. """ a = x - r*w b = x + (1-r)*w if a < D[0]: a = D[0] else: while f(a) > u: a -= w if a < D[0]: a = D[0] break if b > D[1]: b = D[1] else: while f(b) > u: b += w if b > D[1]: b = D[1] break return a, b
def parse_dict(input_data): """Return a rules dict of the format: { 'light red': [(1, 'bright white'), (2, 'muted yellow')], 'dark orange': [(3, bright white), (4, muted yellow)], 'faded blue': [(0, 'bags')] } """ bags = dict() for line in input_data.split('\n'): outer, inner = line.strip().split(' bags contain ') inner = [i.split(' ') for i in inner.split(", ")] if 'no' in inner[0]: bags[outer] = [(0, 'bags')] else: bags[outer] = [(int(i[0]), ' '.join(i[1:3])) for i in inner] return bags
def shouldProcess(app): """ Check if an app should be downloaded and analyzed. """ if not 'internet' in app: return False if not 'unchecked' in app: return False return app['internet'] and app['unchecked'] and app['price'] == u'Free'
def get_repeated_labels(labels): """Get duplicate labels.""" seen = set() rep = [] for x in labels: if x in seen: rep.append(x) seen.add(x) return rep
def gcd(a, b): """ @brief Greatest common divisor: O(log(a + b)) """ if a % b == 0: return b else: return gcd(b, a % b)
def _cmp(a, b): """ Port of Python 2's cmp function. """ # https://docs.python.org/3.0/whatsnew/3.0.html#ordering-comparisons return (a > b) - (a < b)
def IsOwner(unused_action, user, entity): """An authorized_function that checks to see if user is an entity owner.""" return hasattr(entity, 'owner') and entity.owner == user.user_id()
def flatten_dict(dct, old_k=str()): """Take nested dictionaries, combine it into one dictionary :param dct: A dict :param old_k: Previous key, for reduction :returns: A dict, no nested dicts within """ out = dict() for k, v in dct.items(): new_k = "{}.{}".format(old_k, k) if isinstance(v, dict): out = {**out, **flatten_dict(v, new_k)} else: out[new_k.strip(".")] = v return out
def gt(value, arg): """Returns a boolean of whether the value is greater than the argument.""" return value > int(arg)
def hamilton_product(q1, q2): """ Performs composition of two quaternions by Hamilton product. This is equivalent of a rotation descried by quaternion_1 (q1), followed by quaternion_2 (q2). https://en.wikipedia.org/wiki/Quaternion#Hamilton_product :param q1: 4-item iterable representing unit quaternion. :param q2: 4-item iterable representing unit quaternion. :return: Resulting quaternion. """ a1 = q1[0] b1 = q1[1] c1 = q1[2] d1 = q1[3] a2 = q2[0] b2 = q2[1] c2 = q2[2] d2 = q2[3] return a1 * a2 - b1 * b2 - c1 * c2 - d1 * d2, \ a1 * b2 + b1 * a2 + c1 * d2 - d1 * c2, \ a1 * c2 - b1 * d2 + c1 * a2 + d1 * b2, \ a1 * b2 + b1 * c2 - c1 * b2 + d1 * a2
def _avg(count, avg, new_num): """Incremental average. :param count: int -- The previous total. :param avg: float -- The previous average. :param new_num: int|float -- The new number. :return: float -- The new average. """ if not count: return float(new_num) return (count * avg + new_num) / (count + 1.0)
def create_ordered_list(data_dict, items): """Creates an ordered list from a dictionary. Each dictionary key + value is added to a list, as a nested list. The position of the nested item is determined by the position of the key value in the items list. The returned list is the dictionary ordered on the keys. Args: data_dict (dict): Dictonary to be converted to an ordered list. items (list) List of dictionary keys in the desired order. Returns: results (list): Dictionary keys and values in an ordered list. """ results = [] for item in items: if item in data_dict: this_item = [] this_item.append(item) # Add key this_item.append(data_dict[item]) # Add value results.append(this_item) return results
def isint(value): """ Check if value can be converted to int :param value: input value :return: True/False """ try: int(value) return True except ValueError: return False
def numel(shape): """Obtain total number of elements from a tensor (ndarray) shape. Args: shape: A list or tuple represenitng a tensor (ndarray) shape. """ output = 1 for dim in shape: output *= dim return output
def get_palette(num_cls): """ Returns the color map for visualizing the segmentation mask. Args: num_cls: Number of classes Returns: The color map """ n = num_cls palette = [0] * (n * 3) for j in range(0, n): lab = j palette[j * 3 + 0] = 0 palette[j * 3 + 1] = 0 palette[j * 3 + 2] = 0 i = 0 while lab: palette[j * 3 + 0] |= (((lab >> 0) & 1) << (7 - i)) palette[j * 3 + 1] |= (((lab >> 1) & 1) << (7 - i)) palette[j * 3 + 2] |= (((lab >> 2) & 1) << (7 - i)) i += 1 lab >>= 3 return palette
def check_vertical_win_conditions(board, player): """returns True if the given player has a vertical winning triple and False otherwise.""" # Your code starts here. for col_index in range(len(board[0])): char_count = 0 for row_index in range(len(board)): if board[row_index][col_index] == player: char_count += 1 if char_count == len(board): return True return False # Your code ends here.
def eps2chi(eps): """Calculate chi ellipticity from epsilon. Args: eps: a real or complex number, or a numpy array thereof. Returns: The chi ellipticity in the same shape as the input. """ return 2*eps/(1 + abs(eps)**2)
def getIntersections( intervals ): """combine intervals. Overlapping intervals are reduced to their intersection. """ if not intervals: return [] intervals.sort() max_to = intervals[0][1] all_sections = [] sections = [ intervals[0][0], intervals[0][1] ] for this_from, this_to in intervals[1:]: # no overlap: write everything and reset if this_from > max_to: all_sections.append(sections) max_to = this_to sections = [] max_to = max(max_to, this_to) sections.append( this_from ) sections.append( this_to ) all_sections.append( sections ) new_intervals = [] for sections in all_sections: sections.sort() last_x = sections[0] for x in sections[1:]: if last_x == x: continue new_intervals.append( (last_x, x) ) last_x = x return new_intervals
def GetPlistValue(plist, value): """Returns the value of a plist dictionary, or False.""" try: return plist[value] except KeyError: return False
def find_min(L: list, b: int) -> int: """Precondition: L[b:] is not empty. Return the index of the smallest value in L[b:]. >>> find_min([3, -1, 7, 5], 0) 1 >>> find_min([3, -1, 7, 5], 1) 1 >>> find_min([3, -1, 7, 5], 2) 3 """ smallest = b # The index of the smallest so far i = b + 1 while i != len(L): if L[i] < L[smallest]: # W e found a smaller item at L[i] smallest = i i = i + 1 return smallest
def check_primitive_type(stmt): """i_type_spec appears to indicate primitive type. """ return True if getattr(stmt, "i_type_spec", None) else False
def is_empty(inp): """ True if none or empty :param inp: :return: """ return inp is None or len(inp) == 0
def sort_rows_for_csv(part): """this is the sort function that is used to determine the order of the lines of the csv""" if part['NAME'].find(','): stri = part['NAME'].split(',')[0] else: stri = part['NAME'] if 'DO_NOT_PLACE' in part: return '0' if 'PROVIDED_BY' in part: return '1' return ''.join(c for c in stri if not c.isdigit())
def float2str(flt, separator=".", precision=None, prefix=None, suffix=None): """ Converts a floating point number into a string. Contains numberous options on how the output string should be returned including prefixes, suffixes, floating point precision, and alternative decimal separators. Parameters ---------- flt: float The floating point number separator: string The symbol that will replace the decimal point in the float. Default: "." precision: int or None The number of decimal places of the float to use in the string. Default: None prefix: string or None Characters that are to appear at the beginning of the output. Default: None suffix: string or None Characters that are to appear at the end of the output. Default: None Returns ------- string: str A string representation of the floating point number. Examples: --------- >>> float2str(23) '23' >>> float2str(23.5) '23.5' >>> float2str(23.5, separator="p") '23p5' >>> float2str(23.5, precision=4) '23.5000' >>> float2str(23.501345, precision=4) '23.5013' >>> float2str(23.5, precision=0) '24' >>> float2str(23.5, prefix='z', separator='p') 'z23p5' >>> float2str(23.5, prefix 'z', separator='p', suffix='dex') 'z23p5dex' """ if isinstance(precision, int): str_number = f"{flt:.{precision}f}" else: str_number = str(flt) if separator is not ".": # Split number around the decimal point. number_parts = str_number.split(".") string = separator.join(number_parts) else: string = str_number if isinstance(prefix, str): string = "".join([prefix, string]) if isinstance(suffix, str): string = "".join([string, suffix]) return string
def abbe_number(nd, nF, nC): """ Compute the Abbe number (reciprocal dispersion). Using the visible F, d, and C lines: F(H): 486.1 nm d(He): 587.6 nm C(H): 656.3 nm nd, nF, and nC are the refractive indicies at each of these three lines. Todo: Alternately, select a glass type and compute these three n's. """ V = (nd - 1)/(nF - nC) return V
def average(values): """Calculates an unweighted average Args: values (Iterable): The values to find the average of Returns: The average of the inputs Example: >>> average([1, 2, 3]) 2 """ res = sum(values) / len(values) if res == int(res): return int(res) return res
def is_compatible_data_type(expected_data_type, actual_data_type): """ Returns boolean value indicating whether the actual_data_type argument is compatible with the expected_data_type, from a data typing perspective :param expected_data_type: :param actual_data_type: :return: """ retval = False if expected_data_type == 'string': retval = (actual_data_type in ["<type 'str'>", "<type 'long'>", "<type 'unicode'>"]) elif expected_data_type == 'integer': retval = (actual_data_type in ["<type 'int'>", "<type 'long'>", "<type 'str'>", "<type 'unicode'>"]) elif expected_data_type == 'long': retval = (actual_data_type in ["<type 'int'>", "<type 'long'>", "<type 'str'>", "<type 'unicode'>"]) elif expected_data_type in ['boolean', 'java.lang.Boolean']: retval = (actual_data_type in ["<type 'int'>", "<type 'str'>", "<type 'long'>", "<type 'unicode'>"]) elif expected_data_type in ['float', 'double']: retval = (actual_data_type in ["<type 'float'>", "<type 'str'>", "<type 'unicode'>"]) elif expected_data_type == 'properties' or expected_data_type == 'dict': retval = (actual_data_type in ["<type 'PyOrderedDict'>", "<type 'oracle.weblogic.deploy.util.PyOrderedDict'>", "<type 'dict'>", "<type 'str'>"]) elif 'list' in expected_data_type: retval = (actual_data_type in ["<type 'list'>", "<type 'str'>", "<type 'unicode'>"]) elif expected_data_type in ['password', 'credential', 'jarray']: retval = (actual_data_type in ["<type 'str'>", "<type 'unicode'>"]) elif 'delimited_' in expected_data_type: retval = (actual_data_type in ["<type 'str'>", "<type 'list'>", "<type 'unicode'>"]) return retval
def normalize_sequence(value, rank): """For scalar input, duplicate it into a sequence of rank length. For sequence input, check for correct length. """ # Like e.g. scipy.ndimage.zoom() -> _ni_support._normalize_sequence(). try: lst = list(value) except TypeError: lst = [value] * rank if len(lst) != rank: raise ValueError('Invalid sequence length.') return lst
def resource_filename(lang_code: str, resource_type: str, resource_code: str) -> str: """ Return the formatted resource_filename given lang_code, resource_type, and resource_code. """ return "{}_{}_{}".format(lang_code, resource_type, resource_code)
def decode(to_decode): """ Moves all the uppercase character to the beginning of the string and case the lowercase characters to uppercase. Parameters: to_decode: A string that is not all lowercase Returns: A decoded string. >>> decode(" neHAw yePParY") 'HAPPY NEW YEAR' >>> decode(" Gof ERriALTvia") 'GERALT OF RIVIA' >>> decode("ALL UPPERCASE") 'ALLUPPERCASE ' >>> decode("all lowercase") Traceback (most recent call last): ... AssertionError # My doctests >>> decode('324798578~!!') Traceback (most recent call last): ... AssertionError >>> decode('3A4a') Traceback (most recent call last): ... AssertionError >>> decode(' i DloSCve') 'DSC I LOVE' """ assert isinstance(to_decode, str) assert to_decode.lower() != to_decode assert to_decode.replace(' ', '').isalpha() return ''.join([a for a in to_decode if a.isupper()]) \ + ''.join([a.upper() for a in to_decode if not a.isupper()])
def arg_xor_dict(args_array, opt_xor_dict): """Function: arg_xor_dict Description: Does a Xor check between a key in opt_xor_dict and its values using args_array for the check. Therefore, the key can be in args_array or one or more of its values can be in arg_array, but both can not appear in args_array. Arguments: (input) args_array -> Array of command line options and values. (input) opt_xor_dict -> Dictionary with key and values that will be xor with each other. (output) status -> True|False - If key or value is in args_array. """ args_array = dict(args_array) opt_xor_dict = dict(opt_xor_dict) status = True for opt in set(opt_xor_dict.keys()) & set(args_array.keys()): for item in set(opt_xor_dict[opt]) & set(args_array.keys()): print("Option {0} or {1}, but not both.".format(opt, item)) status = False break return status
def _find_argument_unquoted(pos: int, text: str) -> int: """ Get the number of the argument at position pos in a string without interpreting quotes. """ ret = text.split() search = 0 argnum = 0 for i, elem in enumerate(ret): elem_start = text.find(elem, search) elem_end = elem_start + len(elem) search = elem_end if elem_start <= pos < elem_end: return i argnum = i return argnum + 1
def bfsAllPaths(graph, start, goal): """Finds all paths between 2 nodes in a graph using BFS Args: graph (dict): Search space represented by a graph start (str): Starting state goal (str): Goal state Returns: solutions (list): List of the paths that bring you from the start to the goal state """ # set up a path list path = [start] # return a simple path if start is the goal if start == goal: return path # keep track of all solutions solutions = [] # list to keep track of all visited nodes explored = [] # the FIFO queue queue = [] # add the first path to the queue queue.append(path) # keep looping until there are no nodes still to be checked while len(queue) > 0: # pop first item from queue (FIFO) path = queue.pop(0) # retrieve the last node from the path list node = path[-1] # check if the node has already been explored if node not in explored: # add node to list of checked nodes explored.append(node) # get neighbours if node is present, otherwise default to empty list neighbours = graph.get(node, []) # go through all neighbour nodes for neighbour in neighbours: # make a copy of the current path path1 = path[:] # add this neighbour to the path path1.append(neighbour) # append path to solutions if neighbour is goal if neighbour == goal: solutions.append(path1) else: # push it onto the queue for further exploration queue.append(path1) # we couldn't find the goal... :( return solutions
def squeeze(data): """Squeeze a sequence.""" count = [1] values = [data[0]] for value in data[1:]: if value == values[-1]: count[-1] += 1 else: values.append(value) count.append(1) return count, values
def filter_user(user_ref): """Filter out private items in a user dict. 'password', 'tenants' and 'groups' are never returned. :returns: user_ref """ if user_ref: user_ref = user_ref.copy() user_ref.pop('password', None) user_ref.pop('tenants', None) user_ref.pop('groups', None) user_ref.pop('domains', None) try: user_ref['extra'].pop('password', None) user_ref['extra'].pop('tenants', None) except KeyError: pass return user_ref
def frequencies(word_list): """ Takes a list of words and returns a dictionary associating words with frequencies of occurrence """ word_freqs = {} for word in word_list: if word in word_freqs: word_freqs[word] += 1 else: word_freqs[word] = 1 return word_freqs
def get_wstart(ref, wave_ref, wave_per_pixel): """ Obtain the starting wavelength of a spectrum. Parameters ---------- ref: int, Reference pixel. wave_ref: float, Coordinate at reference pixel. wave_per_pixel: float, Coordinate increase per pixel. Returns ------- wstart: float, Starting wavelength. """ return wave_ref - ((ref-1) * wave_per_pixel)
def maxProfitB(prices): """ :type prices: List[int] :rtype: int """ maxCur=0 maxSoFar=0 for i in range(1,len(prices)): maxCur+=prices[i]-prices[i-1] maxCur=max(0,maxCur) maxSoFar=max(maxCur,maxSoFar) return maxSoFar
def make_players(player_data, match_id): """Make player structures.""" return [ dict( player, user=dict( id=player['user_id'], name=player['name'], platform_id=player['platform_id'], person=dict( id=player['person_id'], country=player['country'], name=player['person_name'] ) if player['person_id'] else None, ) if player['user_id'] else None, civilization=dict( id=player['civilization_id'], name=player['civilization_name'], dataset_id=player['dataset_id'] ) ) for player in player_data[match_id] ]
def process_line(line): """Return the structure frequencies for a line of STRIDE data.""" result = {} for structure in line.split(): result[structure] = result.get(structure, 0) + 1 return result
def _sanity_check_kwargs(args): """Sanity check after setting up input arguments, handling back compatibility """ if not args.get("workflow") and not args.get("run_info_yaml"): return ("Require a sample YAML file describing inputs: " "https://bcbio-nextgen.readthedocs.org/en/latest/contents/configuration.html")
def get_slice(index): """Returns a slice converted from index.""" if index == -1: return slice(0, None) if isinstance(index, int): # return slice(index, index+1) return index if isinstance(index, tuple): return slice(index[0], index[1]) if isinstance(index, slice): return index raise ValueError(f'Un supported index: {index}')
def subset_sum(x, R): """Subsetsum :param x: table of non negative values :param R: target value :returns bool: True if a subset of x sums to R :complexity: O(n*R) """ b = [False] * (R + 1) b[0] = True for xi in x: for s in range(R, xi - 1, -1): b[s] |= b[s - xi] return b[R]
def get_variable_name_list(expressions): """Get variable names from a given expressions list""" return sorted(list({symbol.name for expression in expressions for symbol in expression.free_symbols if "x" in symbol.name}))
def ensure_list(name, value, item_type=None): """Raise an error if value is not a list or, optionally, contains elements not of a specified type.""" if not isinstance(value, list): raise TypeError("{} must be a list: {}".format(name, value)) if item_type: for item in value: if not isinstance(item, item_type): raise TypeError("{} contain only {}: {}".format( name, item_type, item)) return value