content
stringlengths
42
6.51k
def cond_probs(obs): """ Computes a discrete conditional probability distribution from two lists of observations. :param obs: An ordered list of observations. :return: Dict: A discrete conditional probability distribution, represented as a dictionary. """ if type(obs) is str: ...
def count_circle_lattice_points(cx: int, cy: int, r: int, k: int) -> int: """ count up integer point (x, y) in the circle centered at (cx, cy) with radius r. and both x and y are multiple of k. """ assert r >= 0 and k >= 0 cx %= k cy %= k def is_ok(dx: int, dy: int) -> b...
def substitute_ascii_equivalents(text_unicode): # Method taken from: http://code.activestate.com/recipes/251871/ """ This takes a UNICODE string and replaces Latin-1 characters with something equivalent in 7-bit ASCII. It returns a plain ASCII string. This function makes a best effort to convert Lat...
def c2f(t): """ Converts Celsius Temperature to Fahrenheit Temperature. """ return t * float(1.8000) + float(32.00)
def remove_empty(data): """Removes empty items from list""" out = [] for item in data: if item == '': continue out.append(item) return out
def get_name_by_index(index, labels): """get name with acv for index Args: index ([int]): [index/labelcode] labels ([dict]): [labels] Returns: [String]: [name (acv)] """ name = "" acv = "" for x in labels: if (x.get('labelcode')==index): name = x...
def asint(value): """Coerce to integer.""" if value is None: return value return int(value)
def fib(n): """ Calculate the nth digit of Fibonacci 0 1 1 2 3 5 8 13 21 34 ... """ a, b = 0, 1 for i in range(n - 1): a, b = b, a + b return a
def count_classifier(words, pos, neg): """ Count the positive or negative words in the sentence return the label """ score = 0 for word in words: if word + ' ' in pos: score += 1 elif word + ' ' in neg: score -= 1 return score
def format(msg, leftmargin=0, rightmargin=78): """Format a message by inserting line breaks at appropriate places. msg is the text of the message. leftmargin is the position of the left margin. rightmargin is the position of the right margin. Return the formatted message. """ curs = leftma...
def denseFeature(feat): """ create dictionary for dense feature :param feat: dense feature name :return: """ return {'feat_name': feat}
def is_nan(value): """ Checks if value is 'nan' or NaT Parameters --------- value: object The object to be checked that it is not nan Returns --------- isnan: Boolean True: nan False: not nan """ isnan = str(value).lower() == 'nan' isnat = str(valu...
def sentence_to_token_ids(sentence, word2id): """ Gets token id's of each word in the sentence and returns a list of those words. Is called by data_to_token_ids and the Lexer. Args: sentence: A list of word tokens. word2id: A dictionary that maps words to its given id. This c...
def song_decoder(song): """Return decoded song string""" return ' '.join((song.replace("WUB"," ").strip()).split())
def cxSet(ind1, ind2): """Apply a crossover operation on input sets. The first child is the intersection of the two sets, the second child is the difference of the two sets. """ temp = set(ind1) # Used in order to keep type ind1 &= ind2 # Intersection (inplace)...
def floor(value, size, offset=200): """Floor of `value` given `size` and `offset`. The floor function is best understood with a diagram of the number line:: -200 -100 0 100 200 <--|--x--|-----|--y--|--z--|--> The number line shown has offset 200 denoted by the left-hand tick mark a...
def allclose(a, b, tol=1e-7): """Are all elements of a vector close to one another""" return all([abs(ai - bi) < tol for ai, bi in zip(a,b)])
def bounding_box(*boxes): """Compute a bounding box around other boxes.""" x0, y0, x1, y1 = boxes[0] for bx0, by0, bx1, by1 in boxes[1:]: x0 = min(x0, bx0) y0 = min(y0, by0) x1 = max(x1, bx1) y1 = max(y1, by1) return x0, y0, x1, y1
def get_count(results): """Creates a dictionary, word being the key, and word count being the value""" counts_dict = dict() for word in results: counts_dict[word] = counts_dict.get(word, 0) + 1 return counts_dict
def extractIniParam(iniparams, inStr): """ if inStr starts with $ then we return matching param from the ini params, otherwise return taskval Params: iniparams - the map of parameters derived from the ini file inStr - input string """ taskval = inStr if inStr.startswith('...
def get_csv_table(column_store, separator=";"): """Return a csv table from a column-store.""" csv_table = "" for idx in range(len(column_store[0])): columns = (column[idx] for column in column_store) csv_table += separator.join(columns) + "\n" return csv_table
def cmdline_for_pid(pid): """Get the commandline arguments list for a given pid. Potentially returns None if the process doesn't exist anymore.""" try: with open('/proc/%s/cmdline' % pid, 'rb') as f: return f.read().split(b'\0') except EnvironmentError: # process already ter...
def index_to_name(index): """Construct the full name for the node given its path.""" if index: return '.'.join(index) return 'everything'
def _xyz_vec2str(x): """Convert a vector to string. """ return "\t".join([str(i) for i in x])
def next_up(v, seq): """ Return the first item in seq that is > v. """ for s in seq: if s > v: return s return v
def parse_number(n) : """Try to cast intput first to float, then int, returning unchanged if both fail""" try : return float(n) if '.' in n else int(n) except : return n
def get_FY_sel(ef1, sf1, ef2, sf2, fy): """ NB have changed so it compares end of season and start of season, not start of consecutive seasons. This is because sexual reproduction can cause a change that wasn't due to the tactic but was just down to ratios starting away from those expected in...
def bgTiret(r, ra, b0, bi): """ Generalized Tiret et al. 2007 anisotropy profile. Parameters ---------- r : array_like, float Distance from center of the system. ra : float Anisotropy radius. b0 : float Anisotropy at r = 0. bi : float Anisotropy at r -> I...
def gcd(a, b): """ a, b: two positive integers Returns the greatest common divisor of a and b """ #YOUR CODE HERE if b == 0: return a else: return gcd(b, a % b)
def unescape(s): """Unescape &amp;, &lt;, and &gt; in a string of data. """ if '&' not in s: return s return s.replace('&gt;', '>').replace('&lt;', '<').replace('&amp;', '&')
def convert_tag(tag): """Convert the tag given by nltk.pos_tag to the tag used by wordnet.synsets""" tag_dict = {'N': 'n', 'J': 'a', 'R': 'r', 'V': 'v'} try: return tag_dict[tag[0]] except KeyError: return None
def add_blank_lines(player_data_list): """Add blank lines that will store differences. Args: player_data_list: player data list Returns: player data list with blank rows for differences """ length_appended = max([len(row) for row in player_data_list]) player_data_list = player_...
def _remove_empty_line(line): """function _remove_empty_line Args: line: Returns: """ return True if line.strip() == "" else False
def coq_axiom(name, type): """Coq axiom Arguments: - `name`: name of the axiom - `type`: type of the axiom """ return "Axiom {0!s} : {1!s}.\n".format(name, type)
def remove_call_brackets(call: str): """Return the given string with the trailing `()` removed, if present. NOTE Made redundant by `str.removesuffix("()")` in Python 3.9+ """ if call.endswith("()"): return call[:-2] return call
def rescale(inlist, newrange=(0, 1)): """ rescale the values in a list between the values in newrange (a tuple with the new minimum and maximum) """ OldMax = max(inlist) OldMin = min(inlist) if OldMin == OldMax: raise RuntimeError('list contains of only one unique value') O...
def _normalize_percent_rgb(value: str) -> str: """ Internal normalization function for clipping percent values into the permitted range (0%-100%, inclusive). """ value = value.split("%")[0] percent = float(value) if "." in value else int(value) return "0%" if percent < 0 else "100%" if per...
def is_prime(n: int) -> bool: """ Simple function to check if a given number n is prime or not Parameters ---------- n: int number that will be checked if it is prime or not Returns ------- bool: True if the given number (n) is prime, False if it is not """ while True: ...
def getFilenameFromDetails(details): """Takes a dictionary of details and makes a machine readible filename out of it. Angle comes in radians.""" filename = "{}_{:.3f}keV_{:.2f}ze_{:.2f}az".format(details['base'], details['keV'], ...
def to_ascii_hex(value: int, digits: int) -> str: """Converts an int value to ASCII hex, as used by LifeSOS. Unlike regular hex, it uses the first 6 characters that follow numerics on the ASCII table instead of A - F.""" if digits < 1: return '' text = '' for _ in range(0, digits):...
def is_three_doubles(word): """check if a word have three consecutive double letters.""" if word is None or len(word) < 6: return False consecutives = 0 index = 0 while index < len(word) - 1: if word[index+1] == word[index]: consecutives += 1 if consecutives =...
def get_response_tokens_from_object(_object): """Get response tokens from response payload""" if not _object: return [] options = _object.options or [] return [option.response_tokens for option in options if option.response_tokens]
def longest_increasing_subsequence_by_one(a): """ Solution: memo[i] stores the length of the longest subsequence which ends with a[i]. For every i, if a[i] - 1 is present in the array before the ith element, then a[i] will add to the increasing subsequence which has a[i] - 1. """ index_of = ...
def create_commit_map(resolved_sbom): """ Arrange packages by repository ( main, community ) Exclude sub-packages, since they share APKBUILD """ packages_commit = {} if 'dependencies' in resolved_sbom: i = 0 for package in resolved_sbom['dependencies']: parent =...
def frames_to_time_code(frames: int, fps: int) -> str: """ Function converts frames to time code `00:00:00:00` format :param frames: number of total frames :type frames: int :param fps: frames per second :type fps: int :return: time code format :rtype: str """ sec_in_min = 60 ...
def divide_set(rows, column, value): """ :param rows: :param column: :param value: :return: """ # for numerical values if isinstance(value, int) or isinstance(value, float): split_function = lambda row: row[column] >= value # for nominal values else: split_functi...
def convert_mug_to_cup(value): """Helper function to convert a string from mug to cup""" if isinstance(value, str) and value.lower() == 'mug': return 'cup' else: return value
def front(inlist): """ Pop from a list or tuple, otherwise return untouched. Examples -------- >>> front([1, 0]) 1 >>> front("/path/somewhere") '/path/somewhere' """ if isinstance(inlist, (list, tuple)): return inlist[0] return inlist
def encode_str(str): """Encode the string.""" str = str.replace('\r\n', ' ') str = str.replace('\n', ' ') str = str.replace('\r', ' ') str = str.replace('\\', '\\\\') str = str.replace('"', '\\"') str = '"' + str + '"' return str
def get_username_list(cmdline_username, config): """Get a list of possible usernames. Usernames are select from the command line and the config file. """ usernames = [] if cmdline_username: usernames = [cmdline_username] else: username = config.get('default-username') if...
def ms_to_kmh(value): """ # Convert m/s to km/h """ return value * 3.6 if value is not None else None
def get_mode_two_initial_mw(t2, min_loading, current_mode_time): """ Get initial MW when unit is in mode two and on fixed startup trajectory Note: InitialMW is based on trader's position within the fixed startup trajectory for fast-start units. This may differ from the InitialMW value reported by S...
def get_both_list(toLoggedInUser, fromLoggedInUser): """ This function takes the list of messages to and from the logged in user and organises them. The function takes two sorted lists and merges them in approximately O(n). This is done to ensure that messages are kept in order. """ bot...
def matlabize(s): """Make string s suitable for use as a MATLAB function/script name""" s = s.replace(' ', '_') s = s.replace('.', '_') s = s.replace('-', '_') assert len(s) <= 63 # MATLAB function/script name length limitation return s
def atttyp(att: str) -> str: """ Helper function to return attribute type as string. :param str: attribute type e.g. 'U002' :return: type of attribute as string e.g. 'U' :rtype: str """ return att[0:1]
def get_eval_tags(trg, pred): """Compares the pred to the trg Args: - trg (list): the target sequence (either a list of words or a list of tags S or C) - pred (list): the predicted sequence (either a list of words or a list of tags S or C) Returns: - tags (list): lis...
def pause_slicer(samp: int, width: int) -> slice: """Returns a slice object which satisfies the range of indexes for a pause point. The incoming numbers for samp are 1-based pixel numbers, so must subtract 1 to get a list index. The width values are the number of pixels to affect, including the ...
def cast_int(value): """ Cast value to 32bit integer Usage: cast_int(1 << 31) == -1 (where as: 1 << 31 == 2147483648) """ value = value & 0xffffffff if value & 0x80000000: value = ~value + 1 & 0xffffffff return -value else: return value
def determine_angle_label(angle: str) -> str: """ Determine the full angle label and return the corresponding latex. Args: angle: Angle to be used in the label. Returns: Full angle label. """ return_value = r"$\Delta" # Need to lower because the label in the hist name is upper ...
def nested(func, default=None): """ get a nested value if it exists, or return the given default if it doesn't Arguments: func(function): A function with no arguments that returns the nested value default: the default value...
def make_save_string(save_properties: list) -> str: """ :param save_properties: list of tuples containing (property, val) :return: save string with underscores delimiting values and properties """ save_string = "" return save_string.join([p + "_" + str(v) + "_" for p, v in save_properties])
def RSet(var, value): """Do a VB RSet Right aligns a string within a string variable. RSet stringvar = string If stringvar is longer than string, RSet replaces any leftover characters in stringvar with spaces, back to its beginning. """ return " " * (len(var) - len(value)) + value[:len(...
def app_icon_url(*args, **kwargs): """Get the URL to the application icon.""" app_id = args[0] return f"http://192.168.1.160:8060/query/icon/{app_id}"
def set_to_bounds(i_s, i_e, j_s, j_e, low=0, high=1): """ Makes sure the given index values stay with the bounds (low and high). This works only for 2 dimensional square matrices where low and high are same in both dimensions. Arguments: i_s : Starting value for row index i_e : ...
def update_bits(n, m, i, j): """ Update n with m at bit position from i to j :param n: original number to be updated :type n: int :param m: number to update :type m: int :param i: beginning bit position :type i: int :param j: ending bit position :type j: int :return: updated...
def channel_name(channel_number: int) -> str: """Gets the channel name associated with a channel number, e.g. 'Channel_19'. Parameters ---------- channel_number : int Which channel to generate the name for. Returns ------- str The name of the channel as a string. """ ...
def try_except_pass(errors, func, *args, **kwargs): """ try to return FUNC with ARGS, pass on ERRORS parameters ---------- errors a single error, or a tuple of errors. func a function that takes args and kwargs """ try: return func(*args, **kwargs) except errors...
def _understand_err_col(colnames): """Get which column names are error columns Examples -------- >>> colnames = ['a', 'a_err', 'b', 'b_perr', 'b_nerr'] >>> serr, terr = _understand_err_col(colnames) >>> np.allclose(serr, [1]) True >>> np.allclose(terr, [2]) True >>> serr, terr =...
def check_refcond(n, h, k, l): """Check reflection condition *n* against h, k, l. The condition number n is the same as in the PowderCell space-group file. """ if n == 0: return True elif n == 1: return h % 2 == 0 elif n == 2: return k % 2 == 0 elif n == 3: r...
def brie_mixing(Kliquid, Kgas, Sliquid, Sgas, brie_exp=3.0): """ Brie mixing of liquid and gas phases for pore filling fluids """ Kbrie = (Kliquid - Kgas)*(1.0-Sgas)**brie_exp + Kgas return Kbrie
def geopotential_to_geometric(h, r0): """Converts from given geopotential altitude to geometric one. Parameters ---------- h: float Geopotential altitude. r0: float Planet/Natural satellite radius. Returns ------- z: float Geometric altitude. """ z = r0...
def mean(num_lst): """ This function calculates the average of a list of numbers Parameters ------------- num_lst : list List of numbers to calculate the average of Returns ------------- The average/mean of num_lst Examples -------------- >>> mean([1, 2, 3, 4, 5]) ...
def remove_margin_slice(array_shape, slice_with_margin, slice_without_margin): """ Remove_margin_slice Parameters ---------- array_shape : tuple slice_with_margin : array_like slice_without_margin : array_like Returns ------- sliced_tuple : tuple """ slice_tuple = tupl...
def get_bytes(bits): """Returns bytes from list of bits""" number = int(''.join(bits), 2) return number.to_bytes(len(bits) // 8, byteorder='big')
def check_rows(board): """ Returns False if there are two identical numbers in row and True otherwise >>> check_rows(["**** ****", "***1 ****", "** 3****", "* 4 1****",\ " 9 5 ", " 6 83 *", "3 2 **", " 8 2***", " 2 ****"]) True >>> check_rows(["**** ****", "***1 ****", "** 3****", "* ...
def validate_header(fields, required): """ Validate the header line in a source file. Parameters ---------- fields : list of str Each element is the name of a field from a header line required : set of str Each element is the name of a required field Returns --...
def diff( source1, source2, start=None, end=None ): """Perform a diff between two equal-sized binary strings and return a list of (offset, size) tuples denoting the differences. source1 The first byte string source. source2 The second byte string source. start Start offset...
def _is_support_vcvars_ver(vc_full_version): """-vcvars_ver option is supported from version 14.11.25503 (VS 2017 version 15.3).""" version = [int(i) for i in vc_full_version.split(".")] min_version = [14, 11, 25503] return version >= min_version
def dict_to_dot_str(d, parent_key='digraph D', indent='', base_indent=''): """Dict will be converted into DOT like the followings: 1) Value string will not be double-quotted in DOT. - make sure to escape double-quotes in a string with special characters (e.g. whitespace, # and ;) ...
def check_adjacent(a): """ Check if three empty slots are adjacent :param a: array :return: True or False """ counter = 0 for i in a: if i: counter += 1 if counter == 3: return True else: counter = 0 # Do two loops as t...
def select_from_view(view, targets): """ Identify the fragments of the view that contain at least one of the targets Args: view (dict): if present, identifies the fragments that contain the relevant units targets (list): list of the fragments to search in the view Return...
def minimum_bounding_box(geojson): """Gets the minimum bounding box for a geojson polygon. Args: geojson (dict): A geojson dictionary. Returns: tuple: Returns a tuple containing the minimum bounding box in the format of (lower_left(lat, lon), upper_right(lat, lon)), such as ((13, -130), (3...
def linear_unmap(val, lo, hi): """Linear unmapping.""" return (val - lo) / (hi - lo)
def get_from_module(module_params, module_name, identifier): """Gets a class/instance of a module member specified by the identifier. Args: module_params: dict, contains identifiers module_name: str, containing the name of the module identifier: str, specifying the module member Re...
def convertcl(text: str) -> str: """ CL tag format conversion. Convert cl tags that appear only before chapter one to the form that appears after each chapter marker. """ lines = text.split("\n") # count number of cl tags in text clcount = len([_ for _ in lines if _.startswith(r"\cl "...
def setFlag(flagbyte, pos, status): """ Sets the bit at 'pos' to 'status', and returns the modified flagbyte. """ if status: return flagbyte | 2 ** pos else: return flagbyte & ~2 ** pos
def build_windows_time(high_word, low_word): """ Generate Windows time value from high and low date times. :param high_word: high word portion of the Windows datetime :param low_word: low word portion of the Windows datetime :return: time in 100ns since 1601/01/01 00:00:00 UTC """ retur...
def ipv4_prefix_to_mask(prefix): """ ipv4 cidr prefix to net mask :param prefix: cidr prefix , rang in (0, 32) :type prefix: int :return: dot separated ipv4 net mask code, eg: 255.255.255.0 :rtype: str """ if prefix > 32 or prefix < 0: raise ValueError("invalid cidr prefix for i...
def create_query(section): """ Creates a search query based on the section of the config file. """ query = {} if 'ports' in section: query['ports'] = [section['ports']] if 'up' in section: query['up'] = bool(section['up']) if 'search' in section: query['search'] ...
def romaine_v2(string): """ (str) -> (bool or int) Converts roman numerals to arabic numerals without using string methods. Restrictions: String must strictly consist of any one of M, D, C, X, V, and I. Anything else (such as trailing whitespaces) will return False. """ total = 0 for y...
def _mask(buf, key): """ Mask or unmask a buffer of bytes with a masking key. @type buf: C{str} @param buf: A buffer of bytes. @type key: C{str} @param key: The masking key. Must be exactly four bytes. @rtype: C{str} @return: A masked buffer of bytes. """ key = [ord(i) for i i...
def _try_import(module_name, insistance): """Maybe import a module and maybe raise an error if the import fails. """ if insistance in [False, 'no', 'false', 'False']: return None module = None try: module = __import__(module_name) except ImportError as e: if insistance in...
def split_commas(ctx, param, value): """ Convert from a comma-separated list to a true list. """ # ctx, param, value is the required calling signature for a Click callback try: values = value.split(',') except AttributeError: # values is None values = None return va...
def isCMSSWSupported(thisCMSSW, supportedCMSSW): """ _isCMSSWSupported_ Function used to validate whether the CMSSW release to be used supports a feature that is not available in all releases. :param thisCMSSW: release to be used in this job :param allowedCMSSW: first (lowest) release that start...
def str2bool(v): """ Convert string to boolean """ return v.lower() in ('yes', 'true', 't', 'y', '1', 'on')
def _etextno_to_uri_subdirectory(etextno): """Returns the subdirectory that an etextno will be found in a gutenberg mirror. Generally, one finds the subdirectory by separating out each digit of the etext number, and uses it for a directory. The exception here is for etext numbers less than 10, which are...
def isAscii(name, listExcluded=None): """ @param name: string to check @param listExcluded: list of char or string excluded. @return: True of False whether name is pure ascii or not """ isascii = None try: name.encode("ASCII") except UnicodeDecodeError: isascii = False ...
def add_trailing_slash(directory_path): """ Add trailing slash if one is not already present. Argument: directory_path -- path to which trailing slash should be confirmed. """ # Add trailing slash. if directory_path[-1] != '/': directory_path = str().join([directory_path, '/']) ...
def _check_trig_shift_by_type(trig_shift_by_type): """Check the trig_shift_by_type parameter. trig_shift_by_type is used to offset event numbers depending of the type of marker (eg. Response, Stimulus). """ if trig_shift_by_type is None: trig_shift_by_type = dict() elif not isinstance(t...
def is_interleaved(c1, c2, chars): """ Return True if the character index lists given by characters c1 qnd c2 are interleaved, False otherwise. """ answer = True # Reference the character index lists and determine which one should go # first, i.e. which list has the smaller first element a...