content
stringlengths
42
6.51k
def capitalise_string(string): """ Capitalise the first letter of each word in a string. The original string may contain (). """ capitalised_string = '' string_list = string.lower().split(' ') for i in range(len(string_list)): if not string_list[i]: continue elif string_list[i][0] != '(': capitalised_string += string_list[i].capitalize() + ' ' else: capitalised_string += '(' + string_list[i][1:].capitalize() + ' ' return capitalised_string[:-1]
def test_format(fmt): """ Test the format string with a floating point number :param fmt: string, the format string i.e. "7.4f" :type fmt: str :returns: bool, if valid returns True else returns False :rtype: bool """ try: if fmt.startswith('{') and fmt.endswith('}'): return True elif 's' in fmt: return True elif 'd' in fmt: _ = ('{0:' + fmt + '}').format(123) else: _ = ('{0:' + fmt + '}').format(123.456789) return True except ValueError: return False
def table_formatter(rows): """Format the rows (a list of col/cell lists) as an HTML table string.""" row_cells = [''.join([f'<td style="font-size: 14px; padding: 20px;">{cell}</td>'for cell in row]) for row in rows] trs = [f'<tr>{cells}</tr>' for cells in row_cells] return f'<table class="lemma-table">{"".join(trs)}</table>'
def samples_number(session, Type='Int32', RepCap='', AttrID=1150021, buffsize=0, action=['Get', '']): """[Get Number of Samples] Returns the integer number of complex samples that will be available to Get Data or Get Data Block when the measurement completes. """ return session, Type, RepCap, AttrID, buffsize, action
def round_closest(x, base=10): """ Args: x: base: Returns: """ return int(base * round(float(x)/base))
def calc_crc(message_array): """ CRC7 Algorithm, given an array of "bytes" (8-bit numbers) calculate a CRC7. Polynomial: 0x89 @param message_array, array of bytes to calculate a CRC7. """ message_length = len(message_array) * 8 remainder = message_array[0] polynomial = 0x89 # original design, do we need to run through the PADDING bits? for bit_index in range(0, message_length): # Pull from next byte, skip when we have pulled in the last byte (8 bits ahead of end) # last 7 bits are zeros (padding) if bit_index != 0 and bit_index < (message_length - 8): # grab the next byte # -1 ensures the starting bit of a byte gets the last bit of its byte next_byte_index = int((bit_index-1) / 8) + 1 # Need to offset for next bit to add next_byte_bit_position = (bit_index + 8) % 8 # Convert out of range case (8) to 0, ensure offset is in order for shifting in the byte next_byte_bit_position = (8 - next_byte_bit_position) % 8 next_value = (message_array[next_byte_index] >> next_byte_bit_position) & 0x1 remainder |= next_value # This will always skip the MSB (CRC-7 is 7 bits long and SD card CMD MSB is always '0b0') if remainder & 0x80: remainder ^= polynomial # the final bit has been processed, kick out of loop if bit_index >= message_length - 1: break remainder <<= 1 # keep only the first 8 bits # NOTE: Do not move this to the C version (C type have a defined size) remainder &= 0xFF return remainder
def hook_makeOutline(VO, blines): """Return (tlines, bnodes, levels) for list of Body lines. blines can also be Vim buffer object. """ tlines, bnodes, levels = [], [], [] tlines_add, bnodes_add, levels_add = tlines.append, bnodes.append, levels.append seen = {} # seen previousely on the command line sig_ = '' for i,L in enumerate(blines): L = L.strip() if not L: continue # skip empty elif not L.startswith('<'): continue # tag? else: L = L.rsplit('>')[0].rstrip() # cleanup line if len(L) < 2: continue # skip really short lines L = L.lower() # outline will be lower cased W = L.split()[1:3] if L.startswith('no ') else L.split()[0:2] W = L.split()[1:5] if L.startswith('no ') else L.split()[0:4] if not W: continue # assign level 1 when seeing a glob cmd for the 1st time, else 2 sig = W[0] if W[0].startswith('int'): # int <type>x/y/z0..zn fold into int <type>x/y sig = '%s %s'%(W[0],W[1].rstrip('0123456789')) L = L.replace('interface','int') L = L.replace('fastethernet','fa') L = L.replace('gigabitethernet','gi') elif W[0].startswith('access-list'): sig = '%s %s'% (W[0],W[1]) L = L.replace('access-list','acl') elif W[0].startswith('static'): sig = '%s %s'% (W[0],W[1]) else: sig = W[0] L = ' '.join(W[0:4]) lev = 2 if sig in seen else seen.setdefault(sig,1) lev = 2 if sig == sig_ else 1 sig_ = sig levels_add(lev) tlines_add(' {0}|{1}'.format(' .'*(lev-1), L)) bnodes_add(i+1) return (tlines, bnodes, levels)
def make_readable(val): """ a function that converts bytes to human readable form. returns a string like: 42.31 TB example: your_variable_name = make_readable(value_in_bytes) """ data = float(val) tib = 1024 ** 4 gib = 1024 ** 3 mib = 1024 ** 2 kib = 1024 if data >= tib: symbol = ' TB' new_data = data / tib elif data >= gib: symbol = ' GB' new_data = data / gib elif data >= mib: symbol = ' MB' new_data = data / mib elif data >= kib: symbol = ' KB' new_data = data / kib else: symbol = ' B' new_data = data formated_data = "{0:.2f}".format(new_data) converted_data = str(formated_data).ljust(6) + symbol return converted_data
def _get_all_techs(postgame, de_data): """Get all techs flag.""" if de_data is not None: return de_data.all_techs if postgame is not None: return postgame.all_techs return None
def is_backend_supported(name: str) -> bool: """Returns if the backend is supported. Args: name: The backend name. Returns: bool """ return name == 's3'
def make_cmd_invocation(invocation, args, kwargs): """ >>> make_cmd_invocation('path/program', ['arg1', 'arg2'], {'darg': 4}) ['./giotto-cmd', '/path/program/arg1/arg2/', '--darg=4'] """ if not invocation.endswith('/'): invocation += '/' if not invocation.startswith('/'): invocation = '/' + invocation cmd = invocation for arg in args: cmd += str(arg) + "/" rendered_kwargs = [] for k, v in kwargs.items(): rendered_kwargs.append("--%s=%s" % (k,v)) return ['./giotto-cmd', cmd] + rendered_kwargs
def is_6_digits(number: int) -> bool: """It is a six-digit number.""" if len(str(number)) == 6: return True return False
def correct_sentence(text: str) -> str: """ returns a corrected sentence which starts with a capital letter and ends with a dot. """ # your code here if ord(text[0]) >= 97 and ord(text[0]) < 123: text = chr(ord(text[0]) - 32) + text[1:] if text[-1] != ".": text += "." return text
def lcs_len(s1, s2): """ return lenght of the lcs of s1 and s2 s1 : sequence , (len = n) s2 : sequence , (len = m) Try to be memory efficient O(n) CPU time O(m.n) Usually faster than computing the full lcs matrix. And generally best algorithm to use if you are only interested in the edit distance, and are working with relatively short sequences, without knowing specific property of your alphabet... """ m = len(s1) n = len(s2) if n == 0 or m == 0: return 0 # one can be smarter by storing only n+1 element # but the hevy use of modulo slow thig down a lot. rngc = [0 for x in range(n)] ## current row rngp = [0 for x in range(n)] ## previous row for i,c1 in enumerate(s1): rngc, rngp = rngp, rngc for j,c2 in enumerate(s2): if c1 == c2 : if i == 0 or j == 0: rngc[j] = 1 else: rngc[j] = rngp[j-1]+1 else : if i == 0: rngc[j] = 0 elif j == 0: rngc[j] = rngp[j] else : rngc[j] = max(rngc[j-1],rngp[j]) return rngc[-1]
def direct(corpus): """la fonction qui renvoie la liste des phrases issues de la traduction directe""" return [elt for elt in corpus if elt["src_lang"] == elt["orig_lang"]]
def luhn_check(card_number): """ checks to make sure that the card passes a luhn mod-10 checksum """ sum = 0 num_digits = len(card_number) oddeven = num_digits & 1 for count in range(0, num_digits): digit = int(card_number[count]) if not ((count & 1) ^ oddeven): digit *= 2 if digit > 9: digit -= 9 sum += digit return (sum % 10) == 0
def roll(s, first, last): """ Determine the variability of a variant by looking at cyclic permutations. Not all cyclic permutations are tested at each time, it is sufficient to check ``aW'' if ``Wa'' matches (with ``a'' a letter, ``W'' a word) when rolling to the left for example. >>> roll('abbabbabbabb', 4, 6) (3, 6) >>> roll('abbabbabbabb', 5, 5) (0, 1) >>> roll('abcccccde', 4, 4) (1, 3) @arg s: A reference sequence. @type s: any sequence type @arg first: First position of the pattern in the reference sequence. @type first: int @arg last: Last position of the pattern in the reference sequence. @type last: int @return: tuple: - left ; Amount of positions that the pattern can be shifted to the left. - right ; Amount of positions that the pattern can be shifted to the right. @rtype: tuple(int, int) """ pattern = s[first - 1:last] # Extract the pattern pattern_length = len(pattern) # Keep rolling to the left as long as a cyclic permutation matches. minimum = first - 2 j = pattern_length - 1 while minimum > -1 and s[minimum] == pattern[j % pattern_length]: j -= 1 minimum -= 1 # Keep rolling to the right as long as a cyclic permutation matches. maximum = last j = 0 while maximum < len(s) and s[maximum] == pattern[j % pattern_length]: j += 1 maximum += 1 return first - minimum - 2, maximum - last
def binc(n, k): """binc(n, k): Computes n choose k.""" if (k > n): return 0 if (k < 0): return 0 if (k > int(n/2)): k = n - k rv = 1 for j in range(0, k): rv *= n - j rv /= j + 1 return int(rv)
def _get_id_given_url(original_url: str) -> str: """ Parse id from original URL """ return original_url.replace('https://', 'http://').replace('http://vocab.getty.edu/page/ia/', '')
def RPL_ENDOFWHO(sender, receipient, message): """ Reply Code 315 """ return "<" + sender + ">: " + message
def determine_format(supported): """ Determine the proper format to render :param supported: list of formats that the builder supports :return: Preferred format """ order = ['image/svg+xml', 'application/pdf', 'image/png'] for format in order: if format in supported: return format return None
def base_loss_name_normalizer(name: str) -> str: """Normalize the class name of a base BaseLoss.""" return name.lower().replace('loss', '')
def find_all_highest(l, f): """Find all elements x in l where f(x) is maximal""" if len(l) == 1: return l maxvalue = max([f(x) for x in l]) return [x for x in l if f(x) == maxvalue]
def get_safe_name(progname, max_chars = 10): """Get a safe program name""" # Remove special characters for c in r'-[]/\;,><&*:%=+@!#^()|?^': progname = progname.replace(c,'') # Set a program name by default: if len(progname) <= 0: progname = 'Program' # Force the program to start with a letter (not a number) if progname[0].isdigit(): progname = 'P' + progname # Set the maximum size of a program (number of characters) if len(progname) > max_chars: progname = progname[:max_chars] return progname
def prepare_author(obj): """ Make key {author.identifier.id}_{author.identifier.scheme} or {author.identifier.id}_{author.identifier.scheme}_{lot.id} if obj has relatedItem and questionOf != tender or obj has relatedLot than """ base_key = u"{id}_{scheme}".format( scheme=obj["author"]["identifier"]["scheme"], id=obj["author"]["identifier"]["id"] ) if obj.get("relatedLot") or (obj.get("relatedItem") and obj.get("questionOf") == "lot"): base_key = u"{base_key}_{lotId}".format( base_key=base_key, lotId=obj.get("relatedLot") or obj.get("relatedItem") ) return base_key
def frequency(tokens: list, seq_len: int = 5) -> dict: """ Counts the frequency of unique sequences in a list of tokens. Returns a dictionary where keys are unique sequences of length 1 to `seq_len` and values are the count of occurences of those sequences in the `tokens` list. Parameters: tokens (list): list of tokens parsed from a document. seq_len (int): (min 1) max length of sequences to count. Returns: dict: {sequence: count} """ assert seq_len >= 1, 'seq_len must be at least 1.' seq_count = {} for length in range(1, seq_len + 1): for i in range(len(tokens) - (length - 1)): seq = tuple(tokens[i:i+length]) if seq in seq_count: seq_count[seq] = seq_count[seq] + 1 else: seq_count[seq] = 1 return seq_count
def is_palindrome(num): """ Returns true if num is a palindrome. """ return str(num) == str(num)[::-1]
def flatten(fields): """Returns a list which is a single level of flattening of the original list.""" flat = [] for field in fields: if isinstance(field, (list, tuple)): flat.extend(field) else: flat.append(field) return flat
def _should_keep_module(name): """Returns True if the module should be retained after sandboxing.""" return (name in ('__builtin__', 'sys', 'codecs', 'encodings', 'site', 'google') or name.startswith('google.') or name.startswith('encodings.') or # Making mysql available is a hack to make the CloudSQL functionality # work. 'mysql' in name.lower())
def dictFromPool(fields, pool): """ pool is assumed to be a list of lists, of various lengths, but the same order, where fields are present fields is the fields to check against """ result = {} found = [i for i in pool if i[:len(fields)] == fields] for i in found: if fields == i: continue newField = i[ len(fields) ] nextFields = list(fields) + [newField] result[newField] = dictFromPool(nextFields, found) return result
def make_test_config(contexts, clusters, users, current_context): """ Return a KubeConfig dict constructed with the given info All parameters are required. """ return { 'apiVersion': 'v1', 'kind': 'Config', 'clusters': [{'name': key, 'cluster': value} for key, value in clusters.items()], 'contexts': [{'name': key, 'context': value} for key, value in contexts.items()], 'users': [{'name': key, 'user': value} for key, value in users.items()], 'current-context': current_context }
def convert_km_to_length(length): """Convert length like '1' to 1000 or '30M' to 30""" try: if length[-1:] == "M": t_length = int(length[:-1]) # Trim off the 'M' else: t_length = int(float(length) * 1000) # Convert to meters length_str = str(t_length) except ValueError: length_str = "" return length_str
def is_bidirectional_conversion(letter_id, letter_case, reverse_letter_case): """ Check that two unicode value are also a mapping value of each other. :param letter_id: An integer, representing the unicode code point of the character. :param other_case_mapping: Comparable case mapping table which possible contains the return direction of the conversion. :return: True, if it's a reverible conversion, false otherwise. """ if letter_id not in letter_case: return False # Check one-to-one mapping mapped_value = letter_case[letter_id] if len(mapped_value) > 1: return False # Check two way conversions mapped_value_id = ord(mapped_value) if mapped_value_id not in reverse_letter_case or len(reverse_letter_case[mapped_value_id]) > 1: return False if ord(reverse_letter_case[mapped_value_id]) != letter_id: return False return True
def python2js(d): """Return a string representation of a python dictionary in ecmascript object syntax.""" objs = [] for key, value in d.items(): objs.append( key + ':' + str(value) ) return '{' + ', '.join(objs) + '}'
def get_fewest_steps(pts1, pts2, intersections): """Returns the minimum number of steps required to get to an intersection point between the two paths. Args: pts1: the list of points along the first path pts2: the list of points along the second path intersections: the list of points where the paths intersect """ # make a dictionary of the number of steps required to get to each # intersection point x_pt_dict = { x_pt: {'path1':0, 'path2':0, 'tot':0} for x_pt in intersections} intersection_steps = [] for intersection in intersections: x_pt_dict[intersection]['path1'] = pts1.index(intersection) x_pt_dict[intersection]['path2'] = pts2.index(intersection) x_pt_dict[intersection]['tot'] = (x_pt_dict[intersection]['path1'] + x_pt_dict[intersection]['path2']) intersection_steps.append(x_pt_dict[intersection]['tot']) return min(intersection_steps)
def validate_alignments(item, base_chars='()-'): """Simple validator for alignments Note ---- Make sure an alignment is not longer than its segments. """ for alm in ['Alignment']: derived_alignment = [x for x in item[alm] if x not in '()-'] if len(derived_alignment) != len(item['Form']): return False return True
def normalize_matrix1D(lst): """ Normalizes a given 1 dimensional list. :param lst: list of items :return: normalized list """ max_val = max(lst) if max_val == 0: return lst else: norm_list = list() for val in lst: norm_list.append(val / max_val) return norm_list
def collapse(values): """Collapse multiple values to a colon-separated list of values""" if isinstance(values, str): return values if values is None: return "all" if isinstance(values, list): return ";".join([collapse(v) for v in values]) return str(values)
def filterRssData(bssid_data, rss_data, keys, minimum_rss_value=-95): """ Filter the rss data by using pre-selected bssids. Args: bssid_data: list of strings with each representing bssid of different access point rss_data: list of integers with each representing signal strength from different access point keys: list of strings, pre-selected bssids minimun_rss_value: negative integer, the minimum signal strength, it is used as defualt value if some of pre-selected bssids could not be found. Return: list of integers, ordered as pre-selected bssids """ # Initialize the filtered data by minimum rss values data = {key:minimum_rss_value for key in keys} # Fill in the data if bssid falls in pre-selected bssids. for index, bssid in enumerate(bssid_data): if bssid in keys: data[bssid] = rss_data[index] return list(data.values())
def hex_to_rgb(hex_color): """ Fungsi ini menerima inputan berupa string hexadecimal dan mengembalikan hasilnya dalam bentuk tuple (r, g, b). Alur proses: * Deklarasi variabel `hex_string` dengan nilai `hex_color` yang telah di bersihkan dari tanda #. * Mengecek apakah panjang string `hex_string` sama dengan 3 * Jika benar, maka setiap karakter di dalam string `hex_string` diulang 2 kali * Jika salah, maka lanjutkan * Mengecek apakah panjang string `hex_string` tidak sama dengan 6 * Jika benar, maka raise ValueError * Jika salah, maka lanjutkan * Looping `i` untuk setiap 2 karakter dari string `hex_string` untuk mengubahnya menjadi basis decimal. * Kembalikan hasil dalam bentuk tuple (r, g, b) Contoh: >>> hex_to_rgb('#000000') (0, 0, 0) >>> hex_to_rgb('#FFFFFF') (255, 255, 255) >>> hex_to_rgb('#0ef') (0, 238, 255) >>> hex_to_rgb('800040') (128, 0, 64) >>> hex_to_rgb('#aabbccdd') Traceback (most recent call last): ... ValueError: Hexadecimal tidak valid """ hex_string = hex_color.lstrip("#") if len(hex_string) == 3: hex_string = "".join(x * 2 for x in hex_string) if len(hex_string) != 6: raise ValueError("Hexadecimal tidak valid") return tuple(int(hex_string[i : i + 2], 16) for i in (0, 2, 4))
def binary_search(values, target): """ :param values: :param target: :return: """ left, right = 0, len(values) - 1 while left <= right: mid = int((left + right) / 2) if target < values[mid]: right = mid - 1 elif target > values[mid]: left = mid + 1 else: return mid return False
def remove_duplicates(items): """Recieve list and return list without duplicated elements""" return list(set(items))
def emitlist(argslist): """Return blocks of code as a string.""" return "\n".join([str(x) for x in argslist if len(str(x)) > 0])
def fn_range(fn): """In : fn (function : dict) Out: range of function (list of values of dict) """ return [v for v in fn.values()]
def scol(string, i): """Get column number of ``string[i]`` in `string`. :Returns: column, starting at 1 (but may be <1 if i<0) :Note: This works for text-strings with ``\\n`` or ``\\r\\n``. """ return i - string.rfind('\n', 0, max(0, i))
def cvsecs(*args): """ converts a time to second. Either cvsecs(min, secs) or cvsecs(hours, mins, secs). """ if len(args) == 1: return float(args[0]) elif len(args) == 2: return 60 * float(args[0]) + float(args[1]) elif len(args) == 3: return 3600 * float(args[0]) + 60 * float(args[1]) + float(args[2])
def likes(names): """ You probably know the "like" system from Facebook and other pages. People can "like" blog posts, pictures or other items. We want to create the text that should be displayed next to such an item. Implement a function likes :: [String] -> String, which must take in input array, containing the names of people who like an item. For 4 or more names, the number in and 2 others simply increases. :param names: A list of names whom like a post. :return: Nicely formatted string of people liking a post. """ n = len(names) return { 0: 'no one likes this', 1: '{} likes this', 2: '{} and {} like this', 3: '{}, {} and {} like this', 4: '{}, {} and {others} others like this' }[min(4, n)].format(*names[:3], others=n-2)
def extract_doi(doi): """Ensure that 'doi' is a single string Occasionally, INSPIRE returns a list of identical DOIs. This just extracts the first element if it is such a list, or returns the input otherwise. """ if isinstance(doi, list) and len(doi)>0: return doi[0] return doi
def numericise(value, empty_value=''): """Returns a value that depends on the input string: - Float if input can be converted to Float - Integer if input can be converted to integer - Zero if the input string is empty and empty2zero flag is set - The same input string, empty or not, otherwise. Executable examples: >>> numericise("faa") 'faa' >>> numericise("3") 3 >>> numericise("3.1") 3.1 >>> numericise("", empty2zero=True) 0 >>> numericise("", empty2zero=False) '' >>> numericise("") '' >>> numericise(None) >>> """ if value == '': return empty_value if value is not None: try: value = int(value) except ValueError: try: value = float(value) except ValueError: pass return value
def B_supp(n, s=1, dx=0, intsupp=False): """ Returns a min and max value of the domain on which the 1D cardinal B-spline of order n is non-zero. INPUT: - degree n, an integer INPUT (optional): - scale s, a real scalar number. Specifies the support of scaled B-splines via supp( B( . / s) ) - offset dx, a real scalar number. Specifies the support of scaled+shifted B-splines via supp(B( . / s - dx) - intsupp, a boolean. Specifies whether or not the support should be on an integer grid. E.g. if xMax would be 2.3, and we only sample integer positions x. Then 2 would still be non-zero, but 3 would evaluate to zero. In this case the non-zero interval would be [-2,2] whereas in the intsupp=False case it would be [-2.3,2.3] OUTPUT: - (xMin, xMax), the min-max range of the support """ xMinMax = s * (n + 1) / 2 xMin = -xMinMax + dx xMax = xMinMax + dx if intsupp: xMax = (int(xMax) - 1 if int(xMax) == xMax else int(xMax)) xMin = (int(xMin) + 1 if int(xMin) == xMin else int(xMin)) return (xMin, xMax)
def consistent_typical_range_stations(stations): """ returns the stations that have consistent typical range data Inputs ------ stations: list of MonitoringStation objects Returns ------ a list of stations that have consistent typical range data """ consistent_station_list = [] for station in stations: if station.typical_range_consistent() == True: consistent_station_list.append(station) return consistent_station_list
def snake2camel( s ): """ Switch string s from snake_form_naming to CamelCase """ return ''.join( word.title() for word in s.split( '_' ) )
def runge_step(f, xk, yk, h, *args): """ completes a single step of the runge cutter method (K4) ---------- Parameters ---------- f: callable differential equation to solve xk: float x ordinate for step start tk: float y ordinate for step start h: float step size ---------- Returns ---------- float: Approximated yk+1 value """ k1 = h*f(xk, yk, *args) k2 = h*f(xk + h/2, yk + k1/2, *args) k3 = h*f(xk + h/2, yk + k2/2, *args) k4 = h*f(xk + h, yk + k3, *args) return yk + (1/6)*(k1 + 2*k2 + 2*k3 + k4)
def parseUpdatedEntity(entityLine): """ parse entity line """ result = entityLine.split() #entity_ID = result[0]+'_'+result[1] entity_name = result[1] #particle = '-' #particle = 'GenericParticle' if len(result) == 3: attributes = result[2] #attributes = attributes.lower() attributes = attributes.replace('gender','color') attributes = attributes.replace('female','pink') attributes = attributes.replace('male','blue') attributes = attributes.replace('photo','pic') attributes = attributes.replace('name','label') else: attributes = 'label=' + entity_name return "UPDATE NODE %s %s" % (entity_name,attributes)
def resolve_variables(template_configuration: dict) -> dict: """ The first step of the lifecycle is to collect the variables provided in the configuration. This will add the name and value of each variable to the run-configuration. :param template_configuration: :return: """ run_configuration = {} variables = template_configuration.get('variables') if variables: for variable in variables: if variable['name']: run_configuration[variable['name']] = variable['value'] else: raise AttributeError return run_configuration
def byte_to_str_index(string, byte_index): """Converts a byte index in the UTF-8 string into a codepoint index. If the index falls inside of a codepoint unit, it will be rounded down. """ for idx, char in enumerate(string): char_size = len(char.encode('utf-8')) if char_size > byte_index: return idx byte_index -= char_size return len(string)
def is_same_dictionary(a, b): """Shallow dictionary comparison""" keysA = set(a.keys()) keysB = set(b.keys()) sharedKeys = keysA & keysB if len(keysA) != len(keysB) or len(sharedKeys) != len(keysB): return False for k, v in a.items(): if b[k] != v: return False return True
def twos_comp(val, bits=32): """compute the 2's complement of int value val from https://stackoverflow.com/questions/1604464/twos-complement-in-python""" if (val & (1 << (bits - 1))) != 0: # if sign bit is set e.g., 8bit: 128-255 val = val - (1 << bits) # compute negative value return val
def huffman_decoding(data, tree): """ Decode Huffman code Parameters: data (str): string of bits Returns: decoded (str): decoded data in original form """ current = tree decoded = "" for bit in data: if bit == '0': current = current.left_child else: current = current.right_child if current.left_child is None and current.right_child is None: decoded += current.char current = tree return decoded
def _image_type(typestr): """Return the translation of CRDS fuzzy type name `typestr` into numpy dtype str() prefixes. If CRDS has no definition for `typestr`, return it unchanged. """ return { 'COMPLEX':'complex', 'INT' : 'int', 'INTEGER' : 'int', 'FLOAT' : 'float', 'BOOLEAN' : 'bool' }.get(typestr, typestr)
def is_valid(var, var_type, list_type=None): """ Check that the var is of a certain type. If type is list and list_type is specified, checks that the list contains list_type. Parameters ---------- var: any type Variable to be checked. var_type: type Type the variable is assumed to be. list_type: type Like var_type, but applies to list elements. Returns ------- var: any type Variable to be checked (same as input). Raises ------ AttributeError If var is not of var_type """ if not isinstance(var, var_type): raise AttributeError(f'The given variable is not a {var_type}') if var_type is list and list_type is not None: for element in var: _ = is_valid(element, list_type) return var
def is_multiline(s): """Returns True if the string contains more than one line. This tends to perform much better than len(s.splitlines()) or s.count('\n') :param s: string to check :return: Bool """ start = 0 lines = 1 while True: idx = s.find('\n', start) if idx == -1: return lines > 1 else: lines += 1 if lines > 1: return True else: start = idx + 1
def set_defaults(data: dict) -> dict: """Set default values for data if missing.""" # Set tuning as default if "tuning" not in data: data.update({"tuning": True}) # Set int8 as default requested precision if "precision" not in data: data.update({"precision": "int8"}) if not data["tuning"]: data["dataset_path"] = "no_dataset_location" return data
def clamp(value, minimum, maximum): """Clamp value within a range - range doesn't need to be ordered""" if minimum > maximum: minimum, maximum = maximum, minimum if value < minimum: return minimum if value > maximum: return maximum return value
def exposure_time(vmag, counts, iodine=False, t1=110., v1=8., exp1=250., iodine_factor=0.7): """ Expected exposure time based on the scaling from a canonical exposure time of 110s to get to 250k on 8th mag star with the iodine cell in the light path Parameters ---------- expcounts : float desired number of counts 250 = 250k, 10 = 10k (CKS) i.e. SNR = 45 per pixel. iodine (bool) : is iodine cell in or out? If out, throughput is higher by 30% Returns ------- exptime : float exposure time [seconds] """ # flux star / flux 8th mag star fluxfactor = 10.0**(-0.4*(vmag-v1)) exptime = t1/fluxfactor exptime *= counts/exp1 if iodine == False: exptime *= iodine_factor return exptime
def async_wm2_to_lx(value: float) -> int: """Calculate illuminance (in lux).""" return round(value / 0.0079)
def get_year(born_txt): """ input: a list of string output: 'yyyy' or '' """ for i in range(len(born_txt)): words = born_txt[i].split() for word in words: if len(word) == 4 and word.isnumeric(): return word if len(word) == 9 and word[4] == '/' and word[:4].isnumeric() and word[5:].isnumeric(): return word return ''
def calculate_crc16(buffer): """ Calculate the CRC16 value of a buffer. Should match the firmware version :param buffer: byte array or list of 8 bit integers :return: a 16 bit unsigned integer crc result """ result = 0 for b in buffer: data = int(b) ^ (result & 0xFF) data = data ^ ((data << 4) & 0xFF) result = ((data << 8) | (result >> 8)) ^ (data >> 4) ^ (data << 3) result = result & 0xFFFF return result
def unique(lst): """Unique with keeping sort/order ["a", "c", "b", "c", "c", ["d", "e"]] Results in ["a", "c", "b", "d", "e"] """ nl = [] [(nl.append(e) if type(e) is not list else nl.extend(e)) \ for e in lst if e not in nl] return nl
def powers(n, k): """Computes and returns a list of n to the powers 0 through k.""" n_pows = [] for i in range(k+1): n_pows.append(n**i) return n_pows
def setdiff(list1, list2): """ returns list1 elements that are not in list2. preserves order of list1 Args: list1 (list): list2 (list): Returns: list: new_list Example: >>> # ENABLE_DOCTEST >>> from utool.util_list import * # NOQA >>> import utool as ut >>> list1 = ['featweight_rowid', 'feature_rowid', 'config_rowid', 'featweight_forground_weight'] >>> list2 = [u'featweight_rowid'] >>> new_list = setdiff_ordered(list1, list2) >>> result = ut.repr4(new_list, nl=False) >>> print(result) ['feature_rowid', 'config_rowid', 'featweight_forground_weight'] """ set2 = set(list2) return [item for item in list1 if item not in set2]
def fib(n: int): """fibonacci""" if n < 2: return n return fib(n - 1) + fib(n - 2)
def kps_to_BB(kps,imgW,imgH): """ Determine imgaug bounding box from imgaug keypoints """ extend=1 # To make the bounding box a little bit bigger kpsx=[kp[0] for kp in kps] xmin=max(0,int(min(kpsx)-extend)) xmax=min(imgW,int(max(kpsx)+extend)) kpsy=[kp[1] for kp in kps] ymin=max(0,int(min(kpsy)-extend)) ymax=min(imgH,int(max(kpsy)+extend)) if xmin==xmax or ymin==ymax: return None else: #return ia.BoundingBox(x1=xmin,y1=ymin,x2=xmax,y2=ymax) return [(xmin, ymin),(xmax, ymax)]
def bytesToNumber(b): """ Restoring the stripped bytes of an int or long into Python's built-in data types int or long. """ result = 0 round = 0 for byte in b: round += 1 if round > 1: result <<= 8 result |= byte return result
def dh(d, theta, a, alpha): """ Calcular la matriz de transformacion homogenea asociada con los parametros de Denavit-Hartenberg. Los valores d, theta, a, alpha son escalares. """ T = 0 return T
def nested_to_dotted(data): """ Change a nested dictionary to one with dot-separated keys This is for working with the weird YAML1.0 format expected by ORBSLAM config files :param data: :return: """ result = {} for key, value in data.items(): if isinstance(value, dict): for inner_key, inner_value in nested_to_dotted(value).items(): result[key + '.' + inner_key] = inner_value else: result[key] = value return result
def html(html_data): """ Builds a raw HTML element. Provides a way to directly display some HTML. Args: html_data: The HTML to display Returns: A dictionary with the metadata specifying that it is to be rendered directly as HTML """ html_el = { 'Type': 'HTML', 'Data': html_data, } return html_el
def killwhitespace(string): """ Merge consecutive spaces into one space. """ return " ".join(s.strip() for s in string.split())
def get_thousands_string(f): """ Get a nice string representation of a field of 1000's of NIS, which is int or None. """ if f is None: return "N/A" elif f == 0: return "0 NIS" else: return "%d000 NIS" % f
def percent_to_zwave_position(value: int) -> int: """Convert position in 0-100 scale to 0-99 scale. `value` -- (int) Position byte value from 0-100. """ if value > 0: return max(1, round((value / 100) * 99)) return 0
def safenum(v): """Return v as an int if possible, then as a float, otherwise return it as is""" try: return int(v) except (ValueError, TypeError): pass try: return float(v) except (ValueError, TypeError): pass return v
def dx_to_wes_state(dx_state): """Convert the state returned by DNAnexus to something from the list of states defined by WES. """ if dx_state in ("running", "waiting_on_input", "waiting_on_output"): return "RUNNING" elif dx_state == "runnable": return "QUEUED" elif dx_state in ("failed", "terminating", "terminated"): return "EXECUTOR_ERROR" elif dx_state in "done": return "COMPLETE" return "UNKNOWN"
def other_heuristic(text, param_vals): """ Post-processing heuristic to handle the word "other" """ if ' other ' not in text and ' another ' not in text: return text target_keys = { '<Z>', '<C>', '<M>', '<S>', '<Z2>', '<C2>', '<M2>', '<S2>', } if param_vals.keys() != target_keys: return text key_pairs = [ ('<Z>', '<Z2>'), ('<C>', '<C2>'), ('<M>', '<M2>'), ('<S>', '<S2>'), ] remove_other = False for k1, k2 in key_pairs: v1 = param_vals.get(k1, None) v2 = param_vals.get(k2, None) if v1 != '' and v2 != '' and v1 != v2: print('other has got to go! %s = %s but %s = %s' % (k1, v1, k2, v2)) remove_other = True break if remove_other: if ' other ' in text: text = text.replace(' other ', ' ') if ' another ' in text: text = text.replace(' another ', ' a ') return text
def get_loss_gradients(model, loss_blobs): """Generate a gradient of 1 for each loss specified in 'loss_blobs'""" loss_gradients = {} for b in loss_blobs: loss_grad = model.net.ConstantFill(b, [b + '_grad'], value=1.0) loss_gradients[str(b)] = str(loss_grad) return loss_gradients
def render_dusk(data, query, local_time_of): """dusk (d) Local time of dusk""" return local_time_of("dusk")
def reversemap(obj): """ Invert mapping object preserving type and ordering. """ return obj.__class__(reversed(item) for item in obj.items())
def str_confirmacao(value): # Only one argument. """Converts a string into all lowercase""" if(value == 0): return "Nao Confirmada" else: return "Reservado"
def blender_id_endpoint(endpoint_path=None): """Gets the endpoint for the authentication API. If the BLENDER_ID_ENDPOINT env variable is defined, it's possible to override the (default) production address. """ import os import urllib.parse base_url = os.environ.get('BLENDER_ID_ENDPOINT', 'https://www.blender.org/id/') # urljoin() is None-safe for the 2nd parameter. return urllib.parse.urljoin(base_url, endpoint_path)
def sum_cubes(n): """Sum the first N cubes of natural numbers. """ total, k = 0\ , 1 while k <= n: total, k = total + pow(k, 3), k + 1 return total
def mechanism_thermo(mech1_thermo_dct, mech2_thermo_dct): """ Combine together the thermo dictionaries for two mechanisms. :param mech1_thermo_dct: thermo dct for mechanism 1 :type mech1_thermo_dct: dict[spc: [[H(t)], [Cp(T)], [S(T)], [G(T)]] :param mech2_thermo_dct: thermo dct for mechanism 2 :type mech2_thermo_dct: dict[spc: [[H(t)], [Cp(T)], [S(T)], [G(T)]] :return total_thermo_dct: dict with thermo from both mechanisms :rtype: dict[mech: mech_thermo_dct] """ total_thermo_dct = {} # Build full thermo dictionary with common index # First loop through mech1: add common and mech1-unique species for mech1_name, mech1_vals in mech1_thermo_dct.items(): mech2_vals = mech2_thermo_dct.get(mech1_name, [None, None, None, None]) total_thermo_dct[mech1_name] = { 'mech1': mech1_vals, 'mech2': mech2_vals } # Now add the entries where mech2 exists, but mech1 does not uni_mech2_names = [name for name in mech2_thermo_dct.keys() if name not in mech1_thermo_dct] for mech2_name in uni_mech2_names: total_thermo_dct[mech2_name] = { 'mech1': [None, None, None, None], 'mech2': mech2_thermo_dct[mech2_name] } return total_thermo_dct
def which_one_in(l, f): """ returns which one element of list l is in f, otherwise None """ included = [i for i in l if str(i) in f] if len(included) == 1: return included[0] elif len(included) > 1: return False else: return None
def sizeof_fmt(mem_usage: float, suffix: str = 'B') -> str: """ Returns the memory usage calculation of the last function. Parameters ---------- mem_usage : float memory usage in bytes suffix: string, optional suffix of the unit, by default 'B' Returns ------- str A string of the memory usage in a more readable format Examples -------- >>> from pymove.utils.mem import sizeof_fmt >>> sizeof_fmt(1024) 1.0 KiB >>> sizeof_fmt(2e6) 1.9 MiB """ for unit in ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi']: if abs(mem_usage) < 1024.0: return f'{mem_usage:3.1f} {unit}{suffix}' mem_usage /= 1024.0 return '{:.1f} {}{}'.format(mem_usage, 'Yi', suffix)
def get_float_value(obj): """ Returns float from LLDB value. :param lldb.SBValue obj: LLDB value object. :return: float from LLDB value. :rtype: float | None """ if obj: value = obj.GetValue() return None if value is None else float(value) return None
def make_iscorr(row, prediction_col_name='predictions', answer_col_name='answer'): """Calculates accuracy @3.""" if bool(set(row[answer_col_name]) & set(row[prediction_col_name])): return 1 else: return 0
def execute_code_if(condition, code, glob=None, loc=None): """ Execute code if condition is true Args: condition (bool): if true the code is executed code_if_obj_not_found (str): the code to be evaluated if the object has not been found. globals (dict): the global variables dictionary locals (dict): the local variables dictionary Returns: the object returned from the code executed, None otherwise """ if not condition: return None if glob is None: glob = globals() if loc is None: loc = locals() return eval(code, glob, loc)
def create_account(caller): """Create a new account. This node simply prompts the user to enter a username. The input is redirected to 'create_username'. """ text = "Enter your new account's name." options = ( { "key": "_default", "desc": "Enter your new username.", "goto": "create_username", }, ) return text, options
def custom_division(numerator: int, denominator: int) -> int: """ Works only if both integers are +ve """ while numerator > denominator: numerator -= denominator return numerator
def MergeStyles(styles1, styles2): """Merges the styles from styles2 into styles1 overwriting any duplicate values already set in styles1 with the new data from styles2. @param styles1: dictionary of StyleItems to receive merge @param styles2: dictionary of StyleItems to merge from @return: style1 with all values from styles2 merged into it """ for style in styles2: styles1[style] = styles2[style] return styles1
def format_errors(errors, config): """Format errors for output to console.""" if config['debug']: return str(errors) else: formatted = {} for key, error in errors.items(): formatted[key] = error['message'] return str(formatted)
def factorize(distri, binlength): """ Helper function for createHisto. """ INTarea = 0 for ns in distri: INTarea += ns * float(binlength) return INTarea