content
stringlengths
42
6.51k
def str_trunc_end(S, L): """Returns a possibly truncated S (ellipsis added at the string's ending) if the length of S is greater than L. L should be equal to or greater than 3 to be making sense.""" if len(S) > L: return S[:max(L-3,0)] + "..." else: return S
def bisection_test_function(x): """Get test function for bisection.""" return x ** 3 - 2
def chop_list(lst, chop_length, filler=None): """Chops a list into a list of lists. Used to generate a plate map corresponding to microplate layouts. Parameters ---------- lst: list The original list that needs to be chopped up chop_length: Int The length of the pieces to chop the big list into filler: Int, optional The stuff to fill up the leftover pieces Returns ------- List Returns the correct well indices of all the quad-specific wells in quadwells """ assert chop_length > 0 ret = [] row_idx = 0 while True: # extract next chunk from input list row = lst[row_idx * chop_length:(row_idx + 1) * chop_length] row_idx += 1 row_len = len(row) # list length was integer multiple of chop_length if row_len == 0: return ret # still in the middle of the list elif row_len == chop_length: ret.append(row) # end of list, but last row needs filling up else: ret.append(row + [filler] * (chop_length - row_len)) return ret return ret
def get_interface_type(interface): """Gets the type of interface, such as 10GE, ...""" if interface is None: return None iftype = None if interface.upper().startswith('GE'): iftype = 'ge' elif interface.upper().startswith('10GE'): iftype = '10ge' elif interface.upper().startswith('25GE'): iftype = '25ge' elif interface.upper().startswith('40GE'): iftype = '40ge' elif interface.upper().startswith('100GE'): iftype = '100ge' elif interface.upper().startswith('PORT-GROUP'): iftype = 'stack-Port' elif interface.upper().startswith('NULL'): iftype = 'null' else: return None return iftype.lower()
def average(iterable, start=None, transform=None): """ Returns the average, or None if there are no elements """ if len(iterable): if start is not None: addition = sum(iterable, start) else: addition = sum(iterable) if transform: addition = transform(addition) return addition / float(len(iterable)) else: return None
def _rename(table_text): """Rename columns""" table_text = table_text.replace('Gene stable ID', 'GeneID', 1) table_text = table_text.replace('Transcript stable ID', 'TranscriptID', 1) table_text = table_text.replace('Protein stable ID', 'ProteinID', 1) table_text = table_text.replace('Exon stable ID', 'ExonID', 1) table_text = table_text.replace('Exon region start (bp)', 'ExonRegionStart', 1) table_text = table_text.replace('Exon region end (bp)', 'ExonRegionEnd', 1) table_text = table_text.replace('Exon rank in transcript', 'ExonRank', 1) table_text = table_text.replace('cDNA coding start', 'cDNA_CodingStart', 1) table_text = table_text.replace('cDNA coding end', 'cDNA_CodingEnd', 1) table_text = table_text.replace('Genomic coding start', 'GenomicCodingStart', 1) table_text = table_text.replace('Genomic coding end', 'GenomicCodingEnd', 1) table_text = table_text.replace('Start phase', 'StartPhase', 1) table_text = table_text.replace('End phase', 'EndPhase', 1) return table_text
def string_unquote(value: str): """ Method to unquote a string Args: value: the value to unquote Returns: unquoted string """ if not isinstance(value, str): return value return value.replace('"', "").replace("'", "")
def getopts(argv): """Collect command-line options in a dictionary""" opts = {} # Empty dictionary to store key-value pairs. while argv: # While there are arguments left to parse... if argv[0][0] == '-': # Found a "-name value" pair. opts[argv[0]] = argv[1] # Add key and value to the dictionary. argv = argv[1:] # Reduce the argument list by copying it starting from index 1. return opts
def detection_fruit(classe, prediction): """ This function analyses the list of prediction and return a consolidation of the predictions done Args: ----- - classe : list of classes - prediction : list of predictions Returns: -------- - fruit """ nb_predicted_images = len(prediction) nb_fruit = len(classe) list_nb_indexes = [prediction.count(x) for x in range(-1, nb_fruit)] list_nb_fruit = list_nb_indexes[1:nb_fruit+1] fruit = list_nb_fruit.index(max(list_nb_fruit)) nb_max = list_nb_fruit[fruit] if nb_max > (nb_predicted_images / 10): result = fruit else: result = -1 return result
def find_difference(left: dict, right: dict) -> dict: """Accepts two dicts with list values. Check which items are present in left but not in right, similar to set difference. Args: left (dict): Dict with list values right (dict): Dict with list values Returns: dict: Dict with list values. Contains items in left but not in right """ diff = {} # Empty dict to store differences for key, values in left.items(): if key in right.keys(): right_values = [v for v in right[key]] diff[key] = set(values).difference( set(right_values) ) else: # If key doesn't exist in right, all values are new diff[key] = left[key] diff = {k:v for k,v in diff.items() if len(v) > 0} # Remove empty return diff
def check_valid_attribute_req_dict(iterable, d): """Check if iterable all of any elements in an iterable are in a dict""" return any((i in d if not isinstance(i, tuple) else (all(sub_i in d for sub_i in i))) for i in iterable)
def run_on_nested_arrays2(a, b, func, **param): """run func on each pair of element in a and b: a and b can be singlets, an array, an array of arrays, an array of arrays of arrays ... The return value is a flattened array """ if isinstance(a, list): if not isinstance(b, list): raise Exception("can't combine list and non-list") if len(a) != len(b): raise Exception("Can't combine lists of different lengths") return([run_on_nested_arrays2(a_, b_, func, **param) for a_, b_ in zip(a, b)]) else: return(func(a, b, **param))
def func_args(arg_values, arg_names): """ Convert args and arg_names into positional args and keyword args. """ posargs = [] kwargs = {} for i, name in enumerate(arg_names): value = arg_values[i] if name is not None: kwargs[name] = value else: posargs.append(value) return posargs, kwargs
def apply_move(board_state, move, side): """Returns a copy of the given board_state with the desired move applied. Args: board_state (2d tuple of int): The given board_state we want to apply the move to. move (int, int): The position we want to make the move in. side (int): The side we are making this move for, 1 for the first player, -1 for the second player. Returns: (2d tuple of int): A copy of the board_state with the given move applied for the given side. """ move_x, move_y = move def get_tuples(): for x in range(len(board_state)): if move_x == x: temp = list(board_state[x]) temp[move_y] = side yield tuple(temp) else: yield board_state[x] return tuple(get_tuples())
def iou(box1, box2): """Finds overlap of two bounding boxes""" xmin = max(box1[0], box2[0]) ymin = max(box1[1], box2[1]) xmax = min(box1[2], box2[2]) ymax = min(box1[3], box2[3]) if xmin >= xmax or ymin >= ymax: return 0 box1area = (box1[2] - box1[0]) * (box1[3] - box1[1]) box2area = (box2[2] - box2[0]) * (box2[3] - box2[1]) intersection = (xmax - xmin) * (ymax - ymin) union = box1area + box2area - intersection return intersection / union
def validate(data): """ Validate the input data for account creation Parameters: ---------- data:{'name':'', 'secret':0, 'balance':0} Returns: ----------- Boolean """ must_keys = ['name', 'secret', 'balance'] return ( len(data) == len(must_keys) and all(key in data for key in must_keys) and len(data.get('name')) > 1 and len(str(data.get('secret'))) == 4 and isinstance(data.get('secret'), int) and (isinstance(data.get('balance'), int) or isinstance(data.get('balance'), float)) )
def cmp(a, b): """Python 2 & 3 version of cmp built-in.""" return (a > b) - (a < b)
def __create_dict_entry(key: str, value: str) -> str: """ Creates a dict entry in for of a string: {'key': value} Args: key (str): key of entry value (str): value of entry Returns (str): dict entry """ return f'\'{key}\': {value},'
def euler(dydx, x0, y0, x, h): """ Euler Method for solving diferential equations Parameters: dydx: Diferential equation x0: Initial x y0: Initial y x: Value of X h: Height Returns: y: Aproximation of y """ y = y0 while x0 < x: y = y + h * dydx(x0, y) print(y) x0 = x0 + h return y
def escape_generic_filter_value(anything: str) -> str: """ Escape anything, so that it can be used in ldap queries without confusing the server. According to the LDAP spec, there's a set of common characters that need escaping: rfc4514 (https://tools.ietf.org/html/rfc4514). RFCs that define new LDAP attributes, as well different server types, may require additional characters be escaped. Additionally, not all characters need to be escaped. For example, many versions of AD do not require commas be escaped, but will be ok if they are. Please ensure you know what you're escaping before calling this. See escape_dn_for_filter for an example of an alternative escape function needed to escape a field with different properties. """ if anything.isalnum(): return anything def escape_char(char): """ Escape a single character.""" if char in "*()\\/\0 \t\r\n+<>,\";": # LDAP query language is really forgiving about strange characters. # rfc2254 says the only characters to escape are "*{}\\\0". AD adds "/" to the # list, and OpenLDAP adds whitespace. Over-escaping is safe, so just do everything # every time. return "\\%02x" % ord(char) else: return char return "".join(escape_char(x) for x in anything)
def round_filters(filters, width_coefficient, depth_divisor, min_depth): """Round number of filters based on depth multiplier.""" multiplier = float(width_coefficient) divisor = int(depth_divisor) min_depth = min_depth if not multiplier: return filters filters *= multiplier min_depth = min_depth or divisor new_filters = max(min_depth, int(filters + divisor / 2) // divisor * divisor) # Make sure that round down does not go down by more than 10%. if new_filters < 0.9 * filters: new_filters += divisor return int(new_filters)
def list_equals(list1, list2): """Compares two lists""" list1.sort() # might bug if some subjs are numeric, other alpha numeric. We suppose all alphanumeric? list2.sort() return list1 == list2
def scaling(dt, amplitude, dx): """Calculate scaling factor for integrated entropy from dt, amplitude, dx Args: dt (float): The difference in theta of hot and cold (in units of plunger gate). Note: Using lock-in dT is 1/2 the peak to peak, for Square wave it is the full dT amplitude (float): The amplitude of charge transition from the CS dx (float): How big the DAC steps are in units of plunger gate Note: Relative to the data passed in, not necessarily the original x_array Returns: float: Scaling factor to multiply cumulative sum of data by to convert to entropy """ return dx / amplitude / dt
def coerce_input_to_str(data): """ Coerce url data to a comma separated string. e.g. ['a','b'] becomes 'a,b' while 'c,d' is unchanged. :param data: Input data to coerce. :type data: str, list, tuple :return: Joined string. :rtype: str """ if isinstance(data, str): return data elif isinstance(data, (list, tuple)): return ",".join(data) raise ValueError(f"{data} is not a valid input.")
def get_gradient_index(val, min_val, max_val, steps): """ Returns the index in gradient given p-value, minimum value, maximum value and number of steps in gradient. >>> get_gradient_index(0.002, 0.001, 0.0029, 10) 5 >>> get_gradient_index(0.0011, 0.001, 0.0029, 10) 0 >>> get_gradient_index(0.002899999, 0.001, 0.0029, 10) 9 >>> get_gradient_index(0.0029, 0.001, 0.0029, 10) 9 >>> get_gradient_index(0.001, 0.001, 0.001, 10) 0 """ if max_val == min_val: return 0 else: d = (max_val - min_val) / steps r = int((val - min_val) / d) return r if r < steps else r - 1
def _canonize_validator(current_validator): """ Convert current_validator to a new list and return it. If current_validator is None return an empty list. If current_validator is a list, return a copy of it. If current_validator is another type of iterable, return a list version of it. If current_validator is a single value, return a one-list containing it. """ if not current_validator: return [] if isinstance(current_validator, (list, tuple)): current_validator = list(current_validator) else: current_validator = [current_validator] return current_validator
def replace_string_in_list(str_list: list, original_str: str, target_str: str): """ Replace a string in a list by provided string. Args: str_list (list): A list contains the string to be replaced. original_str (str): The string to be replaced. target_str (str): The replacement of string. Returns, list, the original list with replaced string. """ return [s.replace(original_str, target_str) for s in str_list]
def index_users_by_group(users): """ Create an index of all users by their groups. Some users will appear multiple times depending on the groups they are assigned. """ index = {} for user in users: for group in user.get("groups", []): index.setdefault(group, []) index[group].append(user) for group_name, user_group in index.items(): user_group.sort(key=lambda user: (user.get("name") or "").upper()) return index
def _extract_batch_length(preds): """Extracts batch length of predictions.""" batch_length = None for key, value in preds.items(): this_length = ( len(value) if isinstance(value, (list, tuple)) else value.shape[0]) batch_length = batch_length or this_length if this_length != batch_length: raise ValueError('Batch length of predictions should be same. %s has ' 'different batch length than others.' % key) return batch_length
def magnitude(vector): """ get magnitude (length) of vector """ return (vector[0]**2 + vector[1]**2 + vector[2]**2) ** .5
def sign(n): """ Get sign multiplicand: 1 if n >= 0, -1 if n < 0 """ return 1 if n >= 0 else -1
def parse_int_input(s: str) -> list: """ Transforms '12345' -> [1, 2, 3, 4, 5] Raises errors on invalid input. Ex: '12a45' -> Error """ try: row = [int(v) for v in s] return row except: raise
def city_code(city): """ :param city: city is a custom slot type in the alexa skill configuration possible values are: Helsinki Helsingfors Espoo Esbo Vantaa Vanda Kauniainen Grankulla :return: a short code is in HSL bus stops. "" for Helsinki, "E" for Espoo "V" for Vantaa and "Ka" for Kauniainen """ lc_city = city.lower() if lc_city == "helsinki" or lc_city == "helsingfors": return "" elif lc_city == "espoo" or lc_city == "esbo": return "E" elif lc_city == "vantaa" or lc_city == "vanda": return "V" elif lc_city == "kauniainen" or lc_city == "grankulla": return "Ka" else: # silently default to Helsinki return ""
def remove_bracket(text): """remove contents in the brackets <>""" n = len(text) flag = True # copy or skip text2 = '' # loop over to copy or skip characters inside '<>' i = 0 while i < n: if flag: if text[i] != '<': text2 += text[i] else: flag = False else: if text[i] == '>': flag = True i += 1 # remove '(())' text2 = text2.replace('(())','') # remove redundant spaces text2 = ' '.join(text2.strip().split()) return text2
def productExceptSelf2(nums): """ :type nums: List[int] :rtype: List[int] """ n = len(nums) output = [0] * n p = 1 for idx, val in enumerate(nums): output[idx] = p p *= val p = 1 for idx in range(n - 1, -1, -1): output[idx] *= p p *= nums[idx] return output
def coord_char(coord, matrix): """Return the element of matrix at specified coord. Args: coord (tuple): A coordinate in the matrix with (row, column) format. matrix (list): A list containing lines of string. Returns: str: Returns the string located in the matrix coord. """ row_index, column_index = coord return matrix[row_index][column_index]
def string_or_float(cell_value): """Takes the input value from an ATable cell and returns either its float value or its string value. In the latter case, one level of surrounding ' or " is removed from the value before returning. """ try: v = float(cell_value) except ValueError: v = str(cell_value) v = v.strip() if (v.startswith("'") and v.endswith("'")) \ or (v.startswith('"') and v.endswith('"')): v = v[1:-1] return v
def Cm(poisson, young): """ Uniaxial compaction coefficient Cm. """ result = ((1+poisson)*(1-2*poisson))/(young*(1-poisson)) return result
def get_missing_file_error(marker_type, playbook): """ Generate error message for empty marker. """ msg = ( "no file is specified in " "``@pytest.mark.ansible_playbook_{0}`` decorator " "for the playbook - ``{1}``") return msg.format(marker_type, playbook)
def encode_msg(type, data): """ compresses type and data into a single integer at least 1 byte large. params: type: 8 bit integer representing the type of the message. data: data of the message as list of bytes. """ encoded_bytes = [type] + data # num_data_bytes = len(data) # encoded = type << (8 * num_data_bytes) # for idx, val in enumerate(data): # encoded += val << (8 * (num_data_bytes - idx - 1)) encoded = int.from_bytes(encoded_bytes, byteorder='big') return encoded
def html_to_float(c): """ Convert a HTML hex color to a Red-Green-Blue (RGB) tuple. INPUT: - ``c`` - a string; a valid HTML hex color OUTPUT: - a RGB 3-tuple of floats in the interval [0.0, 1.0] EXAMPLES:: sage: from sage.plot.colors import html_to_float sage: html_to_float('#fff') (1.0, 1.0, 1.0) sage: html_to_float('#abcdef') (0.6705882352941176, 0.803921568627451, 0.9372549019607843) sage: html_to_float('#123xyz') Traceback (most recent call last): ... ValueError: invalid literal for int() with base 16: '3x' """ if not len(c) or c[0] != '#': raise ValueError("'%s' must be a valid HTML hex color (e.g., '#f07' or '#d6e7da')" % c) h = c[1:] if len(h) == 3: h = '%s%s%s%s%s%s' % (h[0], h[0], h[1], h[1], h[2], h[2]) elif len(h) != 6: raise ValueError("color hex string (= '%s') must have length 3 or 6" % h) return tuple([int(h[i:i + 2], base=16) / 255 for i in [0, 2, 4]])
def create_msg(q1,q2,q3): """ Converts the given configuration into a string of bytes understood by the robot arm. Parameters: q1: The joint angle for the first (waist) axis. q2: The joint angle for the second (shoulder) axis. q3: The joint angle for the third (wrist) axis. Returns: The string of bytes. """ return ('%d,%d,%d\n' % (q1,q2,q3)).encode()
def not_junk(line): """Return False on newlines and C-style comments.""" return line[0] != '#' and line != '\n'
def say(num: int): """ Convert large number to sayable text format. Arguments: num : A (large) number """ under_20 = [ "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen", ] tens = [ "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety", ] above_100 = { 100: "hundred", 1000: "thousand", 1000000: "million", 1000000000: "billion", } if num < 20: return under_20[num] if num < 100: return tens[(int)(num / 10) - 2] + ( "" if num % 10 == 0 else " " + under_20[num % 10] ) # find the appropriate pivot - 'Million' in 3,603,550, or 'Thousand' in 603,550 pivot = max([key for key in above_100.keys() if key <= num]) return ( say((int)(num / pivot)) + " " + above_100[pivot] + ("" if num % pivot == 0 else " " + say(num % pivot)) )
def parse_vertex_and_square_ids( data: str, start_string: str = "Square ID", end_string: str = "# Edges", ) -> dict: """Return a dictionary of vertex ID & square ID pairs. This function will parse through the read-in input data between ''start_string'' and ''end_string'' to return the filtered text in-between. This text is then converted to a dictionary mapping vertex IDs to square IDs. :param data: read-in input file :type data: str :param start_string: starting string to search from, defaults to 'Square ID' :type start_string: str :param end_string: ending string to search until, defaults to '# Edges' :type end_string: str :return: a dictionary of vertex IDs & corresponding square IDs :rtype: dict """ # split the data on the two strings list_of_ids = data.split(start_string)[-1].split(end_string)[0] # split the data on newline character list_of_ids = list_of_ids.split("\n") # remove empty strings that arose due to whitespace by using filter list_of_ids = list(filter(lambda x: x != "", list_of_ids)) # create a dictionary of key-value pairs by splitting on the comma character ids_map = {} for i in list_of_ids: splitted_string = i.split(",") vertex_id = splitted_string[0] square_id = int(splitted_string[1]) # create a mapping ids_map[vertex_id] = square_id return ids_map
def gen_items(n_items): """"Function used in yt_dl to generate the string of indices corresponding to the desired number of items to be downloaded.""" items = '1' for ii in range(2,n_items): items = '{},{}'.format(items, ii) items = '{},{}'.format(items, n_items) return items
def slugify(value): """ Turns 'My Title' into 'My_Title' """ return value.replace(' ', '_')
def command_line_for_tool(tool_dict, output): """ Calculate the command line for this tool when ran against the output file 'output'. """ proc_args = [tool_dict['tool']] + tool_dict['args'](output) return proc_args
def get_length_of_phone(phone): """check length of phone number for validity Type(int) is already coded into html input""" if len(phone) == 10: return True else: return False
def fibonacci(n): """ object: fibonacci(n) returns the first n Fibonacci numbers in a list input: n- the number used to calculate the fibonacci list return: retList- the fibonacci list """ if type(n) != int: print(n) print(":input not an integer") return False if n <= 0: print(str(n)+"not a postive integer") return False f1=1 f2=1 retList=[] for i in range (0,n): retList.append(f1) fn=f1+f2 f1=f2 f2=fn return retList
def _read_exact(read, size): """ Read exactly size bytes with `read`, except on EOF :Parameters: - `read`: The reading function - `size`: expected number of bytes :Types: - `read`: ``callable`` - `size`: ``int`` :return: The read bytes :rtype: ``str`` """ if size < 0: return read(size) vlen, buf = 0, [] push = buf.append while vlen < size: val = read(size - vlen) if not val: break vlen += len(val) push(val) return "".join(buf)
def compute_reward(height): """ Computes the block reward for a block at the supplied height. See: https://en.bitcoin.it/wiki/Controlled_supply for the reward schedule. Args: height (int): Block height Returns: reward (int): Number of satoshis rewarded for solving a block at the given height. """ base_subsidy = 50 * 100000000 era = height // 210000 if era == 0: return base_subsidy return int(base_subsidy / 2 ** era)
def decimal(n): """Return a list representing the decimal representation of a number. >>> decimal(55055) [5, 5, 0, 5, 5] >>> decimal(-136) ['-', 1, 3, 6] """ if (n>0): if (n<10): return [n] else: return decimal(n//10)+ [n%10] else: n=n*(-1) if (n<10): return [n] else: return ['-']+decimal(n//10)+ [n%10]
def get_metrics(response): """ Extract asked metrics from api response @list_metrics : list of dict """ list_metrics = [] for i in response['reports'][0]['columnHeader']['metricHeader']['metricHeaderEntries']: list_metrics.append(i['name']) return list_metrics
def strip_decorator( text, pre_decor='"', post_decor='"'): """ Strip initial and final character sequences (decorators) from a string. Args: text (str): The text input string. pre_decor (str): initial string decorator. post_decor (str): final string decorator. Returns: text (str): the text without the specified decorators. Examples: >>> strip_decorator('"test"') 'test' >>> strip_decorator('"test') 'test' >>> strip_decorator('<test>', '<', '>') 'test' """ begin = len(pre_decor) if text.startswith(pre_decor) else None end = -len(post_decor) if text.endswith(post_decor) else None return text[begin:end]
def convert_to_image_file_format(format_str): """Converts a legacy file format string to an ImageFileFormat enum value. Args: format_str: A string describing an image file format that was passed to one of the functions in ee.data that takes image file formats. Returns: A best guess at the corresponding ImageFileFormat enum name. """ if format_str is None: return 'AUTO_JPEG_PNG' format_str = format_str.upper() if format_str == 'JPG': return 'JPEG' elif format_str == 'AUTO': return 'AUTO_JPEG_PNG' elif format_str == 'GEOTIFF': return 'GEO_TIFF' elif format_str == 'TFRECORD': return 'TF_RECORD_IMAGE' else: # It's probably "JPEG" or "PNG", but might be some other supported format. # Let the server validate it. return format_str
def dixon_stat(vals, r, m = 0): """Calculates dixon test statistic. Use the dixon test statistic to determine whehter there is significant support for the existence of DKs in dataset. Use this for upper outliers, classic test statistic. Parameters: vals (array): Single variable array with values in decreasing order r (int): Hypothesized number of outliers in dataset Returns: float: dixon test statistic """ test_stat = float(vals[0]) / vals[r] return(test_stat)
def infos_to_markdown_table(benchmark_infos): """Conver a list of BenchmarkInfos into a markdown table and return the result.""" markdown = '' for benchmark_info in sorted(benchmark_infos, key=lambda info: info.benchmark): markdown += '|{}|{}|{}|{}|{}|{}|\n'.format(*benchmark_info) return markdown
def _test_assignment(assignment_test): """Test whether an assignment fails. :arg str assignment_test: A python code snippet. :returns bool: True if {assignment_test} fails with a TypeError. """ try: eval(assignment_test) except TypeError: return True return False
def rev_complement(string): """Make the reverse complement""" string = string.upper() string = string[::-1] to_replace = [('A', 't'), ('T', 'a'), ('C', 'g'), ('G', 'c')] for rc in to_replace: string = string.replace(rc[0], rc[1]) string = string.upper() return string
def get_block(blockidx, blocksz, obj): """ Given obj, a list, return the intersection of obj[blockidx*blocksz:(blockidx+1)*blocksz] and obj Ex: get_block(2, 100, range(250) returns [200, 201, ..., 249] """ if blockidx*blocksz > len(obj): return [] elif (blockidx+1)*blocksz > len(obj): return obj[blockidx*blocksz:] else: return obj[blockidx*blocksz:(blockidx+1)*blocksz]
def index_default(i, char): """Returns the index of a character in a line, or the length of the string if the character does not appear. """ try: retval = i.index(char) except ValueError: retval = 100000 return retval
def schilling_equation(n, c): """ A_n(C) as defined by Schilling, Coll. Math. J., 1990 and Franke et al., Nat. Methods, 2015. Won't work above n=30 or so due to recursive limit. """ return sum( [schilling_equation(n-1-j, c) for j in range(0,c+1)]) if n>c else 2**n
def xy_offset(x, y, offset_x, offset_y, offset): """Increment X and Y coordinates by the given offsets.""" return x + offset_x * offset, y + offset_y * offset
def _between_symbols(string, c1, c2): """Will return empty string if nothing is between c1 and c2.""" for char in [c1, c2]: if char not in string: raise ValueError("Couldn't find character {} in string {}".format( char, string)) return string[string.index(c1)+1:string.index(c2)]
def payoff_bull_spread_fprime( underlying, lower_strike, upper_strike, gearing=1.0): """payoff_bull_spread_fprime calculate value of derivative of payoff of bull spread option with respect to underlying. :param underlying: :param lower_strike: :param upper_strike: :param float gearing: coefficient of this option. Default value is 1. :return: derivative of bull spread option. If lower_strike >= upper_strike, then return 0. :rtype: float """ if lower_strike >= upper_strike: return 0.0 if lower_strike < underlying < upper_strike: return gearing else: return 0.0
def calc_statistic(data): """ Calculation and construction of statistical model in the percentage ratio: count of requests, methods, parametres for each level etc. :param data: dictionary that must contain key 'paths' and assigned with this key values :type data: dict :return: statistical model :rtype: dict """ def parse_params(path): """ Helper-function for parametres parsing :param path: raw path data :type path: string :return: pairs(k,v), k - param name, v - list of values :rtype: dict """ res = {} for i in path.split('?')[1:]: parsed_params = i.split('=') res[parsed_params[0]] = None if len(parsed_params) > 0: res[parsed_params[0]] = parsed_params[1:] return res try: res = { 'count_requests' : len(data['requests']), 'methods' : { 'GET' : 0, 'HEAD' : 0, 'POST' : 0, 'PUT' : 0, 'DELETE' : 0, 'UPDATE' : 0 }, 'parametres':{}, 'level_stats':{} } #preprocess buff = [] for i in data['paths']: buff.append(i.split('/')) for req in data['requests']: res['methods'][req.split(' ')[0]] += 1 for r in res['methods']: try: res['methods'][r] = res['methods'][r]/res['count_requests']*100 except ZeroDivisionError: res['methods'][r] = 0.0 level_num = 0 for path in buff: for level in path: level_key = str(level_num) if not (level_key in res['level_stats']): res['level_stats'][level_key] = {} params = {} if '?' in level or '=' in level: params = parse_params(level) level = level.split('?')[0] res['parametres'][level] = params if level in res['level_stats'][level_key]: res['level_stats'][level_key][level] += 1 else: res['level_stats'][level_key][level] = 1 level_num += 1 #end for level level_num = 0 #end for path for i in res['level_stats']: summ_ = 0 for node in res['level_stats'][i]: try: res['level_stats'][i][node] = res['level_stats'][i][node]/res['count_requests']*100 summ_ += res['level_stats'][i][node] except ZeroDivisionError: res['level_stats'][i][node] = 0.0 if summ_ < 100.0: res['level_stats'][i]['END_'+str(int(i)+1)] = 100.0 - summ_ return res except Exception as exc: print("Error in calc_statistic(): %s" % exc) return {}
def compress_2d_list(squares_list): """ Convert 2d list to a 1d list """ result = [] for row in squares_list: for col in row: result.append(col) return result
def Prime(number: int) -> bool: """ Returns whether a number is prime or not (only divisible by itself and 1, with more than 1 factor) This means 2 is prime, but 1 is not :param number: int => The number to test :return: bool => The result of the check """ for x in range(2, number): if number % x == 0: return False return True
def ordered(obj): """Orders the items of lists and dictionaries.""" if isinstance(obj, dict): return sorted((k, ordered(v)) for k, v in obj.items()) if isinstance(obj, list): return sorted(ordered(x) for x in obj) else: return obj
def lowercase_count(strng: str) -> int: """Returns count of lowercase characters.""" return sum(c.islower() for c in strng)
def url_host(url: str) -> str: """ Parses hostname from URL. :param url: URL :return: hostname """ from urllib.parse import urlparse res = urlparse(url) return res.netloc.split(':')[0] if res.netloc else ''
def factorial_i(number): """ Calculates the factorial of a number, using an iterative process. :param number: The number. :return: n! """ # Check to make sure the argument is valid. if number < 0: raise ValueError # Go from 1 to n, multiplying up the numbers. total = 1 for i in range(1, number + 1): total *= i return total
def get_aws_connection_data(assumed_account_id, assumed_role_name, assumed_region_name=""): """ Build a key-value dictionnatiory args for aws cross connections """ if assumed_account_id and assumed_role_name: aws_connection_data = dict( [("assumed_account_id", assumed_account_id), ("assumed_role_name", assumed_role_name), ("assumed_region_name", assumed_region_name)]) else: aws_connection_data = {} return aws_connection_data
def recall(true_y, predicted_y): """ This function is used to calculate the recall :param true_y: These are the given values of class variable :param predicted_y: These are the predicted values of the class variable :return: the recall """ true_positives = 0 false_negetives = 0 for each in range(len(true_y)): if true_y[each] == predicted_y[each] and predicted_y[each] == 1: true_positives += 1 if true_y[each] != predicted_y[each] and predicted_y[each] == 0: false_negetives += 1 return true_positives / float(true_positives + false_negetives)
def is_ns(seq): """Ns filter If there exists an ambiguous base (N call) then the read is discarded. """ if 'N' in seq: return True else: return False
def replace_parens(tokens): """Replace all instances of -LRB- and -RRB- with actual parentheses.""" parens_map = {'-LRB-': '(', '-RRB-': ')'} return [parens_map.get(s, s) for s in tokens]
def is_subdir(child, parent): """ Check whether "parent" is a sub-directory of "child". :param child: Child path. :type child: ``str`` :param parent: Parent directory to check against. :type parent: ``str`` :return: True if child is a sub-directory of the parent. :rtype: ``bool`` """ return child.startswith(parent)
def limit_on_close_order(liability, price): """ Create limit order for the closing auction. :param float liability: amount to bet. :param float price: price at which to bet :returns: Order information to place a limit on close order. :rtype: dict """ return locals().copy()
def tupleit2(anarray): """Convert a non-hashable 2D numpy array to a hashable tuple-of-tuples.""" return tuple([tuple(r) for r in list(anarray)])
def reverse(seq): """ reverse the given sequence """ seq_r = "" for i in range(len(seq)): seq_r += seq[len(seq) - 1 - i] return seq_r
def pskToString(psk: bytes): """Given an array of PSK bytes, decode them into a human readable (but privacy protecting) string""" if len(psk) == 0: return "unencrypted" elif len(psk) == 1: b = psk[0] if b == 0: return "unencrypted" elif b == 1: return "default" else: return f"simple{b - 1}" else: return "secret"
def rad2equiv_evap(energy): """ Converts radiation in MJ m-2 day-1 to the equivalent evaporation in mm day-1 assuming a grass reference crop using FAO equation 20. Energy is converted to equivalent evaporation using a conversion factor equal to the inverse of the latent heat of vapourisation (1 / lambda = 0.408). Arguments: energy - energy e.g. radiation, heat flux [MJ m-2 day-1] """ # Determine the equivalent evaporation [mm day-1] equiv_evap = 0.408 * energy return equiv_evap
def isprime(n): """check if integer n is a prime""" # make sure n is a positive integer n = abs(int(n)) # 0 and 1 are not primes if n < 2: return False # 2 is the only even prime number if n == 2: return True # all other even numbers are not primes if not n & 1: return False # range starts with 3 and only needs to go up the squareroot of n # for all odd numbers for x in range(3, int(n**0.5)+1, 2): if n % x == 0: return False return True
def first(iterable): """Return first item in series or raises a ValueError if series is empty""" iterator = iter(iterable) try: return next(iterator) except StopIteration: raise ValueError("iterable is empty")
def ISO_6391_to_name(code: str) -> str: """ Converts ISO 639-1 (2 letters) language codes to common name (eg: "en" -> "english") """ if code == "ca": return "catalan" if code == "da": return "danish" elif code == "en": return "english" elif code == "es": return "spanish" elif code == "it": return "italian" elif code == "mn": return "mongolian" elif code == "zh": return "chinese" else: raise ValueError("ISO 639-1 code not known: "+str(code))
def find_precision(value): """Find precision of some arbitrary value. The main intention for this function is to use it together with turbogears.i18n.format.format_decimal() where one has to inform the precision wanted. So, use it like this: format_decimal(some_number, find_precision(some_number)) """ decimals = '' try: decimals = str(value).split('.', 1)[1] except IndexError: pass return len(decimals)
def merge_slide_with_same_slide_number(data: list) -> list: """ Function to merge slides with the same slide number into a single one. :param data: The list of dictionaries of the form :type: [{"Header":"", "Paragraph":"", "Header_keywords": [], "Paragraph_keywords": [], slide:int}] :return: The list of dictionaries where slides containing the same slide number are merged :rtype: [{"Header":"", "Header_keywords": [], "Paragraph_keywords": [], slide:int}] """ merged = [] slide_number = [] for slide in data: if slide["slide"] not in slide_number: slide_number.append(slide["slide"]) header_keywords = [] paragraph_keywords = [] for data_1 in [data_2 for data_2 in data if data_2["slide"] == slide["slide"]]: header_keywords += data_1["Header_keywords"] paragraph_keywords += data_1["Paragraph_keywords"] merged.append({"Header": slide["Header"], "Header_keywords": header_keywords, "Paragraph_keywords": paragraph_keywords, "slide": slide["slide"]}) return merged
def hsv_to_rgb(h, s, v): """Converts HSV to RGB values :param h: :param s: :param v: :return: """ if s == 0.0: return v, v, v i = int(h * 6.) # XXX assume int() truncates! f = (h * 6.) - i p, q, t = v * (1. - s), v * (1. - s * f), v * (1. - s * (1. - f)) i %= 6 if i == 0: return v, t, p if i == 1: return q, v, p if i == 2: return p, v, t if i == 3: return p, q, v if i == 4: return t, p, v if i == 5: return v, p, q
def latitude_valid(value): """test for valid latitude >>> latitude_valid(45) True >>> latitude_valid(100) False >>> latitude_valid('x') False """ if value == '': return True try: v = float(value) if v >= -90 and v <= 90: return True else: return False except ValueError: return False
def make_fraud(seed, card, user, latlon): """ return a fraudulent transaction """ amount = (seed + 1) * 1000 payload = {"userid": user, "amount": amount, "lat": latlon[0], "lon": latlon[1], "card": card } return payload
def R2_b(Pimax, AD): """ R2 Determining the required minimum clamp load Fkerf (Section 5.4.1) The required minimum clamp load Fkerf is determined while taking into account the following requirements: b) Sealing against s medium """ # b) FKP = AD * Pimax # (R2/2) # return FKP #
def conical_attractive_force(current_cell, goal_cell, K = 1.0): """ Calculates the linear attractive force for one grid cell with respect to the target current_cell: a list containing x and y values of one map grid cell goal_cell: a list containing x and y values of the target grid cell K: potential attractive constant returns: linear attractive force scaled by the potential attractive constant """ dx = goal_cell[0] - current_cell[0] dy = goal_cell[1] - current_cell[1] distance = (dx ** 2 + dy ** 2)**0.5 return K * distance
def g(L, e): """L a list of ints, e is an int""" for i in range(100): for e1 in L: if e1 == e: return True return False
def isbitset(x, nth_bit): """check if n-th bit is set (==1) in x Args: x: integer or :class:`numpy.ndarray` of integers nth_bit: position of investigated bit (0, 1, 2, ...) Returns: boolean or boolean array denoting whether the nth_bit is set in x. Examples: >>> isbitset(3, 0) True >>> isbitset(2, 0) False """ if nth_bit < 0: raise ValueError('position of bit cannot be negative') mask = 1 << nth_bit return x & mask > 0
def str2bool(x): """Converts a string to boolean type. If the string is any of ['no', 'false', 'f', '0'], or any capitalization, e.g. 'fAlSe' then returns False. All other strings are True. """ if x is None or x.lower() in ['no', 'false', 'f', '0']: return False else: return True
def maximum_prfacc(*evals, eval_metric='accuracy'): """Get maximum for multiple evaluations. Args: evals [tuple]: several evals without limitation eval_metric [str]: evaluation standard for comparsion Returns: max_eval [dict]: one eval with the maximum score """ assert eval_metric in evals[0].keys(), ValueError("Value error of 'eval_metric'.") if eval_metric == 'accuracy': values = [e[eval_metric] for e in evals] else: values = [e[eval_metric]['f1-score'] for e in evals] index = values.index(max(values)) max_eval = evals[index] return max_eval
def read_flag_argument(argv, flag, optional=True, default=None): """ Tries to read a flagged option from a list of strings - typically argv. OBS: python has the argparse module, which shall do the same job and even better. But this function may be easier for simple uses. Example ------- "tmux a -t my_session" --> argv = ["tmux", "a", "-t", "my_session"] Calling read_flag_options(argv, "-t") should return "my_session". Parameters ---------- argv : list List of strings from which the argument is extracted. flag : str String that flags the desired option as the next entry. Must contain trailing "-" or "--". optional : bool If True, returns None for not-found option. If False, raises an error default : str If optional is True, specifies the default return value. """ try: # Finds the flag in list. If not found, catches the ValueError. flag_index = argv.index(flag) except ValueError: if optional: return default else: raise ValueError("Hey, the required flag '{}' was not found.".format(flag)) # Checks if given is was not the last position in list. if flag_index >= len(argv) - 1: raise ValueError("Hey, the flag '{}' is the last element in the given list, but I expected an " "option to be passed after it.".format(flag)) else: return argv[flag_index + 1]
def parse_move(s: str) -> int: """ :param s: :return: """ try: v = int(s) except ValueError: v = -1 return v
def clearBitsAfter(m, off, length): """Clears all bits of a number m with length length with offset smaller OR EQUAL off. Used to determine the fermionic +/- prefactor.""" clearNUm = 0 for i in range(off+1, length): clearNUm += 2**(i) return m & clearNUm