content
stringlengths
42
6.51k
def is_vowel_offset(c_offset): """ Is the offset a vowel """ return (c_offset>=0x04 and c_offset<=0x14)
def mergesort(a): """Iteratively implemented bottom-up mergesort. Returns inversion count.""" swaps = 0 aux = [] def merge(low, mid, high): nonlocal swaps assert not aux, 'auxiliary storage should be empty between merges' left = low right = mid # Merge elements...
def replaceMultiple(mainString, toBeReplace, newString): """[Replace a set of multiple sub strings with a new string] Args: mainString ([string]): [String in which the replacement will be done] toBeReplace ([list]): [A list which elements will be replaced by a newString] newString...
def mv_from_common_values_2(col_mvs, score=1): """ Return mv candidates for missing values that are already candidates in at least two columns. """ # Make dict with key: mv_candidate value: list of columns where applicable val_mvs = dict() for col, tuples in col_mvs.items(): for...
def muc_micro(gold_mentions, response_mentions): """ M. Vilain, J. Burger, J. Aberdeen, D. Connolly, and L. Hirschman. 1995. A model theoretic coreference scoring scheme. In MUC-6. https://www.aclweb.org/anthology/M/M95/M95-1005.pdf The MUC measure focuses on the links (pairs of mentions) and...
def find_phone(p_id, phone_data): """ Finds the phone corresponding to the given user id """ if p_id in phone_data['ids']: position = phone_data['ids'].index(p_id) return phone_data['names'][position] return "-"
def parse_str_to_int(workflow_parameters): """Parse integers stored as strings to integers. >>> parse_str_to_int({'sleeptime': "'2'"}) {'sleeptime': 2} >>> parse_str_to_int({'sleeptime': '2'}) {'sleeptime': 2} >>> parse_str_to_int({'sleeptime': 'two'}) {'sleeptime': 'two'} >>> parse_str...
def closest_ref_length(references, hyp_len): """ This function finds the reference that is the closest length to the hypothesis. The closest reference length is referred to as *r* variable from the brevity penalty formula in Papineni et. al. (2002) :param references: A list of reference trans...
def set_mode(mode_input): """ Setter of mode of mapping based on mode input Parameters: (bool) mode_input: The mode input Returns: (bool) mode: The result mode """ mode = None if mode_input is not None and isinstance(mode_input, bool) and mode_input == True: mode ...
def myDet(p, q, r): """ Calculate determinant of a special matrix with three 2D points. The sign, - or +, determines the side (right or left, respectively) on which the point r lies when measured against a directed vector from p to q. """ # We use Sarrus' Rule to calculate the determinant ...
def split_doubledash(argv, maxsplit=None): """Split on '--', for spearating arguments""" new = [ ] last = 0 nsplit = 0 for i, x in enumerate(argv): if x == '--': new.append(argv[last:i]) last = i + 1 nsplit += 1 if maxsplit is not None and nsplit >...
def search_paginate(page_size=50, page_num=1): """Paginate the results for the frontend.""" page_size = int(page_size) page_num = int(page_num) if page_size <= 0: page_size = 50 if page_num <= 0: page_num = 1 start = (page_num - 1) * page_size end = page_num * page_size r...
def is_almost_equal(x: float, y: float, epsilon: float = 1 * 10 ** (-8)) -> bool: """ Return True if two values are close in numeric value. By default close is withing 1*10^-8 of each other i.e. 0.00000001. Parameters ---------- x, y : float Values to compare. epsilon : float, opti...
def is_dora_indicator_for_terminal(tile): """ :param tile: 34 tile format :return: boolean """ return tile == 7 or tile == 8 or tile == 16 or tile == 17 or tile == 25 or tile == 26
def search_list(list_provided): """Search list provided for characters that are represented only once.""" for i in range(len(list_provided) - 1): if not list_provided[i] in list_provided[i + 1:] and not list_provided[i] in list_provided[:i]: """If the same number is not present before or aft...
def eval(x,y,z): """ Performs evaluations. @ In, x, float, scalar @ In, y, float, scalar @ In, z, float, scalar @ Out, list(float), input values and output value """ dat=[] c = 0 for i in [0.3,0.5,0.7,1.0]: for j in [1.3,1.5,1.7,2.0]: c+=1 dat.append([c,i,j,x,y,z,(i-x)*(j-y...
def node_scoring_function(first: str, second: str): """ node scoring function takes two strings and returns a score in the range 0 <= score <= 1 """ first_, second_ = sorted((first.lower(), second.lower()), key=len) # if first is not a substring of second: score = 0 if not first_ in second_...
def unique(list): """ Returns a copy of the list without duplicates. """ unique = []; [unique.append(x) for x in list if x not in unique] return unique
def are_all_none(*args): """ >>> are_all_none(1, 2, 3) False >>> are_all_none(None, 2, 3) False >>> are_all_none(1, None, 3) False >>> are_all_none(1, 2, None) False >>> are_all_none(1, 2, 3) False >>> are_all_none(1, None, None) False >>> are_all_no...
def ClampValue(input, min, max): """ Clamp Value to min/max :param input: Input :param min: Minimum Value :param max: Maximum Value :return: Clamped Output """ if input > max: return max elif input < min: return min else: return input
def xgcd(a,b) : """Return g,c,d where g=ca+db is the gcd of a and b""" c,d,e,f = 1,0,0,1; while b : q,r= divmod(a,b); a,c,d,b,e,f = b,e,f,r,c-q*e,d-q*f; return (-a,-c,-d) if a < 0 else (a,c,d);
def to_timeout(str_in): """ Tries to coerce provided argument `str_in` to a valid timeout float value. Args: str_in (string): String to coerce to timeout. Returns: (float) or (None): Floating point number - timeout value if provided `str_in` is a valid ti...
def check_format(input_data): """ input_data will be checked to upper case and whether is legal format or not. :param input_data: str, the given DNA sequence. :return: str, the DNA sequence with legal format. """ # all upper input_data = input_data.upper() # extension: check character tr...
def _pipeline_is_running(j): """Return true if the specified K8s job is still running. Args: j: A K8s job object """ conditions = j.get("status", {}).get("conditions", []) if not conditions: return True for c in conditions[::-1]: # It looks like when a pipelinerun fails we have condition succ...
def _get_annotation_user(ann): """Returns the best guess at this annotation's owner user id""" user = ann.get('user') if not user: return None try: return user.get('id', None) except AttributeError: return user
def get_edge(tile): """ Returns the binary sum of the top of the tile """ total, flipped = 0, 0 for i, value in enumerate(tile[0]): total += 2 ** i if value == "#" else 0 for i, value in enumerate(tile[0][::-1]): flipped += 2 ** i if value == "#" else 0 return total, flipped
def assumption_param_text(pname, ptype, param): """ Extract info from param for pname of ptype and return as HTML string. """ # pylint: disable=len-as-condition sec1 = param['section_1'] if len(sec1) > 0: txt = '<p><b>{} &mdash; {}</b>'.format(sec1, param['section_2']) else: ...
def dealiase_sel_kwargs(kwargs, prop_dict, idx): """Generate kwargs dict from kwargs and prop_dict. Gets property at position ``idx`` for each property in prop_dict and adds it to ``kwargs``. Values in prop_dict are dealiased and overwrite values in kwargs with the same key . Parameters ------...
def getProcessName(pdgGen, requiredNumberOfGeneratedObjects): """ returns a process name (such as 'Zee') which can be used in various places (e.g. module names etc.) """ if pdgGen == 11: # electron paths if requiredNumberOfGeneratedObjects == 1: return "Wenu" elif requ...
def showMism(str1, str2): """ return a string with just the mismatching nucleotides, '.' for matching ones also return number of mismatches """ assert(len(str1)==len(str2)) res = [] mismCount = 0 for c1, c2 in zip(str1, str2): if c1==c2: res.append(".") else: ...
def is_project_track(track): """Validates the specified project analytics tracking flag. A flag is nothing but a boolean value. Args: track (bool): A flag to validate. Returns: <bool, str|None>: A pair containing the value True if the specified flag is valid, False otherwi...
def _parsedrev(symbol): """str -> int or None, ex. 'D45' -> 45; '12' -> 12; 'x' -> None""" if symbol.startswith(b'D') and symbol[1:].isdigit(): return int(symbol[1:]) if symbol.isdigit(): return int(symbol)
def write_constant_tier(total_duration, default_value, tc): """ this function returns a string gestures of constant tiers (e.g. F0 and lung-pressure) defaultValue: default value of this constant tier tc: time_constant """ return_str = '' # if it is a long empty gesture, # then split ...
def filter_dicts(d): """ Filter dict to remove None values. :param d: data to filter :type d: dict :returns: filtered data :rtype: dict """ return dict((k, v) for k, v in d.items() if v is not None)
def fuzzy_match(target, item, match_fucn=None): """ This function matches an item to a target list. It is expected that the 'item' comes from user input and we want to accept a 'close-enough' match to the target list and validate that there is a unique close-enough match. If there is no suitable m...
def numerical_sort(string_int_list): """Sorts list of integers that are digits in numerical order.""" as_int_list = [] for vlan in string_int_list: as_int_list.append(int(vlan)) as_int_list.sort() return list(set(as_int_list))
def remapValues(values,targetMin,targetMax,srcMin,srcMax): """ Remaps a list of values to the new domain targetMin-targetMax """ #srcMin = min(values) #srcMax = max(values) if srcMax-srcMin > 0: remappedValues = [] for v in values: rv = ((v-srcMin)/(s...
def get_dims(dims): """ Get default dimension names. Examples -------- >>> get_dims(dims=None) ('northing', 'easting') >>> get_dims(dims=('john', 'paul')) ('john', 'paul') """ if dims is not None: return dims return ("northing", "easting")
def egcd(a, b): """Extended euclidian algorithm""" s0, s1 = 1, 0 t0, t1 = 0, 1 while b != 0: quotient = a // b a, b = b, a % b s0, s1 = s1, s0 - s1 * quotient t0, t1 = t1, t0 - t1 * quotient return a, s0, t0
def make_connection_string(**vargs): """Join a dictionary of connection properties (`vargs`) into a connection string. Examples -------- >>> make_connection_string(**{ \ 'db_password': None, \ 'db_port': '', \ 'db_schema': '', \ 'db_socket': '', \ 'db_type': 'mys...
def getMediaName(prefix, slideNumber, frmt='png'): """Returns the relative name of the media file.""" return prefix + '-' + str(slideNumber) + '.' + frmt
def catalog_deletion_payload(catalog_list): """ Returns payload to delete catalog """ return { "CatalogIds": catalog_list }
def get_file_ending(filename): """Returns the file ending of the filename given as input""" return filename.rsplit('.', 1)[1]
def mg1_mean_qsize(arr_rate, svc_rate, cv2_svc_time): """ Return the mean queue size in M/G/1/inf queue using P-K formula. See any decent queueing book. Parameters ---------- arr_rate : float average arrival rate to queueing system svc_rate : float average service rate (eac...
def compact(array): """Creates a list with all falsey values of array removed. Args: array (list): List to compact. Returns: list: Compacted list. Example: >>> compact(['', 1, 0, True, False, None]) [1, True] .. versionadded:: 1.0.0 """ return [item for i...
def recall_at_n(ranks, n=3): """ Calculate recall @ N Function taken from: https://github.com/google/retrieval-qa-eval/blob/master/squad_eval.py :type ranks: list :param ranks: predicted ranks of the correct responses :return: float value containing the Recall@N """ num = len([rank for...
def decode_time(value): """time decoder Used for fields such as: duration=1234.123s """ if value == "never": return value time_str = value.rstrip("s") return float(time_str)
def get_trans_freq_color(trans_count, min_trans_count, max_trans_count): """ Gets transition frequency color Parameters ---------- trans_count Current transition count min_trans_count Minimum transition count max_trans_count Maximum transition count Returns ...
def create_board(board_size): """ creates a square board based on the given board size """ board = [] for i in range(board_size): row = [] for j in range(board_size): row.append('-') board.append(row) return board
def get_mts(virt_eths): """ Parse the machine type/model/serial from the IVM output. :param virt_eths: A dictionary with adapter data from IVM :returns: A string in the form "type.model.serial" """ for key in virt_eths.keys(): if 'Virtual I/O Ethernet Adapter (l-lan)' in virt_eths[key][...
def validate_framerate_gop_segment_duration(json_data): """Validate that we can get exactly the segment duration that is asked for. For 29.97 and 59.94, we only support gop_durations which are multiples of 30 (60) frames, which result in segment_durations being a multiple of 1001 ms.""" def is_clo...
def startswith(prefix: str, s: str) -> bool: """Describe the prefix of string `s`. Parameters ---------- prefix : str prefix to query. s : str string to check whether its prefixed by `s`. Returns ------- bool whether `s` is prefixed by `prefix`. ...
def transfer_2d_array_to_str(array): """Transfer a 2D float32 array to a string.""" str_list = [] for r in array: str_list.append(",".join([str(e) for e in r])) return " ".join(str_list)
def _get_port_definitions(app): """ Get the ``portDefinitions`` field for the app if present. """ if 'portDefinitions' in app: return app['portDefinitions'] # In the worst case try use the old `ports` array # Only useful on very old Marathons if 'ports' in app: return app['p...
def partition(number): """ Compute the of the partitions of the input number. """ answer = set() answer.add((number, )) for x in range(1, number): for y in partition(number - x): answer.add(tuple(sorted((x, ) + y))) return answer
def decontaminate(F,contam_frac): """ decontaminate flux F following prescription by kipping & Tinetti https://doi.org/10.1111/j.1365-2966.2010.17094.x Fcorr = F*(1+Fcont/F_st)- Fcont/F_st Parameters: ----------- F: array-like; contaminated flux that needs correction cont...
def biehl_jetted_evolution(z, m=-3.): """Evolution of TDEs assumed by Biehl et al. 2018 is 0.1 per Gpc per year (10^-10 per Mpc per year). The source evolution is assumed to be negative, with an index m=3, though the paper also considers indexes up to m=0 (flat). More details found under https://arxiv.o...
def getKeyIdx(key, key2Idx): """Returns from the word2Idx table the word index for a given token""" if key in key2Idx: return key2Idx[key] return key2Idx["UNKNOWN_TOKEN"]
def _linear_transform(src, dst): """ Parameters of a linear transform from range specifications """ (s0, s1), (d0,d1) = src, dst w = (d1 - d0) / (s1 - s0) b = d0 - w*s0 return w, b
def get_frame_from_json(frame): """Get/sanitize raw frame from JSON of frame from `tshark -x -T json ...` Args: frame (dict): A dict of a single packet from tshark. Returns: (str): The ASCII hexdump value of a packet """ if not isinstance(frame, dict): print('frame is type',...
def no_red(obj): """Evaluate json objects adding numbers not in dicts containing "red".""" if type(obj) == int: return obj if type(obj) == list: return sum([no_red(item) for item in obj]) if type(obj) == dict: if 'red' in obj.values(): return 0 return no_red(l...
def partition_horizontal(value, n): """ Break a list into ``n`` peices, but "horizontally." That is, ``partition_horizontal(range(10), 3)`` gives:: [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]] Clear as mud? """ try: n = int(n) value = list(value) ...
def build_run_cmd(raw_cmd, start_date=None, end_date=None, database=None): """Replace placeholder inputs in the model command with given values. Parameters ---------- raw_cmd : str Raw command, whichs hould contain placeholders <start_date>, <end_date> and <database>. start_date : s...
def format_sec_to_hms(sec): """Format seconds to hours, minutes, seconds. Args: sec: float or int Number of seconds in a period of time Returns: str Period of time represented as a string on the form ``0d\:00h\:00m``. """ rem_int, s_int = divmod(int(sec), 60) h_int, m_int,...
def transform_tags(tags:str): """convert the tags field to a list split on spaces""" return tags.split(" ")
def get_swap_wout(t1, t2, w1, w2, decay_factor): """ Get w_swap """ return w1 * w2 * decay_factor
def parse_u12_opt(gene, u12_data): """Parse U12 introns data.""" if u12_data is None: return set() if gene == "None": return set() ans = set() f = open(u12_data, "r") for line in f: line_data = line.rstrip().split("\t") trans = line_data[0] if trans != ge...
def is_float(s): """ test if string parameter is valid float value :param s: string to test :return: boolean """ try: float(s) return True except ValueError: return False
def high(x): """ Given a string of words, return the position of the word with the highest score (a worth 1, b worth 2 c worth 3, etc...) x: string of (lowercase) words separated by spaces """ #calcaulate the score for a word def word_score(word): '''Calcualates the score of a word ...
def to_upper_snakecase(text: str) -> str: """ Convert text to UPPER_SNAKE_CASE """ data = text.replace(" ", "_").upper() if data[0].isdigit(): data = "_" + data return data
def get_user_agent_from_header_meta(request_meta): """ Getting user agent from request meta """ return request_meta.get('HTTP_USER_AGENT', '')
def is_valid(*arg, **kwargs): """ :param arg: input :param kwargs: blacklist :return: True if none of the arg is in the blacklist(kwargs) """ ban_list = ['undefined', 'unspecified', None, ''] if 'ban' in kwargs.keys() and kwargs['ban'] is not None: if type(kwargs['ban']) == list: ...
def _format_block_id(chunk_num): # type: (int) -> str """Create a block id given a block (chunk) number :param int chunk_num: chunk number :rtype: str :return: block id """ return '{0:08d}'.format(chunk_num)
def opt_to_kwargs(opt): """ Get kwargs for seq2seq from opt. """ kwargs = {} for k in [ 'numlayers', 'dropout', 'bidirectional', 'rnn_class', 'lookuptable', 'decoder', 'numsoftmax', 'attention', 'attention_length', 'atte...
def diff_dict(dict1, dict2): """ Returns a dictionary with all the elements of dict1 that are not in dict 2. >>> diff_dict({1:2, 3:4}, {1:3, 3:4, 2:4}) {1: 2} """ return_dict = {} for key in dict1: if key in dict2: if not dict1[key] == dict2[key]: ret...
def convert_json_to_definition_catalogue_entry(p, domainAcronym): """ data class NewDefinition( var name: String = "", var domain: String = "", var status: String = "", var definition: String = "", var guidance: String = "", var identifier: String = "", ...
def specced(name, version): """ Args: name (str): Pypi package name version (str | None): Version Returns: (str): Specced name==version """ name = name.strip() if version and version.strip(): return "%s==%s" % (name, version.strip()) return name
def is_iterable(obj): """Tells whether an instance is iterable or not""" try: iter(obj) return True except TypeError: return False
def date_attribute(attribute, operator, precision=None, value=None): """ Select an audience to send to based on an attribute object with a DATE schema type, including predefined and device attributes. Please refer to https://docs.airship.com/api/ua/?http#schemas-dateattribute for more information ab...
def convert(inner: list) -> dict: """Return inner bags as dictionary.""" out = {} if inner == ["no other"]: return out else: for bag in inner: out[bag[2:]] = int(bag[:2]) return out
def get_resource_type_name(resource_values): """Gets resource type name from resource values.""" resource_type = resource_values['Type'] return resource_type.split('::')[-1]
def condor_format_sequence(sequence): """Format a Sequence According to Condor Conventions.""" return " ".join(map(str, sequence))
def get_input_sequence(input_data): """ Take range/comma input, return list of ints :param input_data: String in format "1,3,10-20,5" :return: List of unique Integers """ unique_data = set() for chunk in input_data.split(','): parts = [int(n) for n in chunk.split('-')] if len...
def sanitize_timestamp(ts): """Insert period into 3rd-from-last place of funky Ravello timestamp.""" ts = str(ts) return float(ts[:-3] + '.' + ts[-3:])
def hersh_bbox(lines): """ passed an array of lines, returns the smallest bounding box """ # nice ways of bombing out if lines is None: return None if len(lines[0]) < 1: return None min_x = max_x = lines[0][0][0] min_y = max_y = lines[0][0][1] for line in lines: for ...
def sign(x: float): """Retuns 1 if x > 0 else -1. > instead of >= so that sign(False) returns -1""" return 1 if x > 0 else -1
def x10(S: str, n: int): """change float to int by *10**n Args: S (str): float n (int, optional): n of float(S)*10**n (number of shift). Returns: int: S*10**n """ if "." not in S: return int(S) * 10**n return int("".join([S.replace(".", ""), "0" * (n - S[::-1].f...
def make_new_get_user_response(row): """ Returns an object containing only what needs to be sent back to the user. """ return { 'userName': row['userName'], 'categories': row['categories'], 'imageName': row['imageName'], 'refToImage': row['refToImage'], ...
def reverse_dict(d): """ reverses key-value mapping """ r = dict() for k,v in d.items(): r[v] = k return r
def canonicalize_address(addr): """ Encases addresses in [ ] per RFC 2732. Generally used to deal with ':' characters which are also often used as delimiters. Returns the addr string if it doesn't contain any ':' characters. If addr contains ':' and also contains a '[' then the addr string is ...
def transpose(table): """ Returns a copy of table with rows and columns swapped Example: 1 2 1 3 5 3 4 => 2 4 6 5 6 Parameter table: the table to transpose Precondition: table is a rectangular 2d List of numbers """ result = []...
def get_float(value): """ Convert a string to a float number :param value: (str) :return: (float) Example: >>> get_float('3.0') 3.0 """ try: ret = float(value) except ValueError: raise ValueError("Could not convert '%s' into a float number" % value) return ...
def escape(html): """Returns the given HTML with ampersands, quotes and carets encoded.""" return html \ .replace('&', '&amp;') \ .replace('<', '&lt;') \ .replace('>', '&gt;') \ .replace('"', '&quot;') \ .replace("'", '&#39;')
def calc_q_c1n(q_c, c_n): """ qc1n from CPT, Eq 2.4 """ q_c1n = c_n * q_c * 1000 / 100 return q_c1n
def get_uri(raw): """ Extract URI of edition. @param raw: json object of a Libris edition @type raw: dictionary """ return raw["@id"].split("/")[-1]
def get_nested_value(nested, branch): """Helper function that gets a specific value in a nested dictionary or class.""" list_branch = branch.split(".") leaf = list_branch.pop(0) # return value of leaf if not nested: return globals().get(leaf, None) # get value of leaf if isinstance(n...
def calculate_intensity(color, intensity=1.0): """ Takes a RGB[W] color tuple and adjusts the intensity. :param float intensity: :param color: color value (tuple, list or int) :return: color """ # Note: This code intentionally avoids list comprehensions and intermediate variables # for a...
def letters_to_py( _letters ): """ return list of letters e.g. uyir_letters as a Python list """ return u"[u'"+u"',u'".join( _letters )+u"']"
def format_install_url(app_id: str, location_id: str) -> str: """Return a web-based URL to auth and install a SmartApp.""" return f"https://account.smartthings.com/login?redirect=https%3A%2F%2Fstrongman-regional.api.smartthings.com%2F%3FappId%3D{app_id}%26locationId%3D{location_id}%26appType%3DENDPOINTAPP%26lan...
def make_lines_raw(value): """No-op. >>> make_lines_raw(None) [] >>> make_lines_raw(['spam', 'eggs']) ['spam', 'eggs'] """ if value is None: return [] return value