content
stringlengths
42
6.51k
def conf_level(val): """ Translates probability value into a plain english statement """ # https://www.dni.gov/files/documents/ICD/ICD%20203%20Analytic%20Standards.pdf conf = "undefined" if val < 0.05: conf = "Extremely Low Probability" elif val >= 0.05 and val < 0.20: conf ...
def _var_names(var_names): """Handle var_names input across arviz. Parameters ---------- var_names: str, list, or None Returns ------- var_name: list or None """ if var_names is None: return None elif isinstance(var_names, str): return [var_names] else: ...
def get_file_ext(maintype): """Extract correct file extension from content type.""" return maintype.split("/")[1]
def is_leaving(text): """ Checks if user is leaving. Parameters: text (string): user's speech Returns: (bool) """ state = False keyword = [ "exit", "quit", "bye", "see you", "see ya" ] for word in keyword: if ((text.lower()).find(...
def bracket_check(string:str)->bool: """function takes in a string and returns boolean True if brackets are balanced, False if not""" #create empty dictionary with 3 types of opening brackets brackets = { "ro" : 0, "so" : 0, "co" : 0 } #check for '' with if and len(...
def validate_boolean(b): """Convert b to a boolean or raise a ValueError.""" try: b = b.lower() except AttributeError: pass if b in ('t', 'y', 'yes', 'on', 'true', '1', 1, True): return True elif b in ('f', 'n', 'no', 'off', 'false', '0', 0, False): return False else: rai...
def storage_change(x, s, prevstate, dt, fun=lambda x: x, S=1.0): """ Storage change function General storage change function for both saturated and unsaturated flow simulations Parameters ---------- x : `float` Positional argument :math:`\\left(length\\right)`. s : `float` ...
def mult_mat_mat(*args): """Multiply two matrices for any indexable types.""" if len(args) == 2: a, b = args return [[sum(ae*be for ae, be in zip(a_row, b_col)) for b_col in zip(*b)] for a_row in a] else: return mult_mat_mat(args[0], mult_mat_mat(*args[1:]))
def unique_elements(input_list): """ Functions to find unique elements from a list of given numbers. :param input_list: list or tuple >>> unique_elements([1, 0, 1, 0, 1, 2]) [0, 1, 2] """ return list(set(input_list))
def divide(value1: int, value2: int) -> float: """ Used to divide the number of cards to check that nothing was lost. Handles division by 0 by returning 0, which is the reciprocal. """ if value1 == value2: # good for 0/0 return 1.0 else: try: div_value = value1 / fl...
def get_dimentions_factors(strides_schedule): """ Method calculates how much height and width will be increased/decreased basen on given stride schedule Args: strides_schedule: A list of stride tuples(heigh, width) Returns: Two numbers that tells how many times height and width will be in...
def parse_accept(accept): """Parses the Accept header sent with a request. Args: accept (str): the value of an Accept header. Returns: (list): A list containing the MIME types that the client is able to understand. """ return accept.replace(" ", "").split(",")
def is_type_of(value, other): """Type check""" return isinstance(value, other)
def tif_filter(time: float, value: float, *function_name) -> str: """ Creates time-initial fluent if time>0, or plain initialization otherwise """ assignment = "(= ({}) {})".format(' '.join(function_name), value) return "(at {} {})".format(time, assignment) if time > 0\ else assignment
def dec2hms(dec): """ ADW: This should really be replaced by astropy """ DEGREE = 360. HOUR = 24. MINUTE = 60. SECOND = 3600. dec = float(dec) fhour = dec*(HOUR/DEGREE) hour = int(fhour) fminute = (fhour - hour)*MINUTE minute = int(fminute) second = (fminut...
def pdir(obj): """ Puts dir of an object on stdout """ print(dir(obj)) return obj
def qualified_name(cls): """ Go from class instance to name usable for imports. """ return cls.__module__ + "." + cls.__name__
def _m_mangled_attr_name (name, cls_name) : """Returns `name` as mangled by Python for occurences of `__%s` % name inside the definition of a class with name `cls_name`. >>> print (_m_mangled_attr_name ("foo", "Bar")) _Bar__foo >>> print (_m_mangled_attr_name ("foo", "_Bar")) _Ba...
def is_list(val): """Check if value is list""" return isinstance(val, list)
def truncate_integer(value: int, length: int = 10) -> int: """ Truncate an integer value to the desired length. :param value: integer to truncate :param length: desired length of integer :return: truncated integer """ val_length = len(str(value)) if val_length > length: diff = v...
def kb_to_string(sess, clauses): """Return the string representation of the knowledge base :param sess: the tensorflow session :param clauses: list of clauses :return: a string representing the knowledge base together with the [learned] clause weights """ s = [] for clause in clauses: ...
def _SplitCoordinates(coord): """Returns lon,lat from 'coord', a KML coordinate string field.""" lon, lat, _ = coord.strip().split(',') return float(lon), float(lat)
def valid_index(index, left, right): """ Checks if INDEX is a valid number and is within the index range. If valid, returns TRUE. Otherwise, returns FALSE. """ try: num = int(index) return (num >= left and num <= right) except (ValueError, TypeError): return False
def factorial(input_number: int) -> int: """ Non-recursive algorithm of finding factorial of the input number. >>> factorial(1) 1 >>> factorial(6) 720 >>> factorial(0) 1 """ if input_number < 0: raise ValueError('Input input_number sho...
def ft2tom2(ft2): """ Convertie les square feets en square meters note: 12 [in] = 1 [ft] and 1 [in] = 25.4 [mm] and 1000 [mm] = 1 [m] :param ft2: area [ft2] :return m2: area [m2] """ m2 = ft2 * (12 * 25.4 / 1000) ** 2 return m2
def _get_column_len(column_width, entry_len, entry_width): """ From the desired column width in cells and the item to be printed, calculate the required number of characters to pass to the format method. In order to get the correct width in chars it is necessary to subtract the number of cells abov...
def inclusion_one_param(arg): """Expected inclusion_one_param __doc__""" return {"result": "inclusion_one_param - Expected result: %s" % arg}
def _dsuper_list_td(t, y, L_list): """ Auxiliary function for the integration. Is called at every time step. """ L = L_list[0][0] for n in range(1, len(L_list)): L = L + L_list[n][0] * L_list[n][1](t) return L * y
def create_cmd(parts): """Join together a command line represented as list""" sane_parts = [] for part in parts: if not isinstance(part, str): # note: python subprocess module raises a TypeError instead # of converting everything to string part = str(part) ...
def fully_linear(A): """ Find single number using bit-wise operations in linear time completely. """ if not A: return None if len(A) == 1: return A[0] x = A[0] for i in range(1, len(A)): x ^= A[i] return x
def unzpad(strint): """ Removes zpadding from an integer string :param strint: a string that contains an integer value :return: """ return '{}'.format(int(strint))
def _parse_source(source): """ Parses the names-generator.go source to find adjectives and names. Parameters ---------- source : str The source file to be parsed. Returns ------- tuple(2) Two lists with [0] being adjectives and [1] being names. """ collecting = ...
def is_operand(token): """Checks if token is an operand A-Z or 0-9, etc.""" return token.isalpha() or token.isdigit()
def is_prime(num): """Check to see whether num can be factored at all.""" for i in range(2, num // 2): if num % i == 0: return False return True
def _hex_ip_to_dec_ip(hex_ip): """Converts a hexadecimal IPv4 address to quad-dotted form. Args: hex_ip: str, zero padded, network order, hexadecimal format IPv4 address. e.g. "01020A04". Returns: str, quad-dotted format IPv4 address, e.g. "4.10.2.1" """ fields = [hex_ip[i:i ...
def net_parent_table(parent_panel): """Reduces a full parent panel to get parent indices on a cycle basis. The full parent panel has parent indices for every step in each cycle. This computes the net parent relationships for each cycle, thus reducing the list of tables (panel) to a single table. A ...
def is_inline(*points): """ Checks whether all given points are on a single line. The points order is not important. Args: *points: ((float, float),) Collection of points to check as (x,y) coordinates. Returns: bool Returns True if all points are on ...
def is_typed_tuple(tpl: object, obj_type: type, allow_none: bool = False, allow_empty: bool = True) -> bool: """ Check if a variable is a tuple that contains objects of specific type. :param tpl: The variable/list to check :param obj_type: The type of objects that the tuple should contain (for the chec...
def total_score(pics, gene_score): """ Computes a weird mean function from ld_snp PICs score and Gene/SNP association score Args: * PICS: scalar * gene_score: scalar Returntype: scalar """ if pics is None: return None A = pics * (pics ** (1/3)) B = gene_score * (gene_score ** (1/3)) return ((A ...
def toggle_player(player): """ toggle_player(1) = 2 toggle_player(2) = 1 toggle_player(other) = who_cares """ return player % 2 + 1
def retrieve_setup(arntask, creds, device_value, res_completed, results_dict): """Retrieve value test setup.""" return arntask, creds, device_value, res_completed, results_dict
def sprint_card(vc_h): """Return a vcard hash in a better format as a string.""" def get_parts(vc_h, f): filtered_parts = [i for i in filter(f, vc_h)] if len(filtered_parts) == 0: ret = "" elif len(filtered_parts) == 1: ret = "%s: %s" % (filtered_parts[0], vc_h[fi...
def geopoint_average(points): """Takes a list of lat-lng tuples and returns an average""" count = len(points) if not count: return None lat = 0 lng = 0 for point in points: lat += point[0] lng += point[1] return (lat/count, lng/count)
def hex_to_rgb(value): """ Useful convert method from http://stackoverflow.com/a/214657 """ value = value.lstrip('#') lv = len(value) return tuple(int(value[i:i + lv // 3], 16) for i in range(0, lv, lv // 3))
def string_2_list(string): """ Convert a list of numbers separated by comma to a list of floats """ return [float(val) for val in string.split(",") if len(val) > 0]
def get_npa(fp, tn): """ This functions returns the negative percent agreement. :param fp: Number of false positives :type fp: int :param tn: Number of true negatives :type tn: int :return: The negative percent agreement, NPA = (tn) / (fp+tn) :rtype: float """ if fp + tn == 0: ...
def unique_dicts(d): """Removes duplicate dictionaries from a list. Args: d (:obj:`list` of :obj:`dict`): List of dictionaries with the same keys. Returns (:obj:`list` of :obj:`dict`) """ return [dict(y) for y in set(tuple(x.items()) for x in d)]
def assumed_role_to_principle(assumed_role_arn): """Return role ARN from assumed role ARN.""" arn_split = assumed_role_arn.split(":") arn_split[2] = "iam" base_arn = ":".join(arn_split[:5]) + ":role/" return base_arn + assumed_role_arn.split("/")[1]
def normalize(data): """Normalizes the input to a upper-case string :param data: the data to normalize """ return data.strip().upper()
def __len_gen__(gen) -> int: """ Get the "length" of a generator. """ # __len_gen__(gen) is faster and consumes less memory than len([for x in gen]) n = 0 for x in gen: n += 1 return n
def f_short_name(text): """function short event name - requested detailed in item 2.""" # split the text words = text.lower() words = words.split() short_name = '_' # for each word in the line: for word in words: short_name = short_name + word[0:3] ## remove special c...
def viou_sx(traj_1, duration_1, traj_2, duration_2, frame_thresh=0.5): """ compute the voluminal Intersection over Union for two trajectories, each of which is represented by a duration [fstart, fend) and a list of bounding boxes (i.e. traj) within the duration. """ if duration_1[0] >= duration_...
def counter(lfsr): """Iterates the counter for the permutation round""" lfsr = (lfsr << 1) | (((0x40 & lfsr) >> 6) ^ ((0x20 & lfsr) >> 5)) lfsr &= 0x7f return lfsr
def isTriangle(a, b, c): """ Checks if the given triangle sides can form a triangle. """ if c > (a+b): return False elif b > (a+c): return False elif a > (b+c): return False return True
def compare_overlaps(context, synsets_signatures, \ nbest=False, keepscore=False, normalizescore=False): """ Calculates overlaps between the context sentence and the synset_signture and returns a ranked list of synsets from highest overlap to lowest. """ overlaplen_synsets = []...
def parse_query_result(columns, rows): """ Parse the query results into a list of dict Arguments: - `columns` (`list[dict]`): Returned by the SIEM. Exemple:: [{'name': 'Alert.LastTime'}, {'name': 'Rule.msg'}, {'name': 'Alert.DstIP'}, {'name': 'Alert.IPSIDAlertID'}] ...
def approx_first_derivative(f,x,h): """ Numerical differentiation by finite differences. Uses central point formula to approximate first derivative of function. Args: f (function): function definition. x (float): point where first derivative will be approximated h (float): step s...
def _get_col_key(translation_type, language): """ Returns the name of the column in the bulk app translation spreadsheet given the translation type and language :param translation_type: What is being translated, i.e. 'default' or 'image' :param language: :return: """ return "%s_%s" %...
def get_GOI_record(record, *args): """ defines a list of records corresponding to the GOI """ chrom = 'chr' + str(args[0]) start = int(args[1]) end = int(args[2]) if record['CHROM'] == chrom: if end >= record['POS'] >= start: return 1 else: return 0 else: return 0
def _get_normalized_vm_disk_encryption_status(vm, vm_iv): """Iterate over a list of virtual machine disks normalize them. Arguments: vm (dict): Raw virtual machine record. vm_iv (dict): Raw virtual machine instance view record. Returns: dict: Normalized virtual machine disk encrypt...
def fafn2fqfn(fafn): """return a FASTQ file name which corresponds to a FASTA file.""" if fafn.find('.') != -1: return fafn[:fafn.rfind('.')] + ".fastq" else: return fafn + ".fastq"
def numberOfArithmeticSlices(A): """ :type A: List[int] :rtype: int """ n = len(A) if n < 3: return 0 sum = 0 silcecLen = 2 diff = A[1] - A[0] for i in range(2, n): newDiff = A[i] - A[i - 1] if diff == newDiff: silcecLen += 1 ...
def collapse_walker_chain( walker_chain, nburn=0 ): """ Takes emcee walker chains and collapses them into single chains, one for each parameter. An optional burn-in range from can be discarded from the beginning of each walker chain prior to combining them together. """ if nburn==None: ...
def triple_x(x): """Callback to fill the finance example value.""" return float(x) * 3
def rename_dupe_cols(cols): """ Takes a list of strings and appends 2,3,4 etc to duplicates. Never appends a 0 or 1. Appended #s are not always in order...but if you wrap this in a dataframe.to_sql function you're guaranteed to not have dupe column name errors importing data to SQL...you'll just hav...
def subidx_2_idx(subidx, subncol, cellsize, ncol): """Returns the lowres index <idx> of highres cell index <subidx>.""" r = (subidx // subncol) // cellsize c = (subidx % subncol) // cellsize return r * ncol + c
def remove_stratified_pathways(pathways, data, remove_description=None): """ Remove the stratified pathways from the data set. Also remove the unintegrated and unmapped values. Remove the descriptions from the pathway names if set. Args: pathways (list): A list of pathway na...
def _translate_snapshot_summary_view(context, vol): """Maps keys for snapshots summary view.""" d = {} d['id'] = vol['id'] d['volumeId'] = vol['volume_id'] d['status'] = vol['status'] # NOTE(gagupta): We map volume_size as the snapshot size d['size'] = vol['volume_size'] d['createdAt'] ...
def remove_newline(word): """Removes newline from word""" return word.replace('\n', '')
def convert_index_to_hour(index, time_span, remainder): """Convert index to hour.""" # This needs -1 because the end hour is inclusive. For example, if the period # represents [2, 26), the end hour is 25. # # Index is added 1 because, in our SQL, we subtract the remainder, divide, # and floor. So, in order ...
def extractInstrValues(expresions, fomatStr): """ Extracts values of register addresses and immedaete expresions - array of srings as parts of instruction (letter code followed by parametrs) fomatStr - format string of the instruction return: reg - array of register addr in oreder Rd, Rs1, Rs2 ...
def arr_to_dict(arr): """ takes in an numpy array or list of lists (tuple of tuples) and returns a dictionary with indices, values Example arr_to_dict([['a','b'],['c','#']]) == {(0, 0): 'a', (0, 1): 'b', (1, 0): 'c', (1, 1): '#'} """ d = {} if isinstance(arr, str): pr...
def get_target_diff_coverage(current_coverage, line_stats): """ Gives some wiggle room for small MRs. If there are fewer than 5 uncovered lines, lower the required coverage to 75%-- this allows things like 2 uncovered lines in a 12-line MR. Otherwise, the diff coverage must be >= the current coverage in...
def cpf_is_digits(value): """ This function receives the Brazilian CPF and returns True if it contains only digits or False if not. :param value: A string with the number of Brazilian CPF :return: True or False """ if value.isdigit(): return True else: return False
def check_if_excluded(path): """ Check if path is one we know we dont care about. """ exclusions= [ "src/CMake", "src/_CPack_Packages", "src/bin", "src/archives", "src/config-site", "src/cqscore", ...
def color(string, color=None): """ Change text color for the Linux terminal. Note: this is duplicate code copied from helpers.py because it cannot be imported into this file due to a circular reference. There are plans to refactor these circular references out, but this is the near term solution. ""...
def find_base_articles(articles): """ Return the base articles from a list of articles :param articles: list of articles :type articles: [str] :return: bases :rtype: [str] """ base_articles = [] for a in articles: a = a.split('+')[0] if 'p' not in...
def has_any(data, keys): """ Checks any one of the keys present in the data given """ if data is None and not isinstance(data, dict): return False if keys is None and not isinstance(keys, list): return False for key in keys: if key in data: return True ...
def smooth_compressed(compressed_depths, window, to_round): """Takes a compressed depth file and averages each position to window(int) left and right of the point to created a smoothed compressed depth file Args: compressed_depths (dict): a position_start, position_end : read_depth formated dictionary ...
def quiz_blank_in_pos(word, quiz_blank): """Checks if a word in quiz_blank is a substring of the word passed in. Args: word: A string representing the word to be checked. quiz_blank: A string representing the missing word placeholders. Returns: The quiz_blank if found and None if n...
def get_field_locs(working_data, fields): """ Finds fields index locations. Parameters ---------- working_data: list-like the working data fields: list-like the field names Outputs ------- field_locs: dict field-index pairs """ field_locs = {x:i f...
def process_child_attrib(d, node): """ Processes the attributes dictionary of a 'node' or 'way' tag. Will split address items into an 'address' sub-dictionary Remaining items will keep their key, value pair :param d: Input dictionary of form {'k': key, 'v': value} :param node: The output dicti...
def h(params, sample): """This evaluates a generic linear function h(x) with current parameters. h stands for hypothesis Args: params (lst) a list containing the corresponding parameter for each element x of the sample sample (lst) a list containing the values of a sample Returns: Evaluation of h(x) """ ac...
def filterSpilloverFilename(filename): """ Remove any unwanted spill-over filename endings (i.e. _NNN or ._NNN) """ # Create the search pattern from re import compile, findall pattern = compile(r'(\.?\_\d+)') found = findall(pattern, filename) if found: # Make sure that the _NNN substri...
def convert_to_list(argument): """Convert a comma separated list into a list of python values""" if argument is None: return [] else: return [i.strip() for i in argument.split(",")]
def is_pandigital(num): """Return true if integer num uses all of the digits from 1 to n exactly once. False otherwise.""" str_num = str(num) if str_num.count('0') > 0: return False n_digits = len(str_num) for i in range(1, n_digits+1): if str_num.count(str(i)) != 1: retu...
def span(text): """ Wraps text around formatting tag (That's how the web editor handles font sizes for some reason) """ return '''<span style="font-size: 16px;">'''+text+"</span>"
def f(x : int) -> int: """blabla""" # x : int x = 42 return 42
def transform_config(cfg, split_1='search:', split_2='known_papers:'): """Ugly function to make cfg.yml less ugly.""" before_search, after_search = cfg.split(split_1, 1) search_default, papers_default = after_search.split(split_2, 1) search, paper_comment = '', '' for line in search_default.splitli...
def AV_to_EBpmRp(A_V): """ Convert A_V to E(Bp-Rp). NOTE: assumes A_V has been "corrected" for distance, galactic latitude, etc. So if you pull A_V from a total extinction in a LOS map (e.g., SF98) that doesn't do this correction, you'll get wrong answers. """ # E(B-V) = A_V/R_V R_V = 3....
def _find_if_has_key(obj, key, of_type=None): """ Recursively find all objects with a given key in a dictionary Args: obj: Dictionary to search key: Key to find of_type: [optional] Type of the referenced item Returns: List of all objects that contain an item with the giv...
def generate_chunk_data_list(size, data_size): """ generate a lit of data chunk enpoints """ L = [] idx = 0 while idx < size: L.append((idx, min(idx + data_size - 1, size - 1))) idx += data_size return L
def generate_spaces(text_width, max_width): """ >>> generate_spaces(4, 6) ' ' """ return ' ' * (max_width - text_width)
def as_int(obj, quiet=False): """Converts an arbitrary value into a integer.""" # Try "2" -> 2 try: return int(obj) except (ValueError, TypeError): pass # Try "2.5" -> 2 try: return int(float(obj)) except (ValueError, TypeError): pass # Eck, not sure what ...
def get_template_string(sql): """generate template string""" if sql: template_string = """from flask_easy import db, fields class {{model_name}}(db.Model): pass """ else: template_string = """import mongoengine as me class {{model_name}}(me.Document): id = me.IntField(primary_ke...
def _get_poly_method(lx: float, alpha: float, d: int): # pragma: no cover """Determines the method to apply for for each log x argument to gumbel_poly""" if d <= 30: return 'direct' elif d <= 50: return 'direct' if alpha <= 0.8 else 'log' elif d <= 70: return 'direct' if alpha ...
def heuristic(a, b): """ Calculates the Manhattan distance between two pairs of grid coordinates. """ x1, y1 = a x2, y2 = b return abs(x1 - x2) + abs(y1 - y2)
def _insert_newlines(text: str, n=40): """ Inserts a newline into the given text every n characters. :param text: the text to break :param n: :return: """ if not text: return "" lines = [] for i in range(0, len(text), n): lines.append(text[i:i + n]) return '\n'.j...
def binary_search(a, k): """ Do a binary search in an array of objects ordered by '.key' returns the largest index for which: a[i].key <= k like c++: a.upperbound(k)-- """ first, last = 0, len(a) while first < last: mid = (first + last) >> 1 if k < a[mid].key: ...
def is_list_match(item, value): """Check if a item match a value or (if it is a list) if it contains only one item and the item matches the value """ if isinstance(item, list): if len(item) == 1 and item[0] == value: return True else: return False else: ...