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+m...
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) botto...
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_')\ ...
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 g...
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'...
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) ...
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.""" ...
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...
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...
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: ...
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...
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(c...
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...
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] >>> sampl...
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.pytho...
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: ...
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...
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: ...
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: ...
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 >>> che...
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()) ...
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): ...
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: ...
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"i...
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] ...
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 ...
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 ------- ...
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, nest...
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]...
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[tre...
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)...
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])...
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 += v...
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_valu...
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" i...
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 re...
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...
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() #...
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 inferr...
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 ...
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...
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: retur...
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. """...
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') ...
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': ...
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...
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: dic...
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('\\') ...
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 - alway...
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(tu...
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 num...
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 ...
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 T...