content
stringlengths
42
6.51k
def get_complement(string): """returns a complementary DNA sequence, e.g. GCTA for TAGC. Mind the sequence inversion!""" string=string.replace('G','1') string=string.replace('A','2') string=string.replace('T','3') string=string.replace('C','4') string=string.replace('1','C') string=string.re...
def broadcast(singular, width: int): """Fill an array of the given width from the singular data provided.""" # Warning: the initial use case for this utility function is to repackage a Future of width 1 as a # Future of greater width, but this relies on an assumption about Future.result() that may change. ...
def build_question_scanerio_map(utterances): """Builds a map from question to scenarios""" question_scenario_map = dict() for utterance in utterances: question = utterance['question'] scenario = utterance['scenario'] if scenario == '': continue if question not in ...
def insertion_sort(array): """ Sort array in ascending order by insertion sort Insertion sort iterates, consuming one input element each repetition, and growing a sorted output list. At each iteration, insertion sort removes one element from the input data, finds the location it belongs within ...
def _is_module_ignored(module_name, ignored_modules) -> bool: """Checks if a given module is ignored.""" if module_name.split(".")[-1].startswith("_"): return True for ignored_module in ignored_modules: if module_name == ignored_module: return True # Check is module is ...
def isLDAPUrl(s): """ Returns 1 if s is a LDAP URL, 0 else """ s_lower = s.lower() return \ s_lower.startswith('ldap://') or \ s_lower.startswith('ldaps://') or \ s_lower.startswith('ldapi://')
def lett2num(character): """ Returns the ASCII order number of the character (after making it lowercase) """ # a -> 0, ..., z -> 25 return int(ord(character.lower()) - 97)
def strip_unbalanced_parens(s, parens='()'): """ Return a string where unbalanced parenthesis are replaced with a space. `paren` is a pair of characters to balance such as (), <>, [] , {}. For instance: >>> strip_unbalanced_parens('This is a super string', '()') 'This is a super string' >...
def is_signif(pvalue, p=0.05): """Tell if condition with classifier is significative. Returns a boolean : True if the condition is significativeat given p """ answer = False if pvalue <= p: answer = True return answer
def dynamic_lucas_number(n_th_number: int) -> int: """ Returns the nth lucas number >>> dynamic_lucas_number(1) 1 >>> dynamic_lucas_number(20) 15127 >>> dynamic_lucas_number(0) 2 >>> dynamic_lucas_number(25) 167761 >>> dynamic_lucas_number(-1.5) Traceback (most recent cal...
def countDigits(n): """Count the number of digits in a given number "n". """ num = len(str(abs(n))) return num
def apiget(result_tuple, errormessage="RoboClaw API Getter"): """ Every read operation from the Roboclaw API returns a tuple: index zero is 1 for success and 0 for failure. This helper looks for that zero and raises an exception if one is seen. If an optional error message was provided, it is sent into the Va...
def label2Addr(label, labels): """ Return int address associated with label or None. label is a string, either digits or symbolic. Array labels has labels for all addresses in mem. """ if label.isdigit(): return int(label) if label in labels: return labels.index(label)
def threshold_by_length(word): """Get a pre-determined probability threshold based on heuristics""" threshold = -5 if len(word) > 6: threshold = -20 if len(word) == 6: threshold = -18 if len(word) == 5: threshold = -16 if len(word) == 4: threshold = -14 if len...
def get_feature_selector(region): """ :param region: :return: """ feat = [] for entry in region.keys(): if entry.startswith('ft'): feat.append(entry) feat = sorted(feat) return feat, len(feat)
def smallest_side(l, w, h): """Return the area of the smallest side of a box""" return min([(l * w), (w * h), (h * l)])
def say_hello(to: str) -> str: """ Just a greeting """ return f"Hello {to}!"
def convert_value(value): """Converts metric value to float.""" try: return float(value) except ValueError: return value
def cast_value_to_bool(value): """Casts a passed value to boolean value.""" if isinstance(value, str): return value.lower() in ["1", "true", "yes"] if isinstance(value, bool): return value return False
def _minimum_bracket_reversals(input_string): """ Calculate the number of reversals to fix the brackets Args: input_string(string): Strings to be used for bracket reversal calculation Returns: int: Number of bracket reversals needed """ # this is technically write, # however t...
def isNull(value): """Returns True if \"NULL\"""" return value == "NULL"
def CountFrequency(my_list): """count the occurence in a list """ # Creating an empty dictionary freq = {} for item in my_list: if (item in freq): freq[item] += 1 else: freq[item] = 1 freq = dict(sorted(freq.items())) return freq
def escape_for_telegram(text): """ Args: text (str) Returns: str: Escaped text """ return text \ .replace('\\', '\\\\') \ .replace('[', '\\[') \ .replace(']', '\\]') \ .replace('(', '\\(') \ .replace(')', '\\)') \ .replace('`', '\\`') ...
def list_replace(subject_list, replacement, string): """ To replace a list of items by a single replacement :param subject_list: list :param replacement: string :param string: string :return: string """ for s in subject_list: string = string.replace(s, replacement) return str...
def uniformCrossover(parent1: list, parent2: list, mask: list): """ This function performs uniform crossover and mutation with the help of a mask ... Attributes ---------- parent1:List features in vectorized form parent2:List features...
def pad(string, length, pad=" ", left=False): """ Pads a string to achieve a minimum length. @param pad The pad character. @param left If true, pad on the left; otherwise on the right. """ if len(pad) != 1: raise ValueError("pad is not a character: {!r}".format(pad)) if...
def init_variances(window_sizes, number_of_states): """Initialize a variances data structure. :param window_sizes: The required window sizes. :param number_of_states: The number of states. :return: The initialized variances data structure. """ variances = [] for i in range(number_of_states)...
def cmp_no_order(seq1, seq2): """Compare two sequences regardless of order""" if len(seq1) != len(seq2): return False temp = seq2[:] for i in seq1: try: temp.remove(i) except ValueError: return False return len(temp) == 0
def clean_flagged_data(conv, field, clean=False): """ Use the given converter on field, and except ValueErrors as returning None ValueErrors will occur when values are flagged, eg conv('12.11P') will fail and return None for that value :param conv: :param field: :param clean: if False, don't str...
def get_sub_domain(domain, sub_domain): """ Remove base domain name from FQDN """ # www.example.com => www # example.com => @ # .example.com => @ # *.example.com => * if sub_domain is not None: sub_domain = sub_domain.replace("." + domain, "").replace(domain, "") if sub_domai...
def ed(fn, iterable, *args, **kwargs): """If ``fn`` maps ``iterable`` to a generator (e.g. :func:`flatten` and others below), ``ed`` will consume the result and produce a tuple or list. If ``iterable`` has a finite length (e.g. tuples, lists), uses the same type to consume it. If not (e.g. generators),...
def is_int(string): """ Here be dragons. https://stackoverflow.com/a/20929983 """ try: int(string) return True except ValueError: return False
def fmtcdb(key, val): """Formats a key and value into cdb format.""" key = str(key) val = str(val) s = '+%d,%d:%s->%s' % (len(key), len(val), key, val) return s
def decrypt_video_packet(packet: bytes, video_key: bytes) -> bytes: """Decrypt an encrypted videos stream payload. Skips decryption if packet is less than 0x240 bytes. """ if len(video_key) < 0x40: raise ValueError(f"Video key should be 0x40 bytes long. Given {len(video_key)}") data = bytea...
def diff(a, n=1): """ Calculate the n-th discrete difference along given axis. The first difference is given by ``out[n] = a[n+1] - a[n]`` along the given axis, higher differences are calculated by using `diff` recursively. :param a: The list to calculate the diff on :param n: The order of ...
def fizz_buzz(n): """ Fizz Buzz Game :param n: an integer :return: fizz if n % 3 == 0 buzz if n % 5 == 0 fizz buzz if n % 15 == 0 """ if n % 3 == 0 and n % 5 == 0: return "fizz buzz" elif n % 3 == 0: return "fizz" elif n % 5 == 0: return...
def postselection_decoding(results): """ Calculates the logical error probability using postselection decoding. This postselects all results with trivial syndrome. Args: results (dict): A results dictionary, as produced by the `process_results` method of a code. Returns: ...
def generate_dict_vpn_ip_nexthops(nexthops): """ This function generates the block of configurtion for the VPN IP nexthops that will be used in CLI template to generate VPN Feature Template """ vipValue = [] for nexthop in nexthops: vipValue.append( { "add...
def kbytes(text): """convert memory text to the corresponding value in kilobytes Args: text (str): string corresponding to an abbreviation of size. Returns: int representation of text. Examples: >>> kbytes(\'10K\') 10 >>> >>> kbytes(\'10G\') 10...
def is_char_sequence(value) -> bool: """ In most instances testing for Sequence or Iterable, these string types are undesirable. """ return isinstance(value, (bytes, bytearray, str))
def int_list(s): """ >>> int_list('10,20, 30') [10, 20, 30] """ return [int(i.strip()) for i in s.split(',')]
def is_kanji(text, start_block=u'\u4e00', end_block=u'\u9fff'): """Check if all characters in text are kanji character. [CJK Unified Ideographs 4E00-9FFF Common]""" res = True for t in text: if t < start_block or t > end_block: res = False break return res
def _ExpandTabs(text, column, tabsize, mark_tabs=False): """Expand tab characters in a string into spaces. Args: text: a string containing tab characters. column: the initial column for the first character in text tabsize: tab stops occur at columns that are multiples of tabsize mark_tabs: if true,...
def normalizeGlyphLeftMargin(value): """ Normalizes glyph left margin. * **value** must be a :ref:`type-int-float` or `None`. * Returned value is the same type as the input value. """ if not isinstance(value, (int, float)) and value is not None: raise TypeError("Glyph left margin must b...
def hypotenuse(a, b): """write a function called hypotenuse that returns the length of the hypotenuse of a right triangle given the lengths of the two legs as arguments.""" if a < 0 or b < 0: print("invalid arguments") return a * a + b * b
def is_email(user_input): """Return True in input is a valid email""" return "@" in user_input, "Please enter a valid email"
def update_tr_radius(Delta, actual_reduction, predicted_reduction, step_norm, bound_hit): """Update the radius of a trust region based on the cost reduction. """ if predicted_reduction > 0: ratio = actual_reduction / predicted_reduction elif predicted_reduction == actual_red...
def dispense_cash(amount): """ Determine the minimum number of ATM bills to meet the requested amount to dispense Parameters ---------- amount : int The amount of money requested from the ATM Returns ------- int The number of bills needed, -1 if it can't be done...
def compare_dicts(dict1, dict2): """ Show values that differ between dictionaries. Return true if the dictionaries are equal. """ set1 = set(dict1.items()) set2 = set(dict2.items()) if dict1 != dict2: # Do a symmetric diff to find values that don't match sorted_values = sorted(se...
def to_selector(labels): """ Transfer Labels to selector. """ parts = [] for key in labels.keys(): parts.append("{0}={1}".format(key, labels[key])) return ",".join(parts)
def strip_ids(list_of_dict:list): """ ListOfDict -> List of Integers remove all of the id values from a list of dictionaries and return them in a list format """ list_of_ids = [] for row in list_of_dict: list_of_ids.append(row["id"]) del row["id"] return list_of_ids
def points_to_path(points, closed=True): """turn a series of points into a path""" first = True data = "M " for point in points: if not first: data += " L " data += f"{point[0]},{point[1]}" first = False if closed: data += " Z" return data
def celcius_to_fahrenheit(celcius_float): """Convert Celcius to Fahrenheit""" return celcius_float*1.8+32
def lower_text(text: str) -> str: """Lower case all of the uppercase characters in a string. Args: text (str): String to be lowered. Returns: str: string with no uppercase characters. """ return text.lower()
def lsst_magnitude_zero_point(bands=''): """ Sample from the LSST zero point distribution """ dist = {'u': 26.5, 'g': 28.3, 'r': 28.13, 'i': 27.79, 'z': 27.40, 'Y': 26.58} return [dist[b] for b in bands.split(',')]
def parallel_cor_function(nucleotide1, nucleotide2, phyche_index): """Get the cFactor.(Type1)""" temp_sum = 0.0 phyche_index_values = list(phyche_index.values()) len_phyche_index = len(phyche_index_values[0]) for u in range(len_phyche_index): temp_sum += pow(float(phyche_index[nucleotide1][u...
def corresponding_directory_perm(perm): """Given 4, returns 5. Given 6, returns 7. Based on desired file permissions, returns corresponding dir permissions. """ perm = int(perm) return perm + 1 if perm % 2 == 0 and perm > 3 else perm
def strip_quotes(string): """Remove quotes from front and back of string >>> strip_quotes('"fred"') == 'fred' True """ if not string: return string first = string[0] last = string[-1] if first == last and first in '"\'': return string[1:-1] return string
def _filter_state_dict(state_dict, remove_model_prefix_offset: int = 1): """Makes the state_dict compatible with the model. Prevents unexpected key error when loading PyTorch-Lightning checkpoints. Allows backwards compatability to checkpoints before v1.0.6. """ prev_backbone = 'features' ...
def guess_bytes(bstring): """ NOTE: Using `guess_bytes` is not the recommended way of using ftfy. ftfy is not designed to be an encoding detector. In the unfortunate situation that you have some bytes in an unknown encoding, ftfy can guess a reasonable strategy for decoding them, by trying a fe...
def common_items(l1, l2): """Return common items in two lists. Parameters ---------- l1 : list A list. l2 : list A list. Returns ------- list The common items. """ return [item for item in l1 if item in l2]
def _extract_gpcrdb_residue_html(txt): """ Extracts the relevant lines for all residues from a GPCRdb html entry. Parameters ---------- txt : str Content (html) of the website with the GPCRdb entry. Returns ------- residue_html : list A list in which...
def sam_q_order(start, end, flags): """ if flags include 16, reverse start end """ reverse = flags >= 16 and str(bin(flags))[-5] == "1" return tuple(sorted([start, end], reverse=reverse))
def operation_startswith(value, test): """Check if value start swith test.""" return value.startswith(test)
def _jsonify_action(name, description_dict): """ Remove all the extra cruft and dispatch fields, and create one dict describing the named action / operator. """ short_description = {"internal_name": name} for data in ["arguments", "cost", "user_name", "description", "short_description"]: if ...
def linearRegression(xyList): """Return the coefficients a b so that yList ~= a * xList + b.""" avgX, avgY, avgX2, avgXY = 0, 0, 0, 0 for x, y in xyList: avgX += x avgY += y avgX2 += x**2 avgXY += x*y a = float(avgXY - avgX * avgY) / float(avgX2 - avgX**2) b = avgY - ...
def return_first_elements(paths): """ From a list of paths, return the first elements of each path (directory). :param paths: a list of strings of directories :return: a list of strings of the first elements of each path (directories) """ first_elements = ['\\'.join(path.split('\\')[:-1]) + '\\...
def find_lcs(s1, s2): """ find longest common string :param s1: :param s2: :return: """ m = [[0 for i in range(len(s2) + 1)] for j in range(len(s1) + 1)] mmax = 0 p = 0 for i in range(len(s1)): for j in range(len(s2)): if s1[i] == s2[j]: m[i + ...
def quad_1d(x, *p): """[summary] Arguments: x {[type]} -- [description] Returns: [type] -- [description] """ A, x0, C = p xc = x - x0 return A * xc**2 + C
def find_swift_version_copt_value(copts): """Returns the value of the `-swift-version` argument, if found. Args: copts: The list of copts to be scanned. Returns: The value of the `-swift-version` argument, or None if it was not found in the copt list. """ # Note that the argument can occur multi...
def qt_filter_get(columns, values, aliases=None, and_or='and'): """ Return an eveluation string to filter the rows of a queryset. This function takes the following arguments: o "columns" is a list of columns to be matched against items within the "values" parameter. o "values" is...
def find_tag(tag_name, tags_stack): """ Find closest opening tag in a tags stack Search is done from the end of the stack. :param tag_name: tag name :type tag_name: str :param tags_stack: tags stack :type tags_stack: list :return: opening tag index or -1 :rtype: int """ i =...
def parse_colname(colname): """ Common function to interpret input column names provided by the user. This function translates column specification provided by the user into a column number. Notes ----- This function will understand the following inputs:: '1,2,...
def is_static_ip(ip): """ Checks if the given ip is a static ip for FRC :param ip: the ip to be checked, a str :return: True if the ip is an FRC static ip, False if it isn't """ if not isinstance(ip, str): return False if len(ip) == 10: if ip.startswith('10.') and ip.count('....
def mac_format(mac): """convert mac format to xxxx-xxxx-xxxx""" if not mac: return None if mac.count("-") != 2: return None addrs = mac.split("-") for i in range(3): if not addrs[i] or not addrs[i].isalnum(): return None if len(addrs[i]) < 1 or len(addr...
def utctz_to_altz(utctz: str) -> int: """we convert utctz to the timezone in seconds, it is the format time.altzone returns. Git stores it as UTC timezone which has the opposite sign as well, which explains the -1 * ( that was made explicit here ) :param utctz: git utc timezone string, i.e. +0200""" ...
def is_vowel_sign_offset(c_offset): """ Is the offset a vowel sign (maatraa) """ return (c_offset >= 0x3e and c_offset <= 0x4c)
def covariance_matrix(nums_with_uncert): """ Returns a matrix that contains the covariances between the given sequence of numbers with uncertainties (AffineScalarFunc objects). The resulting matrix implicitly depends on their ordering in 'nums_with_uncert'. The covariances are floats (never int...
def normalize(name): """Normalize FQDN. >>> normalize('this.is.a.test....') 'this.is.a.test' >>> normalize('this...is..a.test..') 'this...is..a.test' >>> normalize('this..is.a.test') 'this..is.a.test' >>> normalize('this.is.a.test') 'this.is.a.test' """ name = name.lower() ...
def empty_dict(old_dict): """ Return a dictionary of empty lists with exactly the same keys as old_dict **Parameters** :old_dict: Dictionary of lists (identified by the key). :Author: Sirko Straube :Created: 2010/11/09 """ from collections import defaultdi...
def _map_to_0_index(keys): """Map data from current ID to 0 index for hdf5.""" list_keys = list(keys) key_map = {} for i, key in enumerate(list_keys): key_map[key] = i return key_map
def stronglyConnectedComponents(graph): """ `graph` here is a dict from keys (of some hashable class) to a list of keys """ indexCounter = [0] stack = [] lowLinks = {} index = {} result = [] def strongConnect(node): index[node] = indexCounter[0] lowLinks[node] = inde...
def potential(dist): """ take distance r of particles and return the leonard-jones potential """ return 4 * ( 1 / dist ** 12 - 1 / dist ** 6 )
def unscale_input(img): """Reverses scaling of image values from [-1,1] to [0,255]. Args: img (numpy.ndarray[float]): image to scale Returns: numpy.ndarray[float]: unscaled image """ return ((img + 1) * 127.5)
def FloatConv(value): """Returns the float value of a string, if possible.""" try: float_val = float(value) return float_val except ValueError: return value
def dist(unit, tile): """euclidean distance - used for missile attacks and a (bad) approximation of travel time.""" return abs(tile['x'] - unit['x']) + abs(tile['y'] - unit['y'])
def compute_iou(box1, box2): """ computing IoU :param rec1: (y0, x0, y1, x1), which reflects (top, left, bottom, right) :param rec2: (y0, x0, y1, x1) :return: scala value of IoU """ rec1 = [box1[0], box1[1], box1[0] + box1[2], box1[1] + box1[3]] rec2 = [box2[0], box2[1], box2...
def format_seconds(seconds): """ https://stackoverflow.com/questions/538666/python-format-timedelta-to-string """ periods = [ ('year', 60 * 60 * 24 * 365), ('month', 60 * 60 * 24 * 30), ('day', 60 * 60 * 24), ('hour', 60 * 60), ('min', 60), ('sec', 1) ...
def _exp_str(string, exponent): """ Return a string representing string rasied to the power exponent. """ if isinstance(string, str) and isinstance(exponent, int): if exponent < 1: raise ValueError elif exponent == 1: return string else: return...
def to_camel_case(text): """ Converts dash/underscore delimited words into camel casing. :param text: a string of words with '-' and '_' as spaces. :return: the string as camel case. """ s = text.replace("-", " ").replace("_", " ") s = s.split() if len(text) == 0: return text ...
def encode1( strs): """Encodes a list of strings to a single string. :type strs: List[str] :rtype: str """ encoded_str = "" for s in strs: encoded_str += "%0*x" % (8, len(s)) + s return encoded_str
def toString( x ): """ Return a string representing x. If x is a float convert it to scientific notation. Arguments: x: The value to convert to a string. """ if isinstance( x, float ): return "{:.2e}".format( x ) else: return str( x )
def is_even_permutation(seq1, seq2): """ Determine whether a permutation of a sequence is even or odd. :param seq1: the first sequence :param seq2: the second sequence, which must be a permuation of the first :returns: True if the permutation is even, False if it is odd :rtype: bool """ siz...
def cast_map_to_str_dict(map): """ Helper function to cast Unreal Map object to plain old python dict. This will also cast values and keys to str. Useful for metadata dicts. """ return {str(key): str(value) for (key, value) in map.items()}
def is_stack_region(name): """Checks whether memory region is stack""" return name == '[stack]'
def matchStrength(x, y): """Compute the match strength for the individual *x* on the string *y*. """ return sum(xi == yi for xi, yi in zip(x, y))
def tally_letters(string): """Given a string of lowercase letters, returns a dictionary mapping each letter to the number of times it occurs in the string.""" dict = {} dist = set(string) for i in dist: count = 0 for j in string: if i == j: count += 1 ...
def order_dict(_dict: dict, reverse: bool=True) -> dict: """ Takes a dictionary and returns it ordered. :param _dict: :class:`dict` :param reverse: :class:`bool` :return: :class:`dict` """ temp_dict = {} unordered_list = [(k, v) for k, v in _dict.items()] ordered_list = sorted(unor...
def convert_hex_to_rgb(color_set): """Takes the palette color set, converts any hex values into tuples, and returns a integer tuple of the R/G/B color channels. """ returned_list = [] for color in color_set: if isinstance(color, str): # is hex code stripped = color.replace('#',...
def b2hex(b): """This function replace the bytes.hex() function provided in Python3.5 and later .. note:: Micropython (Python 3.4) doesn't support bytes.hex(). Args: b (bytes): the byte chain to convert to hexadecimal representation Returns: str : The string representation of th...