content
stringlengths
42
6.51k
def vector_add(v, w): """soma elementos correspondentes""" return [(v_i + w_i) for v_i, w_i in zip(v, w)]
def any_ga(geoawi): """ GEOAWI: GA W/I GRID 0=None 1=Quest 2=<I2 3=<O2 4=<1/2 DA 5=<1DA 6=<2DA 7=>2DA 8=CG Returns: 0, 1, 88 """ if geoawi == 0: return 0 elif 1 <= geoawi <= 7: return 1 elif geo...
def concatenate(items): """ Concatenate a list of items in a human friendly way. :param items: A sequence of strings. :returns: A single string. """ items = list(items) if len(items) > 1: return ', '.join(items[:-1]) + ' and ' + items[-1] elif items: return items[0] ...
def parse_group_names(group_results, name_attr): """ Parses results from LDAP group search into a list of group names. """ groups = [] for distinguished_name, entry in group_results: if distinguished_name is not None and name_attr in entry: group_name = entry[name_attr] ...
def getLanguageType(file_extention): """ Function to assign language type based on file extention. Input: file_extention: String that lists file type. Output: languageType: string listsing identified language type. """ if file_extention == 'py': return 'python' else: return ...
def fresnel_criterion(W, z, wav): """ determine the frensel number of a wavefield propagated over some distance z :param W: approx. beam/aperture size [m] :param z: propagation distance [m] :param wav: source wavelength [m] :returns F: Fresnel number """ F = W**2/(z*wav) return F
def isascii(c): """Check if character c is a printable character, TAB, LF, or CR""" try: c = ord(c) # convert string character to decimal representation except TypeError: # it's already an int? (Py3) pass return 32 <= c <= 127 or c in [9, 10, 13]
def find_prefix_entry(message, dictionary): """ Find the longest entry in dictionary which is a prefix of the given message """ for entry in dictionary[::-1]: if message.startswith(entry[0]): return dictionary.index(entry) return -1
def read_ip(file): """Reads the last ip from a file.""" try: f = open(file, "r") old_ip =f.read() f.close() except FileNotFoundError: return None return old_ip
def sum_of_squares(n): """ returns the sum of squares of first n numbers """ iter = 1 sum = 0 while iter <= n: sum += iter**2 iter += 1 return sum
def is_sibling_of(page1, page2): """ Determines whether a given page is a sibling of another page :: {% if page|is_sibling_of:feincms_page %} ... {% endif %} """ try: return page1.parent_id == page2.parent_id except AttributeError: return False
def arrayOfFileNames(files): """ Returns a list of file names (strings) without any ".F90" on the end. :param files: A list of file names :return: A list of file names without ".F90" """ result = [] for filename in files: # It's not clubb_api_module is it? if not ("clubb_api...
def create_pid_pname_from_path(pid, pname): """ :param pid: :param pname: :return: PID.xxxx.PNAME.... """ return 'PID.' + str(pid) + '.PNAME.' + pname.upper()
def hook_newHeadline(VO, level, blnum, tlnum): """Return (tree_head, bodyLines). tree_head is new headline string in Tree buffer (text after |). bodyLines is list of lines to insert in Body buffer. """ tree_head = 'NewHeadline' # choose = or + headline type -- same as previous headline if tl...
def list_to_string(list_, sep=", "): """Transforms a list of names, like ['a', 'b', 'c'], into a single string of names, like "a, b, c".""" result = ["{c}".format(c=c.replace("'", "")) for c in list_] return sep.join(result)
def is_keyphrase(labeled_candidate, tags, pos_sequences, tagging_notation="BILOU"): """Receive labeled candidate and return true or false""" labels, candidate_spans = labeled_candidate start, end = candidate_spans["span"] expected_tokens = end - start is_valid = False if tagging_notation == "BIO...
def formatFilterEntry(slotNum, filterName): """Format an entry for the filter wheel menu Inputs: - slotNum: slot number; must be an integer - filterName: name of filter in this slot """ if slotNum is None: raise ValueError("Invalid slotNum=%s; must be an integer" % (slotNum,)) i...
def should_log_full_credential(key): """ Returns true if we should log the value of the credential given the key (name) of the credential For robustness, prefer an allowlist over a blocklist """ suffix_allowlist = [ # generic '_TYPE', # s3 '_REGION', '_ENDPO...
def vibi_calc(ndvi, ndbi): """ Vegetation index built-up index """ return ndvi/(ndvi + ndbi)
def color_mapping(color): """ Convert pyte color to PIL color """ if color == 'default': return 'lightgray' if color in ['green', 'black', 'cyan', 'blue', 'brown']: return color try: return (int(color[0:2], 16), int(color[2:4], 16), int(color[4:6], 16)) except: ...
def parse_stats(tup): """ Parses read stats using MP after reading :param tup: (key, (aln_scores, mapq_scores, sramm_scores)) tuple :return: read_id, mapq value(s), sramm metric scores """ # data[k] = [(int(x[0]), int(x[1])) for x in # [t.replace('(', '').replace(')', '').sp...
def is_corect_parantheses(pattern): """ "{[()[]()]}" returns True. """ if type(pattern) != str: raise TypeError("param @pattern should be str.") stack = [] mapped = {")":"(", "]":"[", "}":"{"} for character in pattern: if character in mapped: if stack: to...
def findNthFibonnachiNumberIterative(n: int) -> int: """Find the nth fibonacchi number Returns: int: the number output """ if n <= 2: return 1 first, second = 0, 1 while n-1: third = first + second first = second second = third n -= 1 return...
def calculate_f1(num_label, num_infer, num_correct): """calculate_f1""" if num_infer == 0: precision = 0.0 else: precision = num_correct * 1.0 / num_infer if num_label == 0: recall = 0.0 else: recall = num_correct * 1.0 / num_label if num_correct == 0: f...
def split_headers_list(headers): """ Split the headers list into unique elements instead of 1 string. Args: headers (list): headers output from fasta_parser Returns: split_headers (list): headers list split into components. no_chrom (list): all things that are not the chromosome....
def step(x, high, low, threshold): """ Returns a decay factor based on the step function .. math:: f(x) = \\begin{cases} high & \\mbox{if} x < threshold; \\\\ low & otherwise. \\end{cases} :param x: The function argument. :pa...
def get_neighbors(r_index, c_index): """Get neighboring cell positions Args: r_index (int): Current row index c_index ([type]): Current column index Returns: [List of list of integers]: List of neighbors with each neighbor containing a list of their row and column index. ...
def collect(collection, fn): """Collects items where the function evalueates as true""" results = [] for item in collection: if fn(item): results << item return results
def IsShowtime( string ): """Determines whether string has the format xx:xx, where xx = pair of digits. """ s = string.strip() if len(s) == 5 and s[2] == ":" and s[:2].isdigit() and s[3:].isdigit(): return True else: return False
def reverse_match(seq: str, recog: list) -> (bool): """ Match the sequence with a recognition sequence in reverse. :param seq: the sequence to search in :param recogn: a list with bases that should be matched subsequently :return: True if the sequence matches the ...
def blank_line(line): """checks if provided line is blank line or not. Args: line (str): input line Returns: bool: is line blank or not """ return not line.strip()
def _convert_keyword(keywords): """Convert keywords collection.""" if isinstance(keywords, list): return keywords if isinstance(keywords, dict): return keywords.keys()
def convert_command_group_all(test): """command-group-all superseded by run-bash-script and run-powershell-script""" cmds = [x['command'] for x in test['args'].pop('commands')] test['args']['source'] = '\n'.join(cmds) if 'windows' in test['name']: test['type'] = 'run-powershell-script' else:...
def find(lst, key, value): """ Searches a list of dictionaries by value of a specified key. Find the first item from a list of dicts where the key identified by ``key`` has the value specified by ``value``. Args: lst (list of dict): List of dictionaries to search key (str): Key to comp...
def to_list(item): """ If the given item is iterable, this function returns the given item. If the item is not iterable, this function returns a list with only the item in it. @type item: object @param item: Any object. @rtype: list @return: A list with the item in it. """ if ...
def word_cleaner(word_to_clean): """Removes any punctuation from word Args: word_to_clean: Dirty word Returns A word without punctionation [a...zA...Z] """ clean_word = "" first = 0 # position of first word last = len(word_to_clean) - 1 # position of last word count =...
def to_feature(obj): """Converts an object to a GeoJSON Feature Returns feature verbatim or wraps geom in a feature with empty properties. Raises ------ ValueError Returns ------- Mapping A GeoJSON Feature represented by a Python mapping """ if obj['type'] == 'Fea...
def is_covered_class_name(class_name, generated_class_names): """We exclude classes generated by immutables.""" for generated_class_name in generated_class_names: if class_name == generated_class_name or class_name.startswith(generated_class_name + '$'): return False return True
def is_inoperable(value): """ Check if value cannot be processed by OmniSci engine. Parameters ---------- value : any A value to check. Returns ------- bool """ if isinstance(value, (tuple, list)): result = False for val in value: result = re...
def _stac_key_order(key: str): """All keys in alphabetical order, but unprefixed keys first.""" if ":" in key: # Tilde comes after all alphanumerics. return f"~{key}" else: return key
def _binary_combinations(n): """ Returns all possible combinations of length n binary numbers as strings """ combinations = [] for i in range(2**n): bin_value = str(bin(i)).split('b')[1] while len(bin_value) < n: bin_value = "0" + bin_value combinations.append(b...
def IsVector(paramType): """ Check if a param type translates to a vector of values """ pType = paramType.lower() if pType == 'integer' or pType == 'float': return False elif pType == 'color' or pType.startswith('float'): return True return False
def line_to_slope(coord1, coord2): """ A simple function to get the slope between two lines :param coord1: :param coord2: :return: """ try: slope = float(coord1[1] - coord2[1]) / float(coord1[0] - coord2[0]) return slope except ZeroDivisionError: return 0.
def camel_case_to_lower_case_underscore(string): """ Split string by upper case letters. F.e. useful to convert camel case strings to underscore separated ones. @return words (list) """ words = [] from_char_position = 0 for current_char_position, char in enumerate(string): if c...
def feature_count(s, sep=':'): """Read feature and count from a string in format of "feature:count". Parameters ---------- s : str Input string. sep : str, optional Separator between feature and count (default: colon). Returns ------- tuple of (str, int) Pair of...
def hex(color: tuple, prefix: str='#') -> str: """ Convert RGB to HEX. :param color: 3-element tuple with color RGB values :param prefix: string prefix :return: string with color in hex """ if len(color) is not 3: raise ValueError('Color should be a 3 element tuple') if not all(...
def my_rotate_word(word: str, t: int) -> str: """My version of Caesar cypher. Uses only the aplphabet letters, makes no distinction between lower case or upper case letters and was not tested for negative rotations. Created in the exercise rotate.py word: string that's going to be encrypted. ...
def traverse_dict(dic, entry_list): """This function traverses a dictionary with a given list of keys and returns the value or None if the keys are not found. Args: dic(dict): The dictionary to traverse. entry_list(list: list): The list of keys you want to traverse with. entry_list: ...
def for_loop(function, argument_list): """Apply a univariate function to a list of arguments in a serial fashion. Uses Python's built-in for statement. Args: function: A callable object that accepts one argument argument_list: An iterable object of input arguments Returns: Lis...
def msecs_to_mins_and_secs(msecs): """ Convert milliseconds to minutes and seconds. msecs is an integer. Minutes and seconds output is a string.""" secs = int(msecs / 1000) mins = int(secs / 60) remainder_secs = str(secs - mins * 60) if len(remainder_secs) == 1: remainder_secs = "0" + r...
def count_descendents(graph, root): """ Inputs: A weighted directed acyclic `graph` with positive edge weights and a starting `root` node Let the weight of a path in the graph be the product of the weights of its constituent edges and 0 if the path is trivial with no edges Returns: The sum of the we...
def Euclidean_Distance(x,y,Boundaries = 'S',Dom_Size=1.0): """ Euclidean distance between positions x and y. """ d = len(x) dij = 0 #Loop over number of dimensions for k in range(d): # Compute the absolute distance dist = abs( x[k] - y[k] ) #Extra condition for periodic BCs: if Boundaries == 'P' o...
def notebook_header(text): """ Insert section header into a jinja file, formatted as notebook cell. Leave 2 blank lines before the header. """ return f"""# # {text} """
def _is_leap(y): """True if y is a leap year.""" return (y % 400 == 0 or (y % 4 == 0 and y % 100 != 0))
def curtail_string(s: str, length=20) -> str: """Trim a string nicely to length.""" if len(s) > length: return s[:length] + "..." else: return s
def filter_matches(this, prev): """ filter match array Logic to determine if a match is overlapped by another match :param this: the match currently be checked :param prev: an earlier (longer) match currently being compared against :return boolean indicating overlap """ s = t...
def get_electricity_production(power_utilities): """Return the total electricity production of all PowerUtility objects in MW.""" return sum([i.production for i in power_utilities]) / 1000
def tokenize(text): """Simple tokenizer, change for something more sophisticated """ return text.lower().split()
def RepresentsFloat(val): """ Takes string and checks if value represents float number >>> RepresentsComplex('10.1') True >>> RepresentsComplex('Am I Float?') False """ try: float(val) return True except: return False
def graph_to_dot(front_edges, background_edges, total_weight=None, root=None, name='graph'): """Given a graph consisting of front edges and background edges and a name, generate a corresponding dot representation for the graph. :param front_edges: a set of focused edges :type f...
def separate_values_to_two_lines(table_as_list: list, column_width: int): """ If there are two values of the one statistic in different units in one line, replace this line with two lines, each containing value in one unit. """ for i, line in enumerate(table_as_list): has_two_units = line.co...
def tokenise_table_name(table_name): """Given a feature class or feature dataset name, returns the schema (optional) and simple name""" dot_count = table_name.count(".") if dot_count == 2: dot_pos = [pos for pos, char in enumerate(table_name) if char == "."] return { "database...
def find_sols(f, arr, sign_check_func = lambda x, y: x*y < 0, verbose = False): """ Given an array of section points, checks if function *f* has a solution in any of the intervals formed by said points. """ sols = [] for i in range(len(arr)-1): if sign_check_func(f(arr[i]), f(arr[i+1])):...
def camelize(val): """Return the camel case version of a :attr:`str` >>> camelize('this_is_a_thing') 'thisIsAThing' """ s = ''.join([t.title() for t in val.split('_')]) return s[0].lower()+s[1:]
def base_msg_type(type_): """ Compute the base data type, e.g. for arrays, get the underlying array item type @param type_: ROS msg type (e.g. 'std_msgs/String') @type type_: str @return: base type @rtype: str """ if type_ is None: return None if '[' in type_: return...
def wrap_geom(geom): """ Wraps a geometry dict in an GeoJSON Feature """ return {'type': 'Feature', 'properties': {}, 'geometry': geom}
def capitalize(item): """Capitlise first letter without losing camelcasing""" return (item[0].upper() + item[1:])
def path_states(path): """Return a list of states in this path. A path is a list of the form [state, action, state, action, ... ] """ return path[0: len(path) - 1: 2]
def prep_single_sample_metadata(sample_metadata): """ Function For Parsing Single Row in Metadata """ fileID = sample_metadata['File ID'] fileName = sample_metadata['File Name'] caseID = sample_metadata['Sample ID'] return {'directory': fileID, 'fileName':fileName, 'barcode':caseID}
def hamming(a, b): """Hamming distance""" diffs = ([x for x in a if x not in b] + [x for x in b if x not in a]) return len(diffs)
def bj_seek_in_children_by_guid(node, guid): """Search the child item with specific GUID and return it.""" for item in node['children']: try: if item['guid'] == guid: return item except KeyError: pass # Simply ignore items without GUID. return ...
def true_positive(y_true, y_pred): """ Function to calculate true positives :param y_true: list of true values :param y_pred: list of predicted values :return: number of true positives """ # initialize counter tp = 0 for yt, yp in zip(y_true, y_pred): if yt == 1 and yp == 1: ...
def rgb_to_hsv(rgb): """ Convert an RGB color representation to an HSV color representation. (r, g, b) :: r -> [0, 255] g -> [0, 255] b -> [0, 255] :param rgb: A tuple of three numeric values corresponding to the red, green, and blue value. :return: HSV represent...
def get_image_url(image_url, target_size='original'): """Given an image URL (of any size), return the URL for the specified size""" if not str(image_url).startswith('http'): return None for size in ('square', 'small', 'medium', 'large', 'original'): image_url = image_url.replace(size, target...
def bubble_sort(array): """ Bubble Sort Complexity: O(N^2) """ array_len = len(array) for k in range(array_len - 1): for i in range(array_len - k - 1): if array[i] > array[i+1]: temp = array[i+1] array[i+1] = array[i] ...
def strip_end(text, suffix): """Strips suffix from string. Essentially, polyfill for removesuffix in Python 3.9.""" if suffix and text.endswith(suffix): return text[:-len(suffix)] return text
def json_date(date=None): """Given a db datetime, return a steemd/json-friendly version.""" if not date: return '1969-12-31T23:59:59' return 'T'.join(str(date).split(' '))
def _parse_args(args): """ Parse an argument list. """ result = {} for arg in args: arg = arg.decode() if arg == "": continue if "=" in arg: key, value = arg.split("=", 1) result[key] = value else: result[arg] = True ...
def clean_name(name: str) -> str: """Ensures that names are composed of [a-zA-Z0-9] FIXME: only a few characters are currently replaced. This function has been updated only on case-by-case basis """ replace_map = { "=": "", ",": "_", ")": "", "(": "", "-"...
def note_distance(note_pair): """Get the distance in semitones between two named notes. E.g. (Bb1, B1) => 1 (C4, B4) => 11 (C5, Bb5) => 10 Parameters ---------- note_pair : tuple of ints Returns ------- note_distance : int """ char_map = {'C': 0, 'D': 2, 'E': 4...
def xml_value_from_key(xml,match,matchNumber=1): """ Given a huge string of XML, find the first match of a given a string, then go to the next value="THIS" and return the THIS as a string. if the match ends in ~2~, return the second value. """ for i in range(1,10): if match.endswith...
def max_divisible(a, b): """ Keep dividing(a/b) till it's divisible(a % b == 0) e.g. Input: a = 300; b = 2 Output: 75 :param a: :param b: :return: """ while a % b == 0: a = a / b return a
def split_all(s, chars): """Split on multiple character values. >>> split_all('a_b_c_d', '_. ') ['a', 'b', 'c', 'd'] >>> split_all('a b c d', '_. ') ['a', 'b', 'c', 'd'] >>> split_all('a.b.c.d', '_. ') ['a', 'b', 'c', 'd'] >>> split_all('a_b.c d', '_. ') ['a', 'b', 'c', 'd'] >>>...
def query_fragility_curve(f_curve, depth): """ Query the fragility curve. """ if depth < 0: return 0 for item in f_curve: if item['depth_lower_m'] <= depth < item['depth_upper_m']: return item['fragility'] else: continue print('fragility curve fa...
def subtraction(x, y): """ Subtraction x and y >>> subtraction(-20, 80) -100 """ assert isinstance(x, (int, float)), "The x value must be an int or float" assert isinstance(y, (int, float)), "The y value must be an int or float" return x - y
def isRootLink(link, childList): """Check if a link is root link.""" for child in childList: if link == child: return False return True
def avail_sizes(call=None): """ use templates for this """ return {"Sizes": "Sizes are built into templates. Choose appropriate template"}
def are_items_in_list(items, l): """Check if items are in a list. Parameters ---------- items : list A list of items (order does not matter). l : list A list. Returns ------- bool True if all items are in the list. False otherwise. """ for i...
def cdf_TPL(x, a, beta, b): """ Cumulative function for truncated power law. pdf(x) = (beta-1)/(a*(1-c^(beta-1))) * (a/x)^beta for a <= x <= b """ F = (1-(a/x)**(beta-1))/(1-(a/b)**(beta-1)) return F
def my_circle(my_radius): """Calculates the area of a circle given its radius. Keyword arguments: my_radius (float) -- Radius of the circle. Returns: Float -- Area of the circle. """ return (3.14 * my_radius * my_radius)
def fmt_mac(tup: bytes) -> str: """ converts a list of bytes into a readable mac address""" return "{:x}:{:x}:{:x}:{:x}:{:x}:{:x}".format(*tup)
def fatten_pancakes(dict): """ Making the pancake """ result_dict = dict.copy() result_dict["eggs"] = 6 result_dict["butter"] = True return result_dict
def d(value: bytes) -> str: """ Decode a bytestring for interpolating into an error message. """ return value.decode(errors="backslashreplace")
def get_slope(vector_one, vector_two): """Get the slope of a line specified by two vectors""" return(vector_two[1] - vector_one[1])/(vector_two[0] - vector_one[0])
def star_rating(score, buckets, low=1, high=5): """star rating""" if not buckets or len(buckets) < 2: return None step = (high - low) / (len(buckets) - 1) for i, (_, _, upper) in enumerate(buckets): if score <= upper: return low + i * step return high
def options(name, shortname=None): """ Return options for argparse. :param name: long name :param shortname: short name to override first character of long name :return: tuple with short and long options """ return f'-{shortname is None and name[0] or shortname}', \ f'--{name}'
def _parse_long(value): """ Attempts to parse the long-handed output console commands output, usually in a form similar to:: status: ACTIVE name: zzzd created_at: 2013-08-23 17:04:46 min_size: 1 last_modified: 2013-08-23 17:04:46 r...
def totalSizeOf(s): """ @type s: C{str} or L{StringFragment} @return An estimate of how much memory (in bytes) string C{s} consumes. @rtype: C{int} """ return 30 + len(s)
def slope_intercept_form(m, x, b): """ Handles the formula used for y=mx+b format to find slope """ m = float(m) x = float(x) b = float(b) return m * x + b
def pagename(f,p): """ Create freq/pol string for use in workbook and worksheet names @param f : frequency @type f : float @param p : polarization in three characters @type p : str @return: str """ return ("%5.2f-%3s" % (f,p)).strip()