content
stringlengths
42
6.51k
def is_prime(n: int) -> bool: """Determine if `n` is prime.""" if n < 2 or str(n)[-1] in [0, 2, 4, 5, 6, 8]: return False for divisor in range(2, int(n ** 0.5) + 1): # n ** 0.5 == sqrt(n) if n % divisor == 0: return False return True
def is_bottom(module_index): """Returns True if module is in the bottom cap""" return ( (module_index>=600)&(module_index<696) )
def take_first(iterable): """Returns first element of iterable.""" return [i[0] for i in iterable]
def digitListToInt(arr): """Given list of string digits, convert to integer. If empty return 0""" if len(arr) == 0: return 0 if len(arr) == 1: return int(arr[0]) else: return int("".join(arr))
def shy(value, max_length=None): """ Inserts &shy; elements in over-long strings. """ if not max_length: return value result = [] for word in value.split(): if len(word) > max_length: # Split the word into chunks not larger than max_length nw = [word[i:i+max_length] for i in range(0, len(word), max_length)] result.append(u"&shy;".join(nw)) else: result.append(word) return u" ".join(result)
def crop_images(images, width_mean, length_mean): """Crop images""" train_padded_c = [] for image in images: left = int((image.shape[0] - int(width_mean))/2) top = int((image.shape[1] - int(length_mean))/2) right = int((image.shape[0] + int(width_mean))/2) bottom = int((image.shape[1] + int(length_mean))/2) train_padded_c.append(image[left:right, top:bottom]) return train_padded_c
def list_type(l): """ """ return list_type(l[0]) if l and isinstance(l, list) else type(l)
def parse_reaction_other(event, user_id): """ Finds a direct mention (a mention that is at the beginning) in message text and returns the user ID which was mentioned. If there is no direct mention, returns None """ if 'type' in event \ and event['type'].startswith('reaction_')\ and user_id != event['user']: return '{} {}'.format(event['type'], event['reaction'], event['user']) return None
def flatten(iterable): """ Flatten array """ def get_items(array): result = [] for item in array: if isinstance(item, list): result += get_items(item) elif item is not None: result.append(item) return result return get_items(iterable)
def _cma_output(result): """ Returns a dict with the NOP result. """ return {"NOP": result}
def unescape(s): """ unescape html """ html_codes = ( ("'", '&#39;'), ('"', '&quot;'), ('>', '&gt;'), ('<', '&lt;'), ('&', '&amp;') ) for code in html_codes: s = s.replace(code[1], code[0]) return s
def stitch_objects_singleview_right(objects1, objects2, rel_rot, rel_tran): """ only keep view2 """ codes = objects2 affinity_info = {} affinity_info['hit_gt_match'] = None affinity_info['gt_match_in_proposal'] = None affinity_info['affinity_pred'] = None affinity_info['affinity_gt'] = None affinity_info['matching'] = None return codes, rel_tran, rel_rot, affinity_info
def rotateRight(x, amountToShift, totalBits): """Rotate x (consisting of 'totalBits' bits) n bits to right. x = integer input to be rotated amountToShift = the amount of bits that should be shifted totalBits = total amount bits at the input for rotation """ x = x%(2**totalBits) n_mod = ((amountToShift % totalBits) + totalBits) % totalBits return ((x >> n_mod) | ((x << (totalBits-n_mod)))&((2**totalBits)-1))
def _assert_is_valid_pixel_size(target_pixel_size): """Return true if ``target_pixel_size`` is a valid 2 element sequence. Raises ValueError if not a two element list/tuple and/or the values in the sequence are not numerical. """ def _is_number(x): """Return true if x is a number.""" try: if isinstance(x, str): return False float(x) return True except (ValueError, TypeError): return False if not isinstance(target_pixel_size, (list, tuple)): raise ValueError( "target_pixel_size is not a tuple, its value was '%s'", repr(target_pixel_size)) if (len(target_pixel_size) != 2 or not all([_is_number(x) for x in target_pixel_size])): raise ValueError( "Invalid value for `target_pixel_size`, expected two numerical " "elements, got: %s", repr(target_pixel_size)) return True
def int_to_uint32(value_in): """ Convert integer to unsigned 32-bit (little endian) :param value_in: :return: """ return list(value_in.to_bytes(4, byteorder='little', signed=False))
def fastlcsfun(a,b,cmpfun, Dmax=None): """ Same, but with a specific comparison function (different than ==, but following the same convention(return 0 if equal)) return the length of the longest common substring or 0 if the maximum number of difference Dmax cannot be respected Implementation: see the excellent paper "An O(ND) Difference Algorithm and Its Variations" by EUGENE W. MYERS, 1986 NOTE: let D be the minimal number of insertion or deletion that transform A into B let L be the length of a longest common substring we always have D = M + N - 2 * L """ N, M = len(a), len(b) if N+M == 0: return 0 #very special case... if Dmax == None: Dmax = N + M #worse case else: Dmax = min(Dmax, M+N) #a larger value does not make sense! assert Dmax >= 0, "SOFWARE ERROR: Dmax must be a positive integer" sesLength = None W = [0] * (Dmax * 2 + 2) #for i in -Dmax..Dmax, V[i] == W[i+Dmax) for D in range(0, Dmax+1): for k in range(-D, +D+1, 2): if k == -D or (k != D and W[k-1+Dmax] < W[k+1+Dmax]): #k == -D or (k != D and V[k-1] < V[k+1]) x = W[k+1+Dmax] #x = V[k+1] else: x = W[k-1+Dmax]+1 #x = V[k-1]+1 y = x - k while x < N and y < M and cmpfun(a[x],b[y]) == 0: #follow any snake x += 1 y += 1 W[k+Dmax] = x # V[k] = x #farstest reaching point with D edits if x >= N and y >= M: sesLength = D L = (M+N-D) / 2 assert D == M+N-L-L, ("INTERNAL SOFWARE ERROR", M,N,D) return L return 0
def string_slice(strvar,slicevar): """ slice a string with |string_slice:'[first]:[last]' """ first,last= slicevar.partition(':')[::2] if first=='': return strvar[:int(last)] elif last=='': return strvar[int(first):] else: return strvar[int(first):int(last)]
def snake_to_camel(func_name: str) -> str: """ Convert underscore names like 'some_function_name' to camel-case like 'SomeFunctionName' """ words = func_name.split('_') words = [w[0].upper() + w[1:] for w in words] return ''.join(words)
def _findFalses(splitLabels, forLabel): """ Takes an array of labels, counts the number of FP and FN """ falses = 0 for row in splitLabels: for actual, predicted in row: # If either the predicted or actual is the label we care about if actual == forLabel: if actual != predicted: #if label is false falses += 1 elif predicted == forLabel: if actual != predicted: falses += 1 return falses
def order_tuple(toOrder): """ Given a tuple (a, b), returns (a, b) if a <= b, else (b, a). """ if toOrder[0] <= toOrder[1]: return toOrder return (toOrder[1], toOrder[0])
def remove_key_value(dictionary, *keys): """Delete key, value pairs from a dictionary.""" for key in keys: if key in dictionary: del dictionary[key] return dictionary
def gen_bitpattern(n, start=''): """Generates a bit pattern like 010001 etc.""" if not n: return [start] else: return (gen_bitpattern(n - 1, start + '0') + gen_bitpattern(n - 1, start + '1'))
def find_bound(vals, target, min_idx, max_idx, which): """ Returns the first index that is either before or after a particular target. vals must be monotonically increasing. """ assert min_idx >= 0 assert max_idx >= min_idx assert which in {"before", "after"} if min_idx == max_idx: return min_idx bound = min_idx # Walk forward until the target time is in the past. while bound < (max_idx if which == "before" else max_idx - 1): time_us = vals[bound] if time_us == -1 or time_us < target: bound += 1 else: break if which == "before": # If we walked forward, then walk backward to the last valid time. while bound > min_idx: bound -= 1 if vals[bound] != -1: break assert min_idx <= bound <= max_idx return bound
def enough(cap: int, on: int, wait: int) -> int: """ The driver wants you to write a simple program telling him if he will be able to fit all the passengers. If there is enough space, return 0, and if there isn't, return the number of passengers he can't take. You have to write a function that accepts three parameters: cap is the amount of people the bus can hold excluding the driver. on is the number of people on the bus. wait is the number of people waiting to get on to the bus. :param cap: :param on: :param wait: :return: """ if cap - on < wait: return wait - (cap - on) return 0
def record_to_data(record): """ :param record: 'cpu:7.5,foo:8' :return: """ data = {} for pair in record.split(','): elem = pair.split(':') data[elem[0]] = float(elem[1]) return data
def _write_file(filename: str, content: str, *, binary: bool = False) -> int: """Write a file with the given content.""" if binary: mode = "wb" encoding = None else: mode = "w" encoding = "utf-8" with open(filename, mode, encoding=encoding) as f: return f.write(content)
def compare_values(a, b): """A utility function to compare two values for equality, with the exception that 'falsy' values (e.g. None and '') are equal. This is used to account for differences in how data is returned from the different AD environments and APIs. """ if not a and not b: return True return a == b
def f(a, b, c): """only args a and b will be used to compute a hash of function inputs""" return a * b * c
def sample_to_orbit(sample: list) -> list: """Provides the orbit corresponding to a given sample. Orbits are simply a sorting of integer photon number samples in non-increasing order with the zeros at the end removed. **Example usage:** >>> sample = [1, 2, 0, 0, 1, 1, 0, 3] >>> sample_to_orbit(sample) [3, 2, 1, 1, 1] Args: sample (list[int]): a sample from GBS Returns: list[int]: the orbit of the sample """ return sorted(filter(None, sample), reverse=True)
def read_block(fd, block=4 * 1024): """Read up to 4k bytes from fd. Returns empty-string upon end of file. """ from os import read try: return read(fd, block) except OSError as error: if error.errno == 5: # pty end-of-file, sometimes: # http://bugs.python.org/issue21090#msg231093 return b'' else: raise
def count_change(amount): """Return the number of ways to make change for amount. >>> count_change(7) 6 >>> count_change(10) 14 >>> count_change(20) 60 >>> count_change(100) 9828 """ # Official sol def count_using_partition(min_coin, amount): if amount == 0: return 1 elif amount < 0 or min_coin > amount: return 0 else: # Exact approach as the one introduced in counting partitions with_min = count_using_partition(min_coin, amount - min_coin) without_min = count_using_partition(2 * min_coin, amount) return with_min + without_min return count_using_partition(1, amount)
def _indexing(x, indices): """ :param x: array from which indices has to be fetched :param indices: indices to be fetched :return: sub-array from given array and indices """ # np array indexing if hasattr(x, 'shape'): return x[indices] # list indexing return [x[idx] for idx in indices]
def split_stable_id(stable_id): """ Split stable id, returning: * Document (root) stable ID * Context polymorphic type * Character offset start, end *relative to document start* Returns tuple of four values. """ split1 = stable_id.split('::') if len(split1) == 2: split2 = split1[1].split(':') if len(split2) == 3: return split1[0], split2[0], int(split2[1]), int(split2[2]) raise ValueError("Malformed stable_id:", stable_id)
def _payload_check_(args, creation=False, cmd=None): """ Checks payload for correct JSON format for a given command. Args: args (dict): Pass in payload creation (bool): True if "create", false otherwise cmd (None or str): str if "Add...", None otherwise Returns: type: list containing bool or bool and str List with False or list with True and error message. False stands for do not terminate the process. """ if cmd != None: if "relation" not in args: return [True, "Relation missing."] elif "private_key" not in args: return [True, "Private-Key missing."] elif "public_key" not in args: return [True, "Public-Key missing."] elif "part_uuid" not in args["relation"]: return [True, "Part UUID missing."] elif "organization_uuid" not in args["relation"]: return [True, "Organization UUID missing."] else: return [False] else: if creation: if "organization" not in args: return [True, "Organization missing."] elif "private_key" not in args: return [True, "Private-Key missing."] elif "public_key" not in args: return [True, "Public-Key missing."] elif "uuid" not in args["organization"]: return [True, "UUID missing."] elif "alias" not in args["organization"]: return [True, "Alias missing."] elif "name" not in args["organization"]: return [True, "Name missing."] elif "type" not in args["organization"]: return [True, "Type missing."] elif "description" not in args["organization"]: return [True, "Description missing."] elif "url" not in args["organization"]: return [True, "URL missing."] else: return [False] else: if "organization" not in args: return [True, "Organization missing."] elif "private_key" not in args: return [True, "Private-Key missing."] elif "public_key" not in args: return [True, "Public-Key missing."] elif "uuid" not in args["organization"]: return [True, "UUID missing."] else: return [False]
def check_uniqueness_in_rows(board: list): """ Check buildings of unique height in each row. Return True if buildings in a row have unique length, False otherwise. >>> check_uniqueness_in_rows(['***21**', '412453*', '423145*', '*543215', \ '*35214*', '*41532*', '*2*1***']) True >>> check_uniqueness_in_rows(['***21**', '452453*', '423145*', '*543215', \ '*35214*', '*41532*', '*2*1***']) False >>> check_uniqueness_in_rows(['***21**', '412453*', '423145*', '*553215', \ '*35214*', '*41532*', '*2*1***']) False """ board = board[1:-1] for i in range(len(board)): board[i] = board[i][1:-1] board[i] = list(board[i]) for i in range(len(board)): board_set = set(board[i]) if len(board[i]) != len(board_set): return False return True
def belief_observation_model(o, b, a, T, O): """Returns the probability of Pr(o|b,a)""" prob = 0.0 for s in b: for sp in b: trans_prob = T.probability(sp, s, a) obsrv_prob = O.probability(o, sp, a) prob += obsrv_prob * trans_prob * b[s] return prob
def find(inp, success_fn): """ Finds an element for which the success_fn responds true """ def rec_find(structure): if isinstance(structure, list) or isinstance(structure, tuple): items = list(structure) elif isinstance(structure, dict): items = list(structure.items()) else: # Base case, if not dict or iterable success = success_fn(structure) return structure, success # If dict or iterable, iterate and find a tensor for item in items: result, success = rec_find(item) if success: return result, success return None, False return rec_find(inp)[0]
def dict_to_object(item): """ Recursively convert a dictionary to an object. """ def convert(item): if isinstance(item, dict): return type('DictToObject', (), {k: convert(v) for k, v in item.items()}) if isinstance(item, list): def yield_convert(item): for index, value in enumerate(item): yield convert(value) return list(yield_convert(item)) else: return item return convert(item)
def get_data_version(str_hash, hash_dict): """ Obtain version string from hash :param str_hash: Hash string to check :param hash_dict: Dictionary with hashes for different blocks :return: List with version string and hash string """ str_version = 'Not found' if 'versions' in hash_dict: hash_dict = hash_dict['versions'] for hash_elem in hash_dict: if str_hash == hash_dict[hash_elem]: str_version = hash_elem break return str_version
def check_number_of_index_tensor(data_shape, tuple_len, op_name): """Check if the number of index tensor exceeds the dimension of the operated tensor.""" if tuple_len <= len(data_shape): return True raise IndexError(f"For '{op_name}', the number {tuple_len} of index tensor " f"is greater than the dimension {len(data_shape)} of the operated tensor.")
def _val2col(val): """ Helper function to convert input value into a red hue RGBA """ nonred = abs(0.5-val)*2.0 return (1.0,nonred,nonred,1.)
def celcius2rankine(C): """ Convert Celcius to Fahrenheit :param C: Temperature in Celcius :return: Temperature in Fahrenheit """ return 9.0/5.0*C + 491.67
def multiply_something(num1, num2): """this function will multiply num1 and num2 >>> multiply_something(2, 6) 12 >>> multiply_something(-2, 6) -12 """ return(num1 * num2)
def dissolve(inlist): """ list and tuple flattening Parameters ---------- inlist: list the list with sub-lists or tuples to be flattened Returns ------- list the flattened result Examples -------- >>> dissolve([[1, 2], [3, 4]]) [1, 2, 3, 4] >>> dissolve([(1, 2, (3, 4)), [5, (6, 7)]]) [1, 2, 3, 4, 5, 6, 7] """ out = [] for i in inlist: i = list(i) if isinstance(i, tuple) else i out.extend(dissolve(i)) if isinstance(i, list) else out.append(i) return out
def convert_case(s): """ Given a string in snake case, convert to CamelCase Ex: date_created -> DateCreated """ return ''.join([a.title() for a in s.split("_") if a])
def backtrack2(f0, g0, x1, f1, b1=0.1, b2=0.5): """ Safeguarded parabolic backtrack Note for equation look to Nocedal & Wright, 2006 ?? :type f0: float :param f0: initial misfit function value :type g0: float :param g0: slope :type x1: float :param x1: step length value :type f1: float :param f1: current misfit function value (?) :type b1: float :param b1: constant for safeguard :type b2: float :param b2: constant for safeguard """ # Parabolic backtrack x2 = -g0 * x1 ** 2 / (2 * (f1 - f0 - g0 * x1)) # Apply safeguards if x2 > b2 * x1: x2 = b2 * x1 elif x2 < b1 * x1: x2 = b1 * x1 return x2
def percentage(part, whole): """Calculating the coverage of Acidobacteria reads from the set of sequences.""" return 100 * float(part)/float(whole)
def to_str(membership): """Convert membership array to pretty string. Example: >>> from graphy import partitions >>> print(partitions.to_str([0,0,0,1,1,1])) [0 0 0 1 1 1] Parameters ---------- membership : np.array or list Membership array to convert Returns ------- str Pretty string """ return "[" + " ".join(map(str, membership)) + "]"
def coalesce_permissions(role_list): """Determine permissions""" if not role_list: return set(), set() aggregate_roles = set() aggregate_perms = set() for role in role_list: aggregate_roles.add(role.name) aggregate_perms |= set(role.permissions) nested_roles, nested_perms = coalesce_permissions(role.roles) aggregate_roles |= nested_roles aggregate_perms |= nested_perms return aggregate_roles, aggregate_perms
def word_weight_cos_sim(word_weight_a, word_weight_b): """ Calculate cosine similarity with term weight Returns: cosine score """ word_weight_dict_a = {} word_weight_dict_b = {} for word, weight in word_weight_a: if word not in word_weight_dict_a: word_weight_dict_a[word] = 0.0 word_weight_dict_a[word] += weight for word, weight in word_weight_b: if word not in word_weight_dict_b: word_weight_dict_b[word] = 0.0 word_weight_dict_b[word] += weight norm_a = 0.0001 norm_b = 0.0001 for weight in word_weight_dict_a.values(): norm_a += weight ** 2 norm_a = norm_a ** (1. / 2) for weight in word_weight_dict_b.values(): norm_b += weight ** 2 norm_b = norm_b ** (1. / 2) product = 0.0 for k in set(word_weight_dict_a.keys()) & set(word_weight_dict_b.keys()): product += word_weight_dict_a[k] * word_weight_dict_b[k] return product / (norm_a * norm_b)
def px(cin, dpi=600): """Convert a dimension in centiinch into pixels. :param cin: dimension in centiinch :type cin: str, float, int :param dpi: dot-per-inch :type dpi: int """ return int(float(cin) * dpi / 100)
def label_parent(k, j): """ Return a label for a node given labels for its children :return: """ if j > k: k, j = j, k return k * (k-1) // 2 + j + 1
def format_grouped_plot_data(plot_data: list, group_field, trend_field): """Function to format raw grouped aggregated time series""" grouped_plottdata = {} for datapoint in plot_data: group = datapoint["_id"][group_field] month = datapoint["_id"]["month"] trend_value = datapoint[trend_field] if group in grouped_plottdata: grouped_plottdata[group][trend_field].append(trend_value) grouped_plottdata[group]["month"].append(month) continue grouped_plottdata[group] = {trend_field: [trend_value], "month": [month], "group": group} return [value for group, value in grouped_plottdata.items()]
def application_error(e): """Return a custom 500 error.""" return 'Sorry, unexpected error: {}'.format(e), 500
def replace_f_stop(in_exp, f): """Like replace_f, but the function returns None when no replacement needs to be made. If it returns something we replace it and stop.""" modified_in_exp = f(in_exp) if modified_in_exp is not None: return modified_in_exp if type(in_exp) not in (tuple, list): return in_exp res = tuple() for e in in_exp: res += (replace_f_stop(e, f),) if type(in_exp) == list: res = list(res) return res
def cobs_decode(data): """ Decode COBS-encoded DATA. """ output = bytearray() index = 0 while index < len(data): block_size = data[index] - 1 index += 1 if index + block_size > len(data): return bytearray() output.extend(data[index:index + block_size]) index += block_size if block_size + 1 < 255 and index < len(data): output.append(0) return output
def _Percent(risk): """Converts a float to a percent. Args: risk: A probability. Returns: A string percent. """ return '{:0.1f}%'.format(risk * 100)
def _MakeIeee64(sign, mantissa4bit, exponent) -> int: """convert the 3 components of an 8bit a64 float to an ieeee 64 bit float""" assert 0 <= exponent <= 7 assert 0 <= mantissa4bit <= 15 return (sign << 63) | ((exponent - 3 + 1023) << 52) | (mantissa4bit << 48)
def calc(directie, valoare): """Adauga""" pozitie_pcty = 0 pozitie_pctx = 0 if directie == "SUS": pozitie_pcty += valoare if directie == "JOS": pozitie_pcty -= valoare if directie == "STANGA": pozitie_pctx -= valoare if directie == "DREAPTA": pozitie_pctx += valoare return float(pozitie_pctx), float(pozitie_pcty)
def in_range(value, min_value, max_value): """ Clamps a value to be within the specified range. If the value is None then None is returned. If either max_value or min_value are None they aren't used. :param value: The value :param min_value: Minimum allowed value :param max_value: Maximum allowed value """ if value is None: return None elif value < min_value and min_value is not None: return min_value elif value > max_value and max_value is not None: return max_value return value
def CommaJoin(names): """Nicely join a set of identifiers. @param names: set, list or tuple @return: a string with the formatted results """ return ", ".join([str(val) for val in names])
def get_fhir_type_name(type_): """ """ try: return type_.fhir_type_name() except AttributeError: if type_ is bool: return "boolean" type_str = str(type_) if ( type_str.startswith("typing.Union[") and "fhirtypes.FHIRPrimitiveExtensionType" in type_str ): return "FHIRPrimitiveExtension" raise
def getConnectString(user, password, host, port, database): """ Gets a connection string to establish a database connection. """ return user + "/" + password + "@//" + host + ":" + port + "/" + database
def float_parameter(level, maxval): """Helper function to scale `val` between 0 and maxval. Args: level: Level of the operation that will be between [0, `PARAMETER_MAX`]. maxval: Maximum value that the operation can have. This will be scaled to level/PARAMETER_MAX. Returns: A float that results from scaling `maxval` according to `level`. """ return float(level) * maxval / 10.
def lsof_tcp_listening_cmd(port, ipv, state, terse): """Return a command line for lsof for processes with specified TCP state.""" terse_arg = '' if terse: terse_arg = '-t' return 'lsof -b -P -n %s -sTCP:%s -i %u -a -i tcp:%u' % ( terse_arg, state, ipv, port)
def deep_update(a, b): """deep version of dict.update()""" for key in b: if key in a: if isinstance(a[key], dict) and isinstance(b[key], dict): deep_update(a[key], b[key]) elif a[key] == b[key]: pass else: a[key] = b[key] else: a[key] = b[key] return a
def handle_file(file: str, file_name: str): """ Copies the file to clipboard by saving it to a temporary directory and then copying it :param file: The file :param file_name: The filename :return: response for the request """ print(file, file_name) # config = Config.get_config() # if config.config.getboolean("CLIPBOARD", "notification", fallback=True): # notify("Copied File to clipboard: \"{}\"".format(filename)) # return {"success": True} return {"message": "Copying files to clipboard is not yet implemented"}
def summerA(n: int) -> int: """ A naive solution. Iterates over every positive integer below the bound. """ total = 0 for i in range(n): if (i % 3 == 0) or (i % 5 == 0): total += i return total
def show_price(price: float) -> str: """ >>> show_price(1000) '$ 1,000.00' >>> show_price(1_250.75) '$ 1,250.75' """ return "$ {0:,.2f}".format(price)
def boolmask(indices, maxval=None): """ Constructs a list of booleans where an item is True if its position is in ``indices`` otherwise it is False. Args: indices (List[int]): list of integer indices maxval (int): length of the returned list. If not specified this is inferred using ``max(indices)`` Returns: List[bool]: mask - a list of booleans. mask[idx] is True if idx in indices Note: In the future the arg ``maxval`` may change its name to ``shape`` Example: >>> import ubelt as ub >>> indices = [0, 1, 4] >>> mask = ub.boolmask(indices, maxval=6) >>> assert mask == [True, True, False, False, True, False] >>> mask = ub.boolmask(indices) >>> assert mask == [True, True, False, False, True] """ if maxval is None: indices = list(indices) maxval = max(indices) + 1 mask = [False] * maxval for index in indices: mask[index] = True return mask
def guess_type(value): """ attempt to convert string value into numeric type """ num_value = value.replace(',', '') # remove comma from potential numbers try: return int(num_value) except ValueError: pass try: return float(num_value) except ValueError: pass return value
def modular_inverse(a, m): """Compute Modular Inverse.""" def egcd(a, b): """Extended Euclidian Algorithm.""" # Explained here: https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm # if a == 0: return (b, 0, 1) else: g, y, x = egcd(b % a, a) return (g, x - (b // a) * y, y) # Modular inverse of x mod m is the number x^-1 such that # x * x^-1 = 1 mod m # g, x, _ = egcd(a, m) if g != 1: raise Exception(f'modular inverse ({a}, {m}) does not exist') else: return x % m
def get_root(notes): """ returns the most common value in the list of notes :param notes: notes in standard notation :return: single note in standard notation """ return max(set(notes), key=notes.count)
def _format_eval_result(value, show_stdv=True): """Format metric string.""" if len(value) == 4: return f"{value[0]}'s {value[1]}: {value[2]:.4f}" elif len(value) == 5: if show_stdv: return f"{value[0]}'s {value[1]}: {value[2]:.4f} + {value[4]:.4f}" else: return f"{value[0]}'s {value[1]}: {value[2]:.4f}" else: raise ValueError("Wrong metric value")
def most_frequent(fills): """Find most frequent element in array""" if len(fills) > 0: return max(set(fills), key=fills.count) else: return ''
def keyword_cipher_decryptor(key: str, encrypted_message: str) -> str: """Decrypts a message which has been encrypted using a Keyword Cipher. Args: encrypted_message (str): Message to be decrypted. key (str): Keyword. Returns: decrypted_message (str): Decrypted message. """ # Remove duplicate characters in key key = "".join(dict.fromkeys(key)) # Create string of lowercase characters chars = "".join([chr(char) for char in range(97, 123)]) # Create cipher key for char in chars: if char not in key: key += char index_values = [key.index(char) for char in encrypted_message] decrypted_message = "".join(chars[index] for index in index_values) return decrypted_message
def scale(value): """Scale an value from 0-65535 (AnalogIn range) to 0-255 (RGB range)""" return int(value / 65535 * 255)
def not_radical(cgr): """ Checking for charged atoms in a Condensed Graph of Reaction. :param cgr: Condensed Graph of the input reaction :return: bool """ if cgr and cgr.center_atoms: if any(x.is_radical or x.p_is_radical for _, x in cgr.atoms()): return False return True
def get_ip(conn): """Return the primary IP of a network connection.""" ipcfg = conn.get('ipConfig') if not ipcfg: return stcfg = ipcfg.get('staticIpConfig') aucfg = ipcfg.get('autoIpConfig') if stcfg: return stcfg.get('ip') elif aucfg: ip = aucfg.get('allocatedIp') if ip is None: ip = aucfg.get('reservedIp') return ip
def analysis_vrn(analysis): """ Returns a dictionary of Vars by row. This index can be used to quicky find a Var definition by row. 'vrn' stands for 'var row name'. """ return analysis.get("vrn", {})
def csv_int2hex(val): """ format CAN id as hex 100 -> 64 """ return f"{val:X}"
def move(face, row, col): """Returns the updated coordinates after moving forward in the direction the virus is facing""" if face == 'N': row, col = row - 1, col elif face == 'S': row, col = row + 1, col elif face == 'E': row, col = row, col + 1 elif face == 'W': row, col = row, col - 1 return row, col
def convert_color_class(class_label_colormap,c): """ color to class """ return class_label_colormap.index(c)
def reverse(string): """ @param Input: Given String @return Output: Reversed String """ return string[::-1]
def in_cksum_done(s): """Fold and return Internet checksum.""" while (s >> 16): s = (s >> 16) + (s & 0xffff) return (~s & 0xffff)
def has_parameters(line): """ Checks if the first word of the text has '(' attached to it. If it's attached, the command has parameters. """ for char in list(line): if char == "(": return True if not (char.isalnum() or char == "@" or char == "^"): return False return False
def parse_encode_donor(data): """Parse a python dictionary containing ENCODE's donor metadata into a dictionary with select donor metadata :param data: python dictionary containing ENCODE' donor metadata :type s: dict :return: dictionary with parsed ENCODE's donor metadata :rtype: dict """ keys_donor = ['accession', 'dbxrefs', 'organism', 'sex', 'life_stage', 'age', 'age_units', 'health_status', 'ethnicity'] donor = {key: data.get(key, '') for key in keys_donor} return donor
def string(s): """ Convert a string to a escaped ASCII representation including quotation marks :param s: a string :return: ASCII escaped string """ ret = [] for c in s: if ' ' <= c < '\x7f': if c == "'" or c == '"' or c == '\\': ret.append('\\') ret.append(c) continue elif c <= '\x7f': if c in ('\r', '\n', '\t'): # unicode-escape produces bytes ret.append(c.encode('unicode-escape').decode("ascii")) continue i = ord(c) ret.append('\\u') ret.append('%x' % (i >> 12)) ret.append('%x' % ((i >> 8) & 0x0f)) ret.append('%x' % ((i >> 4) & 0x0f)) ret.append('%x' % (i & 0x0f)) return ''.join(ret)
def solution(A): """ Complexity - n long n Codility - https://app.codility.com/demo/results/trainingUV284M-WFD/ 100% Idea is to sort the array and check for triplet condition P<=Q<=R 5 8 10 i i+1 i+2 i plus, i+1 > i+2 ie. P+Q > R 5 plus 8 > 10 8+10 > 5 - always true - due to sorted 10+5 > 8 - always true - due to sorted :param A: :return: total counts """ # sort the array A.sort() print(A) # check for all the pairs for index in range(len(A) - 2): if A[index] + A[index + 1] > A[index + 2]: return 1 return 0
def isfloat(value): """ Checks if it is float. As seen in: http://stackoverflow.com/a/20929983 """ try: float(value) return True except ValueError: return False
def get_countN(x,n): """Count the number of nucleotide n in the string.""" return x.upper().count(n.upper())
def _gcd(a : int, b: int) -> int: """Returns GCD(a, b), such that 'a' must always be greater than 'b'. """ if b == 0: return a return _gcd(b, a % b)
def quote(s: str) -> str: """ Quotes the '"' and '\' characters in a string and surrounds with "..." """ return '"' + s.replace('\\', '\\\\').replace('"', '\\"') + '"'
def split_c(c, split_id): """ Split c is a list, example context split_id is a integer, conf[_EOS_] return nested list """ turns = [[]] for _id in c: if _id != split_id: turns[-1].append(_id) else: turns.append([]) if turns[-1] == [] and len(turns) > 1: turns.pop() return turns
def emirp(number) -> bool: """Takes a number as input and checks if the given number is emirp or not.""" c = 1 for i in range(1, number): if(number % i == 0): c += 1 if(c <= 2): n = 0 while number > 0: d = number % 10 n = n*10+d number //= 10 c = 1 for i in range(1, n): if(n % i == 0): c += 1 return True if(c <= 2) else False else: return False
def parse_header(data: str) -> tuple: """Parse header, return column names.""" return tuple(data.rstrip('\n').split('\t'))
def onbits(b): """ Count number of on bits in a bitmap """ return 0 if b==0 else (1 if b&1==1 else 0) + onbits(b>>1)
def join_base_url_and_query_string(base_url: str, query_string: str) -> str: """Joins a query string to a base URL. Parameters ---------- base_url: str The URL to which the query string is to be attached to. query_string: str A valid query string. Returns ------- str The base url with attached the query string. """ if base_url.endswith("/"): base_url = base_url[:-1] return f"{base_url}?{query_string}"
def nested_sum(t): """Takes a list of lists of integers and returns sum of all their elements""" total = 0 for item in t: total += sum(item) return total
def sigma_thermpollution_dist(pollution_1_dist, pollution_2_dist, sigma, lyambda_wall): """ Calculates the sum of thermal pollutions. Parameters ---------- pollution_1_dist : float The thermal pollution of the first coolant, [m**2 * degrees celcium / W] pollution_2_dist : float The thermal pollution of the second coolant, [m**2 * degrees celcium / W] sigma : float The thickness of pipe wall, [m] lyambda_wall : float The thermal conducivity of wall, [W / (m * degrees celcium)] Returns ------- sigma_thermpollution_dist : float The the sum of thermal pollutions, [m**2 * degrees celcium / W] References ---------- &&&&& """ return (sigma / lyambda_wall) + (1 / pollution_1_dist) + (1 / pollution_2_dist)