content
stringlengths
42
6.51k
def remove_suffix(s: str, suffix: str) -> str: """Remove the suffix from the string. I.e., str.removesuffix in Python 3.9.""" # suffix="" should not call s[:-0] return s[: -len(suffix)] if suffix and s.endswith(suffix) else s
def _enquire_check_deprec_args(reverse, kwargs, methodname): """Check the keyword arguments to one of the enquire set_sort_* methods. """ if reverse is not None: if 'ascending' in kwargs: raise TypeError('Only one of "reverse" and "ascending" may be specified') if len(kwargs...
def node_pre_rec_fm(true_feature, pred_feature): """ Return the precision, recall and f-measure. :param true_feature: :param pred_feature: :return: pre, rec and fm """ true_feature, pred_feature = set(true_feature), set(pred_feature) pre, rec, fm = 0.0, 0.0, 0.0 if len(pred_feature) ...
def portfolio_view(request): """Display portfolio.""" message = "Hello" return {'message': message}
def COLOR2(obj): """Format an object into string of highlight color 2 (magenta) in console. Args: obj: the object to be formatted. Returns: None """ return '\x1b[1;35m' + str(obj) + '\x1b[0m'
def pretty_size_print(num_bytes): """ Output number of bytes in a human readable format keywords -------- num_bytes: int number of bytes to convert returns ------- output: str string representation of the size with appropriate unit scale """ if num_bytes is None...
def normalize_chrom_name(chrom): """ Add 'chr' prefix if not present Remove all trailing or inner white spaces :param chrom: :return: """ if not chrom.startswith('chr'): chrom = 'chr' + chrom chrom = chrom.strip().replace(' ', '') return chrom
def reverse(text): """ Return the input string reverse. Recursive solution. """ #The empty String translates to False in a boolean context in Python if text: return reverse(text[1:]) + text[0] else: return text
def iterable_or_int_to_list(arg): """Given either an int or an iterable, returns list of items.""" if isinstance(arg, int): return [arg] else: return list(arg)
def get_diff(r): """Given a list of ints r, returns the difference between its max and min""" return max(r) - min(r)
def _gr_div_ ( graph , scale ) : """Scale the graph graph = ... newg = graph / 10 """ return graph * ( 1.0 / scale )
def checkLine(line: str): """ A funtion that checks if a string passed to this function contains key words that need to be processed further Parameters ---------- line : str\n a string that needs to be checked if it contains key words Returns ------- list\n ...
def withinBoard(r, c): """ Check if a r, c position falls within the board >>> withinBoard(2, 2) True >>> withinBoard(0, 2) False >>> withinBoard(8, 8) True >>> withinBoard(8, 9) False >>> withinBoard(1, 1) True """ return (r in range(1, 9) and c in range(1, 9))
def make_quick_reply(replay_items): """ Create quick reply message. reference - `Common Message Property <https://developers.worksmobile.com/jp/document/100500807?lang=en>`_ :param replay_items: Array of return object of make_quick_reply_item function. :return: quick reply content. ...
def previous(some_list, current_index): """ Returns the previous element of the list using the current index if it exists. Otherwise returns an empty string. """ try: return some_list[int(current_index) - 1] # access the previous element except: return ''
def _get_arps(interface, i): """Collects arp for the matching interface""" entries = [] try: for entry in i.get('arp-oper'): if entry.get('interface') == interface.get('name'): entry.pop('interface') entry['time'] = entry.get('time').split('.')[0].strip(...
def build_service_uri(base_uri, partition, name): """Build the proper uri for a service resource. This follows the scheme: <base_uri>/~<partition>~<<name>.app>~<name> :param base_uri: str -- base uri of the REST endpoint :param partition: str -- partition for the service :param name: str -- ...
def is_sorted(items): """Return a boolean indicating whether given items are in sorted order. Running time: O(n) Memory usage: O(n)""" if len(items) in [0, 1]: return True for i in range(len(items) - 1): if items[i] > items[i + 1]: return False return True
def write_program_to_file(program, filename, memory_location, _labels) -> bool: """ Take the assembled program and write to a given filename. Parameters ---------- program: list, mandatory The compiled program filename: str, mandatory The filename to write to memory_locati...
def conservative_state(state1, state2): """ Given two states, return the lower one """ if state1 == state2: return state1 for skey in ["event_0", "event_1", "event_2"]: if state1 == skey or state2 == skey: return skey return "event_3"
def int_or_None(x): """ A little helper function to return an integer from our record or None if it is an empty string. Arguments: - `x`: the value returned from database row e.g. record.get('x') """ if x is None: return None elif x in ("", " "): return None else: ...
def get_indexes (minIndex, nClusters): """ Get the index of the clusters based on the index of the minimum distance between clusters """ index1 = 0 while minIndex >= (nClusters - 1): minIndex -= nClusters - 1 nClusters -= 1 index1 += 1 index2 = minIndex % (nClusters - 1) ...
def check_dict(ref_dict, tst_dict): """Compare dictionaries of inputs and and those loaded from json files""" def to_list(x): if isinstance(x, tuple): x = list(x) if isinstance(x, list): for i, xel in enumerate(x): x[i] = to_list(xel) return x ...
def get_residue_charge(seq): """ Compute net charge - by summing D/E/K/R charges. Parameters: seq: str, Peptide Sequence Returns: float, charge """ return seq.count("D") + seq.count("E") - seq.count("K") - seq.count("R")
def waterSolubility(T, wSP): """ waterSolubility(T, wSP) waterSolubility (ppm by wt) = 10**(A + B/T + C/T^2) Parameters T, temperature in Kelvin wSP, A=wSP[0], B=wSP[1], C=wSP[2] A, B, and C are regression coefficients Returns water solubility in ppm by weight at T ...
def fixed2float(v): """Convert fixed to float""" return v * (1/65536.0)
def replace(string, target, replacement, n=None): """ Description ---------- Replace a target string with a replacement string 'n' number of times. Parameters ---------- string : str - string to iterate\n target : str - string to search for\n replacement : str - string to replace ta...
def get_verification_buffer(message): """ Returns a serialized string to verify the message integrity (this is was it signed) """ return '{chain}\n{sender}\n{type}\n{item_hash}'.format(**message)\ .encode('utf-8')
def unpad_integer(integer, bits=7): """ Decodes a bit-padded integer such as the one used for ID3v2 tag sizes. @param bytearray integer The integer to unpad in its 'raw' byte-array form. @param int bits (optional) The number of non-padded bits to the integer. The default is 7 (as used by ID3v2). ...
def twos_comp(val, bits): """compute the 2's compliment of int value val""" if (val & (1 << (bits - 1))) != 0: val = val - (1 << bits) return val
def strtobool(val): # pragma: no cover """Convert a string representation of truth to true (1) or false (0). True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values are 'n', 'no', 'f', 'false', 'off', and '0'. Raises ValueError if 'val' is anything else. """ val = val.lower() ...
def isascii(s): """Checks how many bytes of non-ascii characters there is in the quote""" total = 0 for t in s: q = len(t.encode('utf-8')) if q > 2: total += q return total < 300
def load_module(module_path, symbols=()): """Loads a module by given module path :param module_path: module path :param type: str """ return __import__(module_path, globals(), locals(), symbols)
def simple_call_string(function_name, argument_list): """Return function_name(arg[0], arg[1], ...) as a string""" return function_name + "(" + \ ", ".join([var + "=" + repr(value) for (var, value) in argument_list]) + ")"
def covariates_at_spikes(spiketimes, behaviour_data): """ Returns tuple of covariate arrays at spiketimes for all neurons """ cov_s = tuple([] for n in behaviour_data) units = len(spiketimes) for u in range(units): for k, cov_t in enumerate(behaviour_data): cov_s[k].append(co...
def get_dict_labels(dictionary): """Returns the keys of a dictionary as list. Args: dictionary (dict): Arbitrary dictionary, e.g. used for parametrization. Returns: dict_labels (list): List of dicationary keys. """ dict_labels = list(dictionary.keys()) return dict_labels
def istmp(name): """Is this a name of a tmp variable?""" return name.startswith("tmp")
def identifying_col_pos_ele(ip_1): """ The task of this function is to identify the coloured elements position ,column value holding the element and sublists where the elements are present Arguments: sublist_seq- A sublist of input grid. Return:Position of coloured elements present in each subli...
def strip(line): """Strip the identation of a line for the comment header.""" if line.startswith(' ' * 4): line = line[4:] return line.rstrip()
def strip_white_spaces(input_list): """Takes a list of string as input Removes the leading and trailing white spaces from each string in the list Returns an output list having the string elements with leading and trailing white spaces removed """ output_list = [] for element in input_list: ...
def parse_flask_rule(rule: str): """Parses a flask rule (URL), and returns an openapi compatible version of the url""" parsed_rule = [] index = -1 while index < len(rule): index += 1 if index > len(rule) - 1: break char = rule[index] if char != "<": ...
def fib(n): """ Generate the first N fibonacci numbers Parameters ---------- str : String the provided input Returns ------- int the 2 numbers divided """ if n <= 1: return n else: return fib(n-1) + fib(n-2)
def interpolate(a=[], b=[], amt=0.5): """ Linear interpolation for each dimension i in a,b a,b: array-like or float """ return (1 - amt) * a + amt * b
def cal_accuracy_on_3(sample_label_prob_dict_list, test_label_list): """ :param sample_label_prob_dict_list: [ {1: 0.2, 2:0.15, 3:0.2, ..., 9:0.1} {1: 0.2, 2:0.15, 3:0.2, ..., 9:0.1} ... ] test_label_list: [1,2,5...
def binary_search(l, item): """Searches the list for item if found""" mid = len(l)//2 first = 0 last = len(l)-1 found = False index = -1 while first <= last and not found: if item == l[mid]: found = True index = mid elif item < l[mid]: last...
def fibonacci(n): """Return a list containing the Fibonacci series up to n.""" result = [] a, b = 0, 1 while a < n: result.append(a) # For returning to caller. a, b = b, a + b return result
def to_locale(language): """Simplified copy of `django.utils.translation.to_locale`, but we need it while the `settings` module is being loaded, i.e. we cannot yet import django.utils.translation. Also we don't need the to_lower argument. """ p = language.find('-') if p >= 0: # Get...
def single_letter_count(word, letter): """How many times does letter appear in word (case-insensitively)? >>> single_letter_count('Hello World', 'h') 1 >>> single_letter_count('Hello World', 'z') 0 >>> single_letter_count("Hello World", 'l') 3 ...
def tuple_into_seq(list_tuple): """ Extract all repeating motifs. :param list_tuple: list(tuple) - motif sequence in list((seq, rep)) format :return: str - motif sequence in ACATCAG,3-TGT,CATCGACT format """ return ','.join([s if r == 1 else '%d-%s' % (r, s) for (s, r) in list_tuple])
def get_union_of_tags(documents): """ Get a list of every tag on any document in ``documents``. """ tags = [] for doc in documents: for t in doc.tags: if t not in tags: tags.append(t) return tags
def format_header_block_plus(string: str): """Returns a header for use with my function files. Example: #######################################\n ########### ARRAY FUNCTIONS ###########\n #######################################\n """ newstring = "" newstring += "{0:#<39}".f...
def parse_extension(name): """Get the extention from a file name. If zipped or tarred, can contain a dot""" split_name = name.split('.') if len(split_name) == 2: fmt = split_name[-1] elif len(split_name) > 2 and 'gz' in name: fmt = '.'.join(split_name[-2:]) else: fmt = split_...
def is_hyperopt(x): """Check whether a given object is a hyperopt argument The format expected is ('hp_NAME_OF_FUNCTION', 'name for hyperopt', remaining, arguments) """ if isinstance(x, (tuple, list)): if isinstance(x[0], str): s = x[0].split("_", 1) if s[0] == "hp": ...
def _dummyJit(*args, **kwargs): """ Dummy version of jit decorator, does nothing """ if len(args) == 1 and callable(args[0]): return args[0] else: def wrap(func): return func return wrap
def raw_to_rules(raw_rules): """ :param raw_rules: :return: Gets raw rules as received from API and extracts only the relevant fields """ rules = list() for rule in raw_rules: source_services = rule.get('sourceService', {}) if isinstance(source_services, list): s...
def __modifiy_discussion_url(prep_dict: dict) -> dict: """ Adds the /discuss prefix for every url entry :param prep_dict: :return: """ # modify urls for the radio buttons for el in prep_dict: if el == 'url': prep_dict['url'] = '/discuss' + prep_dict['url'] return pre...
def _toRoutePath(resource, route): """ Convert a base resource type and list of route components into a Swagger-compatible route path. """ # Convert wildcard tokens from :foo form to {foo} form convRoute = [ '{%s}' % token[1:] if token[0] in {':', '+'} else token for token in rou...
def get_formatted_duration(seconds: float, format: str="hms") -> str: """Format a time in seconds. :param format: "hms" for hours mins secs or "ms" for min secs. """ mins, secs = divmod(seconds, 60) if format == "ms": t = "{:d}m:{:02d}s".format(int(mins), int(secs)) elif format == "hms":...
def ifelse (pred:bool, cons, alt): """ If predicate consequent else alternative """ if pred: return cons else: return alt
def walltime(time): """Return a qsub-style walltime string for the given time (in hours).""" hours = int(time) time -= hours minutes = int(time * 60) time -= minutes / 60 seconds = int(time * 3600) return ":".join(map(str, (hours, minutes, seconds)))
def abbr_status(value): """ Converts RFC Status to a short abbreviation """ d = {'Proposed Standard':'PS', 'Draft Standard':'DS', 'Standard':'S', 'Historic':'H', 'Informational':'I', 'Experimental':'E', 'Best Current Practice':'BCP', 'Intern...
def parse_message_for_command(entry): """ parse_message_for_command(entry) - look at the given message and determine if it was a bot command. If so, return the following information: action, personId, personEmail, language - action : the string to return so that the calling method know...
def append_no_duplicate(config, path, base, nxt): """ a list strategy to append only the elements not yet in the list.""" for e in nxt: if e not in base: base.append(e) return base
def alternate_transformation(text): """ Alternates the capitalization of a string's characters """ return "".join( [char.lower() if index % 2 else char.upper() for index, char in enumerate(text)] )
def get_consensus(padded): """Return consensus from matrix of aligned sequences.""" seq = {x: {"A": 0, "C": 0, "G": 0, "U": 0} for x in range(len(padded[0]))} for kmer_split in padded: for pos, base in enumerate(kmer_split): try: seq[pos][base] += 1 except Key...
def process_hub_timeout(bit): """Return the HUB timeout.""" if bit == '1': return '5 Seconds' return '2 Seconds'
def generate_parameter_map(parameters): """ Generates mapping of parameters for fasm features for architecture definition. """ xml = [] xml.append("<meta name=\"fasm_params\">") for feature, parameter in sorted(parameters): xml.append(" {} = {}".format(feature, parameter)) xml....
def load_array(loader, filename, index): """ Load a data array from the specified index within a file. """ return loader(filename, index)
def _dashCapitalize(name): """ Return a byte string which is capitalized using '-' as a word separator. @param name: The name of the header to capitalize. @type name: L{bytes} @return: The given header capitalized using '-' as a word separator. @rtype: L{bytes} """ return b'-'.join([wo...
def _adjust_component(color: int) -> int: """ Returns an integer representing the midpoint of one of the four quadrants of a single color scale that range from 0-255 depending on the value of the color inputted (color). >>> _adjust_component(0) >>> 31 >>> _adjust_component(40) ...
def _tl_sub(tl1, tl2, alpha=1.0): """Difference between two tensor lists.""" return [ t1 - alpha * t2 for t1, t2 in zip(tl1, tl2) ]
def rescale_value(value, current_limits, new_limits): """ Given a value and the limits, rescales the value to the new limits input: value : float variable containing the value current_limits : a tuple containing the lower and upper limits of the valu...
def statistics(*args): """ Compute the average, minimum and maximum of a list of numbers. Input: a variable no of arguments (numbers). Output: tuple (average, min, max). """ # this function takes variable argument lists avg = 0; n = 0 # avg and n are local variables for term in args: ...
def list_avg(l): """Calculate average of an integer list after removing outliers. Return average as float""" l.sort() return sum(l[1:-1])/float(len(l[1:-1]))
def col(label: str) -> int: """Return the correct index given an Excel column letter.""" if not label.isalpha(): raise ValueError(f"'{label}' is not a valid column label.") return ( sum( (ord(char) - ord("A") + 1) * (26 ** position) for position, char in enumerate(rev...
def keyword_as_title(keyword): """ Given a dictionary key or other token-like keyword, return a prettier form of it use as a display title. Example: keyword_as_title('foo') => 'Foo' keyword_as_title('some_text') => 'Some Text' :param keyword: :return: a string which is the keyword ...
def merge_value_dicts(old_value_dict, new_value_dict, zero_missing=False): """ Merge an old and new value dict together, returning the merged value dict. Value dicts map from label values tuple -> metric value. Values from the new value dict have precidence. If any label values tuples from the old...
def remote_file_exists(filename): """Return True if the given file exists on the device and False otherwise.""" try: adb_shell('test -f %s' % filename) return True except Exception: return False
def remove_padding(plaintext): """ This function removes A VALID(!) PKCS#7 padding. Args: plaintext (bytes): PKCS#7 padded data """ return plaintext[:-plaintext[-1]]
def val_to_boolean(val): """ Convert any value to boolean Boolean: return as-is - Integer: 1 = True, 0 = False - Strings (case-insensitive): '1', 'true', 't', 'yes', 'on', 'y' = True - '0', 'false', 'f', 'no', 'off', 'n' = False Args: val: value to convert Returns: bo...
def dups(lst): """ shows the duplicates in a list """ seen = set() # adds all elements it doesn't know yet to seen and all other to seen_twice seen_twice = set(x for x in lst if x in seen or seen.add(x)) # turn the set into a list (as requested) return list(seen_twice)
def ev(dist): """ :param dist: dictionary representing a probability distribution :return: the expected value of this distribution """ assert sum(dist.values()) == 1 return sum(dist[v] * v for v in dist.keys())
def resistor_value_parser(RValue): """Convert a resistor value. Parameters ---------- RValue : float Resistor value. Returns ------- float Resistor value. """ if type(RValue) is str: RValue = RValue.replace(" ", "") RValue = RValue.replace("meg", "m...
def permlist_to_tuple(perms): """ convert list of lists to tuple of tuples in order to have two level iterables that are hashable for the dictionaries used later """ return tuple(tuple(perm) for perm in perms)
def generate_filename_from_str(string): """ Generate a valid filename from a given string. - replace all spaces and dashes with underscore. - only keeps alphanumerical chars :param string: the string to create the filename from :returns: the generated string, a valid filename """ keep...
def __is_ascii(rule_string): """ Takes the string of the rule and parses it to check if there are only ascii characters present. :param rule_string: the string representation of the yara rule :return: true if there are only ascii characters in the string """ return len(rule_string) == len(rule_s...
def percentile_nonweighted(L, p): """ Returns the percentile value from a list of non-weighted values @param L - list of numerical values @param p - float of the probability value @return float value of the percentile value of the list """ if len(L)>0: return L[int(len(L) * p)] ...
def extract_read_ref_origin(readname): """Extracts the name of the reference the read originated from. Read names are expected to look like this: >@NC_012803.1-4276933/2 >gi|29611500|ref|NC_004703.1|_Bacteroides_thetaiotaomicron_VPI-5482_nr0_+_R1 The first part of the read contains the sequence na...
def JoinVersion(version_tuple): """Create a string from a version tuple. The tuple should be of the form (18, 0, 1025, 163). """ return '.'.join(map(str, version_tuple))
def constant_potential_single_charge(phi0, radius, kappa, epsilon): """ It computes the surface charge of a sphere at constant potential, immersed in water. Arguments ---------- phi0 : float, constant potential on the surface of the sphere. radius : float, radius of the sphere. kappa ...
def find(value, node): """Find node with val equal to value""" while node: if value < node.val: node = node.left elif value > node.val: node = node.right else: return node
def build_self_awareness_detection_prompt(question, answer): """Builds the prompt to check if the model can detect answers generated by self-aware models. Args: answer: String: the model should guess if the answer was generated by a self-aware model question: String: the question, from which th...
def get_error(code): """Method for generating error response.""" return { 'status': 'error', 'code': code }
def evaluate(function, param1, param2): """ Returns <function>, called with <param1> and <param2> """ return function(param1, param2)
def fixedcase_word(w, truelist=None): """Returns True if w should be fixed-case, None if unsure.""" if truelist is not None and w in truelist: return True if any(c.isupper() for c in w[1:]): # tokenized word with noninitial uppercase return True if len(w) == 1 and w.isupper() and...
def next_largest_coin(coin): """Return the next coin. >>> next_largest_coin(1) 5 >>> next_largest_coin(5) 10 >>> next_largest_coin(10) 25 >>> next_largest_coin(2) # Other values return None """ if coin == 1: return 5 elif coin == 5: return 10 elif coin ==...
def get_group_definitions_list(mmtf_dict): """Gets a list of group definitions from the .mmtf dict and packs its atom attributes into atoms dicts. :param dict mmtf_dict: the .mmtf dictionary to read. :rtype: ``list``""" group_definitions = [] for group in mmtf_dict["groupList"]: atoms...
def subseq(letters, subseq, ordered=True): """ Returns whether the letters contains the given subsequence. >>> subseq('snake', 'sake') True >>> subseq('snake', 'sea') False >>> subseq('snake', 'sea', ordered=False) True """ for c in subseq: if c not in letters: r...
def s3_build_path(bucket,key): """ Build the full path to the file """ return "s3://{}/{}".format(bucket,key)
def _get_unretained_cw_log_group_resource_keys(template): """Return the keys to all CloudWatch log group resources in template if the resource is not to be retained.""" unretained_cw_log_group_keys = [] for key, resource in template.get("Resources", {}).items(): if resource.get("Type") == "AWS::Logs...