content
stringlengths
42
6.51k
def filter_vdj_alarms(all_alarms, sample_properties): """ Only get subset of metric alarms """ chain_filter = sample_properties.get('chain_type') if chain_filter is None: return all_alarms result = [] for alarm in all_alarms: # No filters specified; don't filter if 'filters'...
def get_bigram_scores(text_words, min_bgfreq=2.): """ compute scores for identifying bigrams in a collection of texts compute unigram and bigram frequencies (of words) and give a score for every bigram. depending on this score (e.g. if higher than a threshold), bigram phrases can be identified in th...
def centerOfMass(*args): """input: [m, x, y, z, r] variables: m=mass, x=position-along-x, y=position-along-y, z=position-along-z, r=position-along-radius""" mi=0; xi=1; yi=2; zi=3; ri=4 m_total = sum([item[mi] for item in arg...
def time(present_t, start_t, lap): """ calculates the starting time of the present lap :param present_t: present time :param start_t: starting time of the lap :param lap: duration of the lap :return: starting time of the present lap """ if present_t - start_t >= lap: start_t = pr...
def infer_time_unit(time_seconds_arr): """ Determine the most appropriate time unit for an array of time durations specified in seconds. e.g. 5400 seconds => 'minutes', 36000 seconds => 'hours' """ if len(time_seconds_arr) == 0: return 'hours' max_time_seconds = max(time_seconds_arr...
def is_binary_dxf_file(filename: str) -> bool: """Returns ``True`` if `filename` is a binary DXF file.""" with open(filename, "rb") as fp: sentinel = fp.read(22) return sentinel == b"AutoCAD Binary DXF\r\n\x1a\x00"
def outputCode(x): """ x = <-4.1714, 4.1714> y = <0, 1> Formula: y = (x + 4.1714) / 8.3428 """ x = float(x) return (x + 4.1714) / 8.3428
def replace_dict_keys(dicts, replace_list_dict): """ Replace values in `dicts` according to `replace_list_dict`. Parameters ---------- dicts : dict Dictionary. replace_list_dict : dict Dictionary. Returns ------- replaced_dicts : dict Dictionary. Examples ...
def es5(n): """ Write a script that, given an input number n, computes the numbers of the Fibonacci sequence that are less than n. """ if n <= 0: return 0 if n <= 1: return 1 a, b = 0, 1 cont = 2 while a + b < n: b += a a = b - a cont += 1 ...
def _is_slice_in_list(s, l): """ Check if list s in in list l :param s: first array :param l: second array :return: bool """ len_s = len(s) return any(s == l[i:len_s + i] for i in range(len(l) - len_s + 1))
def _stix_vid_to_version(stix_vid): """ Convert a python package name representing a STIX version in the form "vXX" to the dotted style used in the public APIs of this library, "X.X". :param stix_vid: A package name in the form "vXX" :return: A STIX version in dotted style """ assert len(st...
def exclude_zero_decimals(value): """ Returns removes trailing zeros from decimal numbers if all numbers after the decimal are zeros. """ if value==None: return_value=value else: str_value = str(value) value_length = len(str_value) decimal_index = str_value.index(...
def name_to_path_name(name): """ :param name: :return: """ return name.replace("\\", "\\\\")\ .replace(".", r"\.")\ .replace("$", r"\$")\ .replace("|", r"\|")\ .replace("[", r"\[")\ .replace("]", r"\]")
def contains_num(token): """ Return True for - Dates: 21.01.2011 - Probably egzotic entities: B2B, sum41 - Skype names: duygu621 Args: token: single token Returns: Booelan Raises: None Examples: >>> contains_num("duygu") False >>> con...
def rcomp(s): """Does same thing as reverse_complement only cooler""" return s.translate(str.maketrans("ATCG","TAGC"))[::-1]
def get_verification_code(hash_value): """Compute Mobile-ID verification code from a hash Excerpt from https://github.com/SK-EID/MID#241-verification-code-calculation-algorithm 1. 6 bits from the beginning of hash and 7 bits from the end of hash are taken. 2. The resulting 13 bits are transformed into...
def first_line(s): """Return first full line from string s (not including the '\n') """ i = s.find('\n') if i > 0: return s[:i] else: raise RuntimeError("can't find '\\n' in first_line")
def urlQuoteSpecific(s, toQuote=''): """ Only quote characters in toQuote """ result = [] for c in s: if c in toQuote: result.append("%%%02X" % ord(c)) else: result.append(c) return "".join(result)
def format_key(key): """ Format the key provided for consistency. """ if key: return key if key[-1] == "/" else key + "/" return "/"
def format_skills(items): """Format list of skills to a string for CLI output.""" list_str = '' for item in items: list_str += ( '{line}\n' 'Name: {name}\n' 'Description: {description}\n' 'Protocols: {protocols}\n' 'Version: {version}\n' ...
def unbox_usecase(x): """ Expect a set of numbers """ res = 0 for v in x: res += v return res
def allZeroDict(source): """ Checks whether or not a dictionary contains only 0 items :param source: a dictionary to test :returns: bool -- whether or not all entries in the dictionary are equal to zero """ for i in source.values(): if i != 0: return False return True
def stringifydict(res): """[summary] Args: res ([type]): [description] Returns: [type]: [description] """ a = {} for k, v in res.items(): if type(v) is dict: a[k] = stringifydict(v) else: a[str(k)] = v return a
def rec_cmp_releases(one, two): """Recursive function that compares two version strings represented as lists to determine which one comes "after" / takes precedence, or if they are equivalent. List items must be integers (will throw TypeError otherwise). If the left argument ("one") is a later version...
def calculateYVertice(termA, termB, termC, xVertice): """ Calculates the value of the vertice Y. """ vertice = ((termA*(pow(xVertice, 2)) + (termB*xVertice) + termC)) return vertice
def locate_s_in_RHS(surf_index, surf_array): """Find starting index for current surface on RHS This is assembling the RHS of the block matrix. Needs to go through all the previous surfaces to find out where on the RHS vector it belongs. If any previous surfaces were dirichlet, neumann or asc, then they...
def parse_integer_range(bounds_string): """ Returns an integer lower bound and upper bound of the range defined within <bounds_string>. Formats accepted include 'n', 'n+', and 'm-n'. :param bounds_string: String representing a range of integers :return: Pair of integer lower bound and upper bound o...
def sanitize_path(path): """Cleaning up path for saving files.""" return "".join([c for c in path if c.isalpha() or c.isdigit() or c in ' .-_,']).rstrip()
def interpolate(point1, point2, numberOfPoints, roundToInt = True): """<numberOfPoints> should be greater or equal to 1. <numberOfPoints> is number of points from point1 until point2.""" if numberOfPoints == 1: return([point1]) interval = (point2 - point1) / numberOfPoints if roundToInt: return([int(round(poin...
def default_case(experiment_code, participantid, project_id): """Creates a minimal case.""" return { "type": "case", "experiments": {"submitter_id": experiment_code}, "submitter_id": participantid, "primary_site": "unknown", "disease_type": "unknown", "project_id"...
def smoothstep(a, b, x): """ Returns the Hermite interpolation (cubic spline) for x between a and b. The return value between 0.0-1.0 eases (slows down) as x nears a or b. """ if x < a: return 0.0 if x >= b: return 1.0 x = float(x - a) / (b - a) return x * x * (3 - 2 * x)
def reverse_string_iterative(s): """ Returns the reverse of the input string Time complexity: O(n) Space complexity: O(n) More efficient, only 3 O(n) operations """ chars = list(s) # O(n) i, j = 0, len(s) - 1 while i < j: # O(n) chars[i], chars[j] = chars[j], chars[i] i += 1 j -= 1 ...
def line_interpolate_y(line, x): """Interpolates y values on a line when given x To avoid duplicate hits for nodes level with the joints between lines, the end of a line is not considered an intersection.""" if line[0][0] == x: return line[0][1] #if line[1][0] == x: # return lin...
def print_result(error, real_word): """" print_result""" if error == 5: print("You lost!") print("Real word is:", real_word) else: print("You won!") return 0
def get_config_contract(config): """ A function to delete context and dockerfile_path from config """ if not config: return config if "context" in config: del config["context"] if "dockerfile_path" in config: del config["dockerfile_path"] return config
def merge(a,b): """ Function to merge two arrays """ c = [] while len(a) != 0 and len(b) != 0: if a[0] < b[0]: c.append(a[0]) a.remove(a[0]) else: c.append(b[0]) b.remove(b[0]) if len(a) == 0: c += b else: c += a ret...
def seq_sqrt(xs): """Computes and returns a list of the square-roots of each value in xs.""" sqrts = [] for n in xs: if n >= 0: sqrts.append(n ** 0.5) else: sqrts.append(0) return sqrts
def tokenise(line): """Tokenise a string and return a list. Split a line of text into tokens separated by whitespace, but ignoring whitespace that appears within quotes. This attempts to do a similar to job the CCP4 'parser' (which is itself actually a tokeniser) in the core CCP4 libraries. The hard part ...
def solution(s: str) -> int: """ >>> solution('(()(())())') 1 >>> solution('())') 0 """ count = 0 m = {'(': 1, ')': -1} for token in s: count += m[token] if count < 0: return 0 return 0 if count else 1
def untrack_cache_storage_for_origin(origin: str) -> dict: """Unregisters origin from receiving notifications for cache storage. Parameters ---------- origin: str Security origin. """ return { "method": "Storage.untrackCacheStorageForOrigin", "params": {"origin": ori...
def create_distribution_chart(p_summary): """ Helper function that generates Tool distribution chart Args: p_summary (dictionary): parsed summary.yaml """ graph_data = [set() for i in range(len(p_summary.keys()))] all_fusions = [fusions for _, fusions in p_summary.items()] all_fusion...
def count_swaps(str_one, str_two): """ return the minimum number of swaps necessary to change str_one into str_two """ left, right = '', '' swap_count = 0 # iterate strings and find differences. store non-matching characters in left and right # evaluate, and count matching pairs that can be ...
def get_ion_actor_id(process): """Given an ION process, return the ion-actor-id from the context, if set and present""" ion_actor_id = None if process: ctx = process.get_context() ion_actor_id = ctx.get('ion-actor-id', None) if ctx else None return ion_actor_id
def UpperCase(text : str): """Returns Uppercase text.""" return text.upper()
def scrub_external_ids(eids): """ Removes the index from "univaf_v.[_.]" keys. """ for i in range(len(eids)): if 'univaf' not in eids[i]: continue if 'v' not in eids[i].split(':')[0].split('_')[-1]: # very risky! assumes keys to be "univaf.v._.:.*" eid...
def line_id_2_txt(line_id): """ Convert line id (integer) to string nnnn :return: line_id_txt -> <string> ID de la linia introduit en format text """ line_id_str = str(line_id) if len(line_id_str) == 1: line_id_txt = "000" + line_id_str elif len(line_id_str) == 2: line_id_txt...
def suppress_non_unicode(dirty_string): """Get rid of non-unicode characters. WARNING: This loops through each character in strings. Use sparingly. http://stackoverflow.com/questions/20078816/replace-non-ascii-characters-with-a-single-space """ return '' .join([i if ord(i) < 128 els...
def make_hit(card, cards, deck): """ Adds a card to player's hand """ if card in deck: cards.append(card) deck.remove(card) return cards
def bsearch(n, pred): """ Given a boolean function pred that takes index arguments in [0, n). Assume the boolean function pred returns all False and then all True for values. Return the index of the first True, or n if that does not exist. """ # invariant: last False lies in [l, r) and pred(l) i...
def gctor2newc(name, args): """Create a new container object based on generator-constructor name.""" if name == "construct_yaml_set": return set() if name == "construct_yaml_map": return {} if name == "construct_yaml_object": return args[0].__new__(args[0]) return []
def convert_rankine_to_celcius(temp): """Convert the temperature from Rankine to Celcius scale. :param float temp: The temperature in degrees Rankine. :returns: The temperature in degrees Celcius. :rtype: float """ return ((temp - 491.67) * 5) / 9
def enum(cls): """Make a class behave like an enumerated type by generating a reverse mapping for all the names defined on the class which are uppercased. """ rmap = {} for name in dir(cls): if name == name.upper(): k = cls.__name__ + "_" + name v = getattr(cls, name)...
def get_status_from_node(data_item): """ Extract the status conditions from the data Returns: a dict combining the hostname and the status conditions. """ addresses = data_item['status']['addresses'] address = None for addr in addresses: if addr['type'] == 'Hostname': address...
def pop_known_arguments(args): """Extracts known arguments from the args if present.""" rest = [] run_test_cases_extra_args = [] for arg in args: if arg.startswith(('--gtest_filter=', '--gtest_output=')): run_test_cases_extra_args.append(arg) elif arg == '--run-manual': run_test_cases_extra_...
def duplicate_encode_oneline_list(word): """List comp version.""" return "".join(["(" if word.count(c) == 1 else ")" for c in word])
def serialize_monto(valor=0, moneda="MXN"): """ $ref: '#/components/schemas/monto' """ if valor: return { "valor": 0 if valor is None else int(valor), "moneda": moneda } return {"valor": 0, "moneda": moneda}
def _fk(feature_name, channel, target): """Construct a dict key for a feature instance""" return "{}::{}::{}".format(feature_name, channel, target)
def binary_to_decimal(binary): """Converts a binary number into a decimal""" reversed_binary = binary[::-1] # i = correct power when reversed decimal = 0 for i, value in enumerate(reversed_binary): if value == "0": continue # ignore 0 because no value decimal += 2**i # m...
def calScNoEq1(GaDe, GaVi, GaDiCoi): """ calculate Schmidt number args: GaDe: gas density [kg/m^3] GaVi: gas viscosity [Pa.s] | [kg/m.s] GaDiCoi: gas component diffusivity coefficient [m^2/s] """ # try/except try: return (GaVi/GaDe)/GaDiCoi except Exception ...
def formatSurveyStr(survey): """Format survey keyword data @param[in] surveyData: the value of guider.survey or sop.survey (a pair of strings, either of which may be None) """ surveyStrList = [] if survey[0] is None: surveyStrList.append("?") else: surveyStrList.append(s...
def html_strip(text): """ Strips html markup from text """ mark = 0 markstart = 0 markend = 0 index = 0 occur = 0 for i in text: if i == "<": try: if text[index+1] != " ": mark = 1 markstart = index ...
def _parse_package_name(name: str) -> str: """ Force lower case and replace underscore with dash to compare environment packages (see https://www.python.org/dev/peps/pep-0426/#name) Args: name: Unformatted package name Returns: Formatted package name """ return name.lower()...
def count_sequences(data): """Count the number of JSON NE sequences. :param data: Dictionary of NE sequences :type data: Dictionary :return: Number of NE sequences :rtype: Integer """ count = 0 try: for value in data.items(): if isinstance(value, list): ...
def convert_to_string(num): """ Converts a base 27 number back into a string @param num The number we wish to convert @return converted_string The string of that number @complexity O(M) where M the length of the string """ converted_string = "" ...
def check_win(board,player_marker): """ Checks if computer/player wins """ return ((board[0] == player_marker and board[1] == player_marker and board[2] == player_marker) or (board[3] == player_marker and board[4] == player_marker and board[5] == player_marker) or (board[6] == player_ma...
def clean_escseq(element, encodings): """Remove escape sequences that Python does not remove from Korean encoding ISO 2022 IR 149 due to the G1 code element. """ if 'euc_kr' in encodings: return element.replace( "\x1b\x24\x29\x43", "").replace("\x1b\x28\x42", "") else: ...
def refinement_func_area(tri_points, area): """ refine (equivalent to the max_volume parameter) """ max_area = 0.005 return bool(area > max_area)
def backwards(string): """Return string, but backwards.""" return string[::-1] # Could also be: # return ''.join(reversed(string))
def get_qual_range(qual_str): """ >>> get_qual_range("DLXYXXRXWYYTPMLUUQWTXTRSXSWMDMTRNDNSMJFJFFRMV") (68, 89) """ vals = [ord(c) for c in qual_str] return min(vals), max(vals)
def makeListList(roots): """Checks if the element of the given parameter is a list, if not, creates a list with the parameter as an item in it. Parameters ---------- roots : object The parameter to be checked. Returns ------- list A list containing the parameter. ""...
def valid_passphrase(passphrase: str) -> bool: """Find if there are no repeated words in this passphrase.""" all_words = passphrase.split() return len(all_words) == len(set(all_words))
def getLineFromPoints(point1, point2): """ Get line parameter (y = mx +c) from two points. Parameters ---------- point1, point2 : list of int Coordinates of the two points Returns ------- m, c : float Line parameters for y = mx +c """ # m = (y2 - y1)/(x1 - x2) ...
def to_img_tag(b64): """Create an Img html tag from a base64 string. Parameters ---------- b64 : :class:`str` A base 64 string. Returns ------- :class:`str` The <img> tag. """ return f'<img src="data:image/jpeg;base64, {b64}"/>'
def howmany_within_range(row, minimum, maximum): """Returns how many numbers lie within `maximum` and `minimum` in a given `row`""" count = 0 for n in row: if minimum <= n <= maximum: count = count + 1 return count
def domain_level(host): """ >>> domain_level('') 0 >>> domain_level(' ') 0 >>> domain_level('com') 1 >>> domain_level('facebook.com') 2 >>> domain_level('indiana.facebook.com') 3 """ if host.strip() == '': return 0 else: raw_parts = host.strip()...
def guess_module_name(fct): """ Guesses the module name based on a function. @param fct function @return module name """ mod = fct.__module__ spl = mod.split('.') name = spl[0] if name == 'src': return spl[1] return spl[0]
def encrypt(plaintext, key): """ encrypt encryption function. Encrypts the text using the Caesar Cypher method. :param plaintext: text block input :type plaintext: str :param key: key for encryption :type key: int :return: text block output :rtype: str """ cyphertext = '' ...
def getValid(pair1, pair2): """ Validate that the pair does not have the same key used twice """ res = [] for p1 in pair1: for p2 in pair2: if not p1 & p2 and p1|p2 not in res: res.append(p1|p2) return res
def orderTranscriptsByChromosome(transcripts): """ orders a set of transcripts by chromosome """ chromosomes = {} for trans_id in transcripts.keys(): seqname = transcripts[trans_id][0]['seqname'] if seqname not in chromosomes: chromosomes[seqname] = [trans_id] els...
def factorial(x): """This function returns the factorial of a single input/argument.""" # check if input value is negative or positive if x < 0: return print("Factorials do not exist for negative numbers.") else: y = 1 for i in range(1, x + 1): y = y * i retu...
def fully_qualified_classname(class_or_instance): """Get the fully qualified Python path of a class (or instance). Parameters ---------- class_or_instance : any The class (or instance of a class) to work on Returns ------- str The fully qualified, dotted Python path of that...
def _expand(dat, counts, start, end): """ expand the same counts from start to end """ for pos in range(start, end): for s in counts: dat[s][pos] += counts[s] return dat
def escape(container, field, app_map=None): """ See: http://www.hl7standards.com/blog/2006/11/02/hl7-escape-sequences/ To process this correctly, the full set of separators (MSH.1/MSH.2) needs to be known. Pass through the message. Replace recognised characters with their escaped version. Return a...
def gray(s): """Color text gray in a terminal.""" return "\033[1;30m" + s + "\033[0m"
def appointment_removal(parent, list_to_remove): """ Removes the appointment in list_to_remove from parent. """ for element in list_to_remove: for index in range(0, len(parent)): parent[index] = \ [item for item in parent[index] if item != element]...
def tei_to_omeka_header(csv_header_info): """ Transforms an XML-TEI header path to a Omeka (semantic-web compliant) header.""" # XML-TEI headers elements to Linked Data correspondences xml_tag_to_voc = { u"#fileDesc#titleStmt_title": u"dc:title", u"#fileDesc#titleStmt_author_key": u"dc:cre...
def n2npairs(n): """return number of pairs for n conditions. see also scipy.special.binom.""" return (n - 1) * n / 2
def get_lcm(num1,num2): """ returns lowest common multiple amoung two numbers """ if(num1>num2): num = num1 den = num2 else: num = num2 den = num1 rem = num % den while(rem != 0): num = den den = rem rem = num % den gcd =...
def parse_id(text): """Parse a string into a list of integers. :param str text: the input string. :return list: a list of IDs which are integers. :raise ValueError Examples: Input IDs separated by comma: parse_id("1, 2, 3") == [1, 2, 3] parse_id("1, 2, ,3") == [1, 2, 3] parse_i...
def convert_to_days(period_type, time_to_elapse): """ :param period_type: :param time_to_elapse: :return: """ return time_to_elapse * 7 if 'week' in period_type else time_to_elapse * 30
def parallel_multiplier(items): """Determine if we will be parallelizing items during processing. """ multiplier = 1 for data in (x[0] for x in items): if data["config"]["algorithm"].get("align_split_size"): multiplier += 50 return multiplier
def K(u, kap, eps): """Compute diffusion function .. math:: K(u) = \kappa \, (1 + \varepsilon u)^3 + 1 Parameters ---------- u : array_like Temperature variable. kap : float Diffusion parameter. eps : float Inverse of activation energy. Returns ---...
def Q(p0, p1, v0, v1, t0, t1, t): """Basic Hermite curve.""" s = (t-t0)/(t1-t0) h0 = (2*s+1)*(s-1)*(s-1) h1 = (-2*s+3)*s*s h2 = (1-s)*(1-s)*s*(t1-t0) h3 = (s-1)*s*s*(t1-t0) return h0*p0 + h1*p1 + h2*v0 + h3*v1
def pprint_blockers(blockers): """Pretty print blockers into a sequence of strings. Results will be sorted by top-level project name. This means that if a project is blocking another project then the dependent project will be what is used in the sorting, not the project at the bottom of the depende...
def accept_file(file, filters): """ Returns True if file shall be shown, otherwise False. Parameters: file - an instance of FileSystemObject filters - an array of lambdas, each expects a file and returns True if file shall be shown, otherwise False. ""...
def _to_initials(state): """ Given a state, returns its initials """ states = { 'Alaska': 'AK', 'Alabama': 'AL', 'Arkansas': 'AR', 'American Samoa': 'AS', 'Arizona': 'AZ', 'California': 'CA', 'Colorado': 'CO', 'Connecticut': 'CT', '...
def map_args(args): """used to filter arguments passed in on the command line that should also be passed as keyword args to make_map""" arg_set = set(['starting_year', 'ending_year', 'ranking_algorithm', 'similarity_algorithm', 'filtering_algorithm', 'number_of_terms', ...
def gen_rate_step(n, schedule): """ :param n: the current iteration number :param schedule: a dictionary where the keys are the min value for the step and the values are the corresponding rate; for example, {0: 0.005, 200: 0.0002, 400: 0.0001} is an annealing schedule where iterations...
def is_valid_minute(minute): """ Check if minute value is valid :param minute: int|string :return: boolean """ return (minute == '*') or (59 >= minute >= 0)
def contained_in_others(ls, others): """ Identifies whether all of the elements in ls are contained in the lists of others (a list of lists of items (O(n^2)) """ return all(any([elem in other_ls for other_ls in others]) for elem in ls)