content
stringlengths
42
6.51k
def make_suffix_string(args, suffix_key): """Make an InVEST appropriate suffix string. Creates an InVEST appropriate suffix string given the args dictionary and suffix key. In general, prepends an '_' when necessary and generates an empty string when necessary. Parameters: args (dict): t...
def check_file(fname): """Check that file can be read; exit with error message if not.""" try: f = open(fname, "rb") f.close() return 0 except IOError: print("ERROR: Could not read file", fname) return 1 sys.exit() f.close()
def count_chars(text: str, char_to_count: str) -> int: """Count the number of times that 'char_to_count' is found in the 'text'.""" count = 0 for char in text: if char == char_to_count: count += 1 return count
def best_units(num): """ Returns scale factor and prefix such that 1 <= num*scale < 1000""" if num < 1e-12: return 1e15, 'f' if num < 1e-9: return 1e12, 'p' if num < 1e-6: return 1e9, 'n' if num < 1e-3: return 1e6, 'u' if num < 1: return 1e3, 'm' if nu...
def _GetDefineName(name): """Get define-formatted name.""" name = name.replace('\'', '').replace('.', '').replace('/', '') name = 'R22_PARAM_' + name.replace(' ', '_').upper() return name
def tordist(x1: float, x2: float, wrap_dist: float ) -> float: """Calculate the toroidial distance between two scalars Args: x1(float) : first datapoint x2(float) : second datapoint wrap_dist(float) : wrapping distance (highest value), values higher than this will wrap around to zero ...
def prazen_kvadrat_n(n_vrstic): """ vrni string, ki bo narisal prazen kvadrat v velikost n_vrstic""" # BEGIN SOLUTION result = '' # END SOLUTION return result
def number_of_bins(data, resolution=None): """ Calculate the number of bins for requested resolution of the data Parameters ---------- data : numpy.ndarray of type float resolution : float Returns ------- bins : None or int Number of bins. If `resolution` <= 0 returns None....
def soundex(name, len=4): """ Code referenced from http://code.activestate.com/recipes/52213-soundex-algorithm/ @author: Pradnya Kulkarni """ # digits holds the soundex values for the alphabet digits = "01230120022455012623010202" sndx = "" fc = "" # Translate alpha chars ...
def hztous(hz): """ Convert frame rate in hz to microseconds between frames """ return (1/hz)*10**6
def seperate(text, provided_list=None) -> list: """ This seperates each character of a string and sorts them into a new list or a provided list. >>> test_text = "hello" >>> test_list = ['t', 'e', 's', 't', ' '] >>> print(seperate(test_text, test_list)) ['t', 'e', 's', 't', ' ', 'h', ...
def tan2tantwo(tan: float) -> float: """returns Tan[2*ArcTan[x]] assuming -pi/2 < x < pi/2.""" return 2 * tan / (1 + tan) / (1 - tan)
def _flatten(d, parent_key='', sep='.'): """flattens a dictionary into a list of (k, v) tuples.""" items = [] for k, v in d.items(): k_ = '{}{}{}'.format(parent_key, sep, k) if parent_key else k if isinstance(v, dict): items.extend(_flatten(v, k_, sep=sep)) else: ...
def has_file_allowed_extension(filename, extensions): """Checks if a file is an allowed extension. Args: filename (string): path to a file extensions (tuple of strings): extensions to consider (lowercase) Returns: bool: True if the filename ends with one of given extensions """ return filename.lower().ends...
def NN_moffat(x, mu, alpha, beta, logamp): """ One-dimensional non-negative Moffat profile. See: https://en.wikipedia.org/wiki/Moffat_distribution """ amp = 10**logamp return amp*(1. + ((x-mu)**2/alpha**2))**(-beta)
def sum_of_middle_three(score1,score2,score3,score4,score5): """Take 5 scores and return the sum without the minimum or maximum""" sum_of_all_five_scores = score1 + score2 + score3 + score4 + score5 min_score = min(score1,score2,score3,score4,score5) max_score = max(score1,score2,score3,score4,score5) ...
def ndarray(typed_array, shape, dtype): """Return a ndarray.""" _dtype = type(typed_array) if dtype and dtype != _dtype: raise Exception( "dtype doesn't match the type of the array: " + _dtype + " != " + dtype ) shape = shape or (len(typed_array),) return { "__jai...
def magic_index(arr): """ 8.3 Magic Index: A magic index in an array A [ 0... n -1] is defined to be an index such that A[i] = i. Given a sorted array of distinct integers, write a method to find a magic index, if one exists, in array A. FOLLOW UP What if the values are not distinct? For d...
def set_bit_to_one(number, position): """Sets the bit at the given position of the given number to 1.The position is counted starting from the left in the binary representation (from the most significant to the least significant bit). """ return number | (1 << (31 - position))
def area_calculation(list_of_coordinates): """takes a list of 2D-coordinates(tuples) and reutrns area""" if len(list_of_coordinates) == 0: return 0 area = 0 l = len(list_of_coordinates) for i in range(l-1): area = area + list_of_coordinates[i][0]*list_of_coordinates[i+1][1] - list_of_coordin...
def gc_skew(seq): """ Calculate GC skew (g-c)/(g+c) for sequence. For homopolymer stretches with no GC, the skew will be rounded to zero. Args: seq (str): Nucleotide sequence Examples: >>> sequtils.gc_skew('AGGATAAG') 3.0 """ seq = seq.upper() g = seq.count(...
def unescape_jsonpointer_part(part: str) -> str: """convert path-part according to the json-pointer standard""" return part.replace("~1", "/").replace("~0", "~")
def scanning_title_provider(body): """Get the title of a page from its content body. This implementation does not use a standard xml parser. Instead, it scans the body text looking for content between <title> and </title>. This adds the benefit of working with invalid, or non-standard, xhtml content. ...
def _lines(text): """Split text into lines, stripping and returning just the nonempty ones. Returns None if the result would be empty.""" lines = [x for x in map(lambda x: x.strip(), text.split('\n')) if len(x) > 0] if len(lines) == 0: return None return lines
def level_to_criticality(level: int) -> str: """Translate level integer to Criticality string.""" if level >= 4: return 'Very Malicious' elif level >= 3: return 'Malicious' elif level >= 2: return 'Suspicious' elif level >= 1: return "Informational" return 'Unknow...
def get_provenance_record(plot_file, caption, run): """Create a provenance record describing the diagnostic data and plot.""" record = { 'caption': caption, 'statistics': ['mean'], 'domains': ['global'], 'plot_types': ['map', 'metrics'], 'authors': [ 'burke_el...
def _extract_spotify_id(raw_string): """ :param raw_string: :return: """ # print raw_string # Input string is an HTTP URL if raw_string.endswith("/"): raw_string = raw_string[:-1] to_trim = raw_string.find("?") if not to_trim == -1: raw_string = raw_string[:to_trim] ...
def make_sector_identifier(intersection): """ Makes a text version of the database id in the given intersection """ return f'{intersection["id"]}'
def get_principal(user, realm): """Convert OpenAFS k4 style names to k5 style principals.""" return "%s@%s" % (user.replace('.', '/'), realm)
def bubble_sort(unsorted_list): """ Function sorting input list with bubble sort algorithm :param unsorted_list: input list with unsorted elements :return: copy of input list with sorted elements """ sorted_list = unsorted_list.copy() posortowana = False while not posortowa...
def _convert_now(arg_list): """ Handler for the "concatenate" meta-function. @param IN arg_list List of arguments @return DB function call string """ nb_args = len(arg_list) if nb_args != 0: raise Exception("The 'now' meta-function does not take arguments (%d provided)" % nb_args) ...
def _get_architecture_or_default(environment): """Returns the current target architecture or the default architecture if none has been explicitly set. @param environment Environment the target architecture will be looked up from @returns The name of the target architecture from the environment or a d...
def getTreeString(x, y, z, numLogs): """ Returns a Malmo string to use in the mission XML to create a tree. """ leavesHeight = y + 4 treeHeight = y + numLogs return """ <DrawingDecorator> <DrawSphere x="{x}" y="{yLeaves}" z="{z}" radius="3" type="leaves" /> <DrawLine x1="{x}" y1="{y}" z1="{z}" x...
def parseline(line,format): """\ Given a line (a string actually) and a short string telling how to format it, return a list of python objects that result. The format string maps words (as split by line.split()) into python code: x -> Nothing; skip this word s -> Return this word ...
def latex_clean_label(s: str) -> str: """Clean label for troublesome symbols""" return s.replace("_", " ")
def is_valid_jwt(jwt: str) -> bool: """ Check your jwt. Parameters ---------- jwt: str jwt string. Returns ------- bool True if jwt is valid , False else """ return len(jwt.split(".")) == 3
def formatIntervalHours(cHours): """ Format a hours interval into a nice 1w 2d 1h string. """ # Simple special cases. if cHours < 24: return '%sh' % (cHours,); # Generic and a bit slower. cWeeks = cHours / (7 * 24); cHours %= 7 * 24; cDays = cHours / 24; cHours %= 24;...
def reverse(seq): """Return the reverse of the given sequence (i.e. 3' to 5').""" return seq[::-1]
def is_valid(passport): """ Validates a passport that contains all required fields. I decided not to use regex for some reason. """ valid_years = ( (1920 <= int(passport["byr"]) <= 2002) and (2010 <= int(passport["iyr"]) <= 2020) and (2020 <= int(passport["eyr"]) <= 2030) ...
def screencast_frame_ack(sessionId: int) -> dict: """Acknowledges that a screencast frame has been received by the frontend. Parameters ---------- sessionId: int Frame number. **Experimental** """ return {"method": "Page.screencastFrameAck", "params": {"sessionId": sessionId}}
def fill_oc_stress_period_data(stress_period_data, nper): """For MODFLOW 2005-style models, repeat last entry in stress_period_data for subsequent stress periods (until another entry is encountered), as is done by default in MODFLOW 6. """ filled_spd = {} last_period_data = {} for period in ...
def spec_key_comparator(key_a: str, key_b: str) -> int: """ Comparator to sort spec keys putting the '*' key last. """ if key_a == '*': return 1 elif key_b == '*': return -1 return key_a.__lt__(key_b)
def remove_packaging(symbol: str): """Remove package names from lisp such as common-lisp-user:: Args: symbol (str): string to have package name striped Returns: str: symbol input with package name removed (if present) """ split_symbol = symbol.split('::') return symbol if len(s...
def _get_element_or_alt(data, element, alt): """ if :element: is in dict :data: return it, otherwise return :alt: """ if element in data: return data[element] else: return alt
def parse_extensions(ext): """ Parse the extensions as given in the format and convert it into a dictionary. <category>:<ext1> <ext2> <ext3> .... Args: ext (str): A string containing the extensions as the format given in the top of this file. Returns: dict: A dictionary representin...
def poincare_half_space_params(n_samples): """Generate poincare half space benchmarking parameters. Parameters ---------- n_samples : int Number of samples to be used. Returns ------- _ : list. List of params. """ manifold = "PoincareHalfSpace" manifold_args = [...
def fListToString(a_list, a_precision=3): """ returns a string representing a list of floats with a given precision """ # CHECKME: please tell me if you know a more comfortable way.. (print format specifier?) l_out = "[" for i in a_list: l_out += " %% .%df" % a_precision % i l_out += "]" ...
def strip(s, chars=None): """ Return a version of s with characters in chars removed from the start and end. By default, removes whitespace characters. """ return s.strip(chars)
def FormatDatetime(date): """Returns a string representing the given UTC datetime.""" if not date: return None else: return date.strftime('%Y-%m-%d %H:%M:%S UTC')
def _padding_arg(h, w, input_format): """Calculate the padding shape for tf.pad(). Args: h: (int) padding on the height dim. w: (int) padding on the width dim. input_format: (string) the input format as in 'NHWC' or 'HWC'. Raises: ValueError: If input_format is not 'NHWC' or 'HWC'. Returns: ...
def _fill_fields(fields, values): """Fill all possible *fields* with key/[value] pairs from *values*. :return: subset of *values* that raised ValueError on fill (e.g. a select could not be filled in because JavaScript has not yet set its values.) """ unfilled = [] for name, field_values in v...
def convert_base_to_aux(new_base: float, close: float): """converts the base coin to the aux coin Parameters ---------- new_base, the last amount maintained by the backtest close, the closing price of the coin Returns ------- float, amount of the last base divided by the clo...
def _get_ground_state(states, energies, j_list, j0=None): """Gets the ground state and ground energy from the list of states, energies, and angular momenta. This is chosen by finding the state with lowest associated energy for which angular momentum matches j0 :param states: list of energy states :...
def poly(y,alpha): """Bias: Polynomial Transformation for WFG1 Transition 3.""" return ( pow( y, alpha ) )
def prepare(data): """Restructure/prepare data about merges for output.""" sha = data.get("sha") commit = data.get("commit") message = commit.get("message") tree = commit.get("tree") tree_sha = tree.get("sha") return {"message": message, "sha": sha, "tree": {"sha": tree_sha}}
def chromedriver_path_of(system_name) -> str: """Gets system name and returns a string path :param string system_name: should be "Windows", "Linux" or "Darwin". System name can be obtained from "platform" module and "system" function """ if system_name == 'Windows': return "./chromedriver....
def displayHits(hits): """ Handles the I/O of the song-searching functionality Parameters ---------- hits : list Holds json dictionaries with information of the songs that the search turned up Returns ------- integer Either -1 if no song was chosen or the index in hits with the appropriate song's...
def dynamic_suffix(is_pretty: bool) -> str: """Return the suffix of the dynamic wrapper of a method or class.""" if is_pretty: return '*' else: return '___dyn'
def durationToShortText(seconds): """ Converts seconds to a short user friendly string Example: 143 -> 2m 23s """ days = int(seconds / 86400000) if days: return '{0} d'.format(days) left = seconds % 86400000 hours = int(left / 3600000) if hours: hours = '{0} h '.forma...
def same_subtitle(subtitle1, subtitle2) -> bool: """Check if same subtitle, needed because other attributes can be differ""" if subtitle1 == subtitle2: return True if subtitle1 is None or subtitle2 is None: return False if (subtitle1['name'] == subtitle2['name'] and subtitle1[...
def isString(strng, encoding): """ Returns true if the string contains no ASCII control characters and can be decoded from the specified encoding. """ for char in strng: if ord(char) < 9 or ord(char) > 13 and ord(char) < 32: return False try: strng.decode(encodi...
def trp(l, n): """ Truncate or pad a list """ r = l[:n] if len(r) < n: r = list(['0']) * (n - len(r)) + r return r
def counting_sort(numbers): """Sort given numbers (integers) by counting occurrences of each number, then looping over counts and copying that many numbers into output list. Running time: O(n + k) where k is the range of numbers, because if k is really high then affects the run time significantly. Memo...
def GetColumnOrder(column_headers): """Converts GA API columns headers into a column order tuple used by Gviz. Args: column_headers: A list of dicts that represent Column Headers. Equivalent to the response from the GA API. e.g. [ ...
def is_rule(line: str, starting_chr: str = '*', omit: str = 'NOTE') -> bool: """If the first character of the line is the selected character and the line doesn't contain the omitted text (case-sensitive).""" return True if line.startswith(starting_chr) and line.find(omit) == -1 else False
def dame(n, f): """Na sahovnico velikosti n x n postavi n sahovskih dam, tako da se ne napadajo. Poiscemo vse resitve. Vsakic, ko najdemo resitev r, izvedemo f(r).""" def ne_napadajo(r,i,j): """Ze razvrscene dame v seznamu r ne napadajo polja (i,j).""" for (u,v) in enumerate(r): ...
def business_rule_1(amount: int, use_br: bool, threshold: int) -> bool: """ Account receives a transaction with value >= threshold within a day. :param amount: transaction value :param use_br: whether to use this br :param threshold: the threshold :return: True when the laundering was successfu...
def _describe_image_attribute_response(response, attribute, attr_map): """ Generates a response for a describe image attribute request. @param response: Response from Cloudstack. @param attribute: Attribute to Describe. @param attr_map: Map of attributes from EC2 to Cloudstack. @return: Respons...
def get_item(iterable_or_dict, index, default=None): """Return iterable[index] or default if IndexError is raised.""" try: return iterable_or_dict[index] except (IndexError, KeyError): return default
def iterable(obj): """ check if an object is iterable """ try: iter(obj) except Exception: return False else: return True
def create_signature_header(encoded_authn_params, signature): """ Combine the encoded authentication parameters string and signature string into the signature header value. """ return f"{encoded_authn_params.decode('utf-8')}.{signature}"
def list_divide(vec, val): """ Returns ------- out : list Input list 'vec' divided by the value 'val'. """ return [vec[0]/val, vec[1]/val]
def check_for_tree(map, width, pos): """ Checks a position on the map for a tree :param map: List of string representing map :param pos: Position to check :return: 1 if there is a tree, 0 if not """ x = pos[0] % width y = pos[1] if map[y] != '' and map[y][x] == '#': return 1 ...
def mentions(value, *terms): """Do any of the `terms` mention `value`?""" for term in terms: if term in value: return term
def falling_edge_count(array): """ Loop through all of the elements in the array and count the number of times that the value switches from 1 to 0 (falling edges) :param array: Input data buffer array - values are 0 or 1 :return: Count of times the value in the array falls from 1 to 0 (number of pul...
def UnpackResDat(resdat): """ Unpack 'res' data :param str resdat: 'res' data :return: resnam(str),resnmb(int),chain(str) :seealso: lib.PackResDat() """ # resdat: resnam:resnmb:chain -> resnam,resnum, chain name resnam=''; resnmb=-1; chain='' if len(resdat) > 0: i...
def is_null(val): """Check if a value is null, This is needed b/c we are parsing command line arguements and 'None' and 'none' can be used. """ return val in [None, 'none', 'None']
def ipv4(value): """ Return whether or not given value is a valid IP version 4 address. This validator is based on `WTForms IPAddress validator`_ .. _WTForms IPAddress validator: https://github.com/wtforms/wtforms/blob/master/wtforms/validators.py Examples:: >>> ipv4('123.0.0.7') ...
def alias(alias): """Select a single alias.""" return {'alias': alias}
def count_to_write(link_counters): """Find the to_write count in the counters returned by a CommunicationLink.""" for processor in link_counters.values(): if 'to_write' in processor: return processor['to_write']
def normalize_string(string: str) -> str: """ removes trailing or leading whitespace, then converts it to lowercase """ return string.strip().casefold()
def hamming_distance(first, second): """Calculate Hamming Distance, number of mismatched nucleotides in two DNA sequences Arguments: first {String} -- First DNA sequence second {String} -- Seconde DNA sequence Returns: integer -- Number of mismatches """ sum = 0 ...
def get_direct_url(data: dict) -> str: """ Returns the direct video URL from the returned data by YoutubeDL, like https://r1---sn-vg5obxn25po-cjod.googlevideo.com/videoplayback?... """ return data['entries'][0]['url']
def matchDict(label, input): """Match input to the pattern described by label. Both label and input are dictionaries with keys-values pairs. The format of the value in each key-value pair of label can be: - an atomic element. E.g., {..., 'headForm':'is', ...} - a list of possib...
def check_ranges(total_length, ranges): """ Check to make sure the given ranges are valid. Inputs: - total_length: Integer giving total length - ranges: Sorted list of tuples giving (start, end) for each range. Returns: Boolean telling whether ranges are valid. """ # The start of the first range m...
def strip_HTML(s): """Simple, clumsy, slow HTML tag stripper""" result = '' total = 0 for c in s: if c == '<': total = 1 elif c == '>': total = 0 result += ' ' elif total == 0: result += c return result
def _build_trie(patterns): """Build and return trie like in "trie.py", by using dictionary of dictionaries""" trie = dict() new_node_label = 0 trie[new_node_label] = dict() new_node_label += 1 root = trie[0] for pattern in patterns: current_node = root for current_symbol in p...
def calc_bound(end_point, tick_interval, is_upper): """ Finds an axis end point that includes the value *end_point*. If the tick mark interval results in a tick mark hitting directly on the end point, *end_point* is returned. Otherwise, the location of the tick mark just past *end_point* is retur...
def small_qing(ind, k=10.): """Qing function defined as: $$ f(x) = \sum_{i=1}^{n} (x_i^2 - i)^2$$ with a search domain of $-4 < x_i < 4, 1 \leq i \leq n$. """ return sum(( (ind[i]**2. - i)**2. for i in range(len(ind)))),
def get_location_id(location): """ :param: location :return: location ID """ locations = { 'USA_AK_FAIRBANKS': 1, 'USA_CA_LOS_ANGELES': 2, 'USA_IL_CHICAGO-OHARE': 3, 'USA_MN_MINNEAPOLIS': 4, 'USA_TX_HOUSTON': 5, 'USA_WA_SEATTLE': 6 } return loc...
def is_ok_dataset(r): """Convenience test for a non-failure dataset-related result dict""" return r.get('status', None) == 'ok' and r.get('type', None) == 'dataset'
def lcs(str_in, shift): """lcs(): """ return str_in[shift:] + str_in[:shift]
def get_time(t): """Time in min sec :param t: Run time :type t: float :returns: str """ minutes = t // 60 seconds = t % 60 return f"""{minutes:.0f} min:{seconds:.0f} sec"""
def sol(arr): """ Naive solution. Complexity is n^2 """ n = len(arr) s = 0 m = 0 while s < n: st = s c = 0 h = {} while st < n: if arr[st] in h: break else: h[arr[st]] = 1 c += 1 ...
def valid_url(string): """Checks if the given url is valid Parameters ---------- string: str Url which needs to be validated Returns ------- bool """ if string and (string[:7] == "http://" or string[:8] == "https://"): return True return False
def create_email_field_dict(field_name, field_type, field_value, field_displayed_text, is_allow_create_indicator, is_href, is_editable, ...
def run_filters( vdat, filtering = None ): """ vdat - dictionary of INFO field from VCF line filtering - dictionary of fields to be filtered; defaults to None Currently implemented for sensitive and specific. Can modify the filters to return False anytime you want to not report results based on filteirng criteri...
def delegate(session_attributes, slots): """ Defines a delegate slot type response. """ return { "sessionAttributes": session_attributes, "dialogAction": {"type": "Delegate", "slots": slots}, }
def find_nearest_wordpiece_index(offset_index, offset_to_wp, scan_right=True): """According to offset_to_wp dictionary, find the wordpiece index for offset. Some offsets do not have mapping to word piece index if they are delimited. If scan_right is True, we return the word piece index of nearest right byte, n...
def get_disk_volume_name(instance_name, diskNumber): """Return persistent volume name based on instance name and disk number """ return '%s-disk-%02d' % (instance_name, diskNumber)