content
stringlengths
42
6.51k
def format_time( seconds ): """ Formats the time, in seconds, to a nice format. Unfortunately, the :py:class:`datetime <datetime.datetime>` class is too unwieldy for this type of formatting. This code is copied from :py:meth:`deluge's format_time <deluge.ui.console.utils.format_utils.format_time>`. :param ...
def clean_states(state): """Function to remove 'State' keyword in some states names.""" if state is None: return state else: if 'state' or 'State' in state: return state.split()[0].capitalize() else: return None
def generate_timespec_buf(step = "1 ns", unit = "1 ps"): """ Generate a timespec buffer given the input, if left empty fills in the default of 1ns/1ps Args: step (string): Timespec step unit (string): Unit of time step Returns: (string): buffer with the given timespec ...
def encode_sint24(val): """ Format a value as a signed 24 bit integer Specs: * **sint24 len**: 3 bytes * **Format string**: 'K' """ return val.to_bytes(3, 'little', signed=True)
def crit_dim_var(var): """Check if nested dict or not Arguments --------- var : dict Dictionary to test wheter single or multidimensional parameter Returns ------- single_dimension : bool True: Single dimension, False: Multidimensional parameter """ single_dimension...
def generate_ashp_gshp_split(gshp_fraction): """Assing split for each fueltype of heat pump technologies, i.e. the share of GSHP of all heat pumps Arguments ---------- gshp_fraction : float Fraction of GSHP (GSHP + ASHP = 100%) Returns -------- installed_heat_pump_by : dict ...
def timePoint_hierarchy(nb_TP): """ Convert the number of time points in a list with all the time points. This list can be used by many others functions. The time points columns in the input dataset should be write like : "tp* s" * is the time point number (the first time point must be 1). @type nb_...
def get_leading_prefixes(sequences): """ Return a set of proper prefixes for given sequence of strings. :arg iterable sequences :rtype: set Given an iterable of strings, all textparts leading up to the final string is returned as a unique set. This function supports the :meth:`~.Terminal....
def has_no_e(word): """Returns True if word contains no e letter >>> has_no_e("hello") False >>> has_no_e("myopia") True """ word.split() if "e" in word: return False else: return True
def adcm_is_upgradable(request) -> bool: """Set flag that controls either ADCM will be upgradable or not""" if hasattr(request, "param") and request.param: return True return False
def _convert_opts(opts): """ Convert list with command options to single string value with 'space' delimeter :param opts: list with space-delimeted values :return: string with space-delimeted values """ return ' '.join(opts)
def _is_int(_obj): """ Checks if an object is an int with a try-except loop :param _obj: :return: """ try: int(_obj) except TypeError or ValueError as e: return False else: return True
def source_virtualenv(virtualenv_dir=""): """ This Function takes in... :param virtualenv_dir: :return: """ if virtualenv_dir is None: return "" assert virtualenv_dir != "" return "source {0}".format(virtualenv_dir)
def rowval(num: str): """ chess rows are 1-indexed, subtract one to operate on 'board' """ return int(num) - 1
def is_ascii(s): """https://stackoverflow.com/questions/196345/how-to-check-if-a-string-in-python-is-in-ascii""" return all(ord(c) < 128 for c in s)
def geojsonToFeatureCollection(geojson: dict) -> dict: """Take a GeoJson and wrap it in a FeatureCollection.""" if geojson["type"] != "FeatureCollection": collection = { "type": "FeatureCollection", "features": [{"type": "feature", "geometry": geojson}], } return ...
def transform_row_into_list(row): """This function transform a row into a named tuple""" result = row.strip('\n').split(',') return result
def has_uk_establishment_number_prefix(value): """Checks if a UK establishment number has the correct (BR) prefix.""" return not value or value.startswith('BR')
def remove_non_ascii(input_string): """remove non-ascii: http://stackoverflow.com/a/1342373""" no_ascii = "".join(i for i in input_string if ord(i) < 128) return no_ascii
def get_page_by_uid(uid, pages): """ Get a page by its UID Args: uid (str): The page UID to search for pages (list of dict): list of pages Returns: dict: The matching page if any """ page_info = [page for page in pages if page["uid"] == uid] if page_info: r...
def compare_metrics(comparison, best): """ compare metrics """ if best is None: return True threshold = 1e-4 rel_epsilon = threshold + 1. return comparison > best * rel_epsilon
def delete_gnupg_key(key_id): """ :status 501: NotImplemented """ return {'message': 'GnuPG key deleted'}, 501
def filter_empty_irrep(coll): """ A matrix is returned for every irrep, even if the irrep is not present for the molecule; these must be filtered out to avoid problems with NumPy arrays that have a zero dimension. """ return tuple(m for m in coll if all(m.shape))
def cos2tan(cos: float) -> float: """returns Tan[ArcCos[x]] assuming 0 < x < pi.""" return ((1 - cos) * (1 + cos)) ** 0.5 / cos
def split_str_to_list(input_str, split_char=" "): """Split a string into a list of elements. Args: input_str (str): The string to split split_char (str, optional): The character to split the string by. Defaults to " " (a single whitespace). Returns: List[str]: The strin...
def remove_kwargs(remove_list, **kwargs): """Remove items from kwargs dict that may cause conflict with successive function calls""" # return {k: v for k, v in kwargs.items() if k not in remove_list} # This iterates the entire dict for item in remove_list: # This just iterates the remove_list _ = ...
def num_round(x) -> str: """comma separated with only the largest 2 units as non-zero""" if x > 100: x = round(x, 2 - len(str(int(x)))) elif x < 100: x = round(x, 3 - len(str(int(x)))) elif abs(x) > 10: x = round(x, -1) else: x = x x = int(round(x)) return f'{...
def pick_pairs(amount): """Picks non-overlapping team pairs of 2 rounds.""" return [(i,i+1,2) for i in range(0, amount, 2)]
def space_underscores(s): """ replace underscores with spaces separate function to keep f strings from getting too long :param s: a string :return: s with underscores replaced with spaces """ return s.replace("_", " ")
def _round_coord(coord): """ Round a number to the nearest arc-minute """ dm = 1.0 / 60 mm = coord / dm imm = int(mm + 0.5) return imm * dm
def __numeric(s): """ guarantee a number (return 0 otherwise) rely on float() because the builtin isnumeric() will not handle cases like '-.5' """ try: return float(s) except ValueError: return 0
def _get_training_data(vrn_files): """Retrieve training data, returning an empty set of information if not available. """ out = {"SNP": [], "INDEL": []} # SNPs for name, train_info in [("train_hapmap", "known=false,training=true,truth=true,prior=15.0"), ("train_omni", "k...
def get_id_from_repo(repo_dir): """Returns the Google Drive File/Folder ID for specified files.""" return repo_dir.split('/')[-1]
def verify_line(line: str, no: int, conds: set): """ Verify if the given line is compliant to the training data format. :param line: Line string. :param no: Line number. :param conds: Available weather condition strings. :return: Faulty line number, otherwise None. """ if conds is None: ...
def multiplex(Fs, signal1, signal2): """ This function multiplexes data from two input signals into one single \ list, where the first value is sampling frequency and the following \ values contain the multiplexed values from each signal :param int Fs: sampling frequency (in Hz) :param list sig...
def ode45_step(f, x, t, dt, *args): """ One step of 4th Order Runge-Kutta method """ k1 = dt * f(t, x, *args) k2 = dt * f(t + 0.5*dt, x + 0.5*k1, *args) k3 = dt * f(t + 0.5*dt, x + 0.5*k2, *args) k4 = dt * f(t + dt, x + k3, *args) return x + 1/6. * (k1 + 2*k2 + 2*k3 + k4)
def remove_tags(value): """ Returns the text with all tags removed This can fail if give invalid input. This is only intended to be used on safe HTML markup. It should not be used to clean unsafe input data. For example, this will fail. Example:: >> remove_tags('<<> <test></test>') ...
def _calc_time_threshold(seg_mean: float, seg_std: float) -> float: """ Auxiliary function for calculating the threshold based on the mean and standard deviation of the time transitions between adjacent places on discrete MoveDataFrame. Parameters ---------- seg_mean : float The t...
def isopt(c): """Function that checks wheter the passed character is an operator.""" if c == "+" or c == "-" or c == "*" or c == "/": return True else: return False
def move_item_to_list(list_of_lists, target_list_idx): """Takes a list of lists and moves one item to the list specified from the next list. This function works in-place upon the list of lists. Args: list_of_lists (list): A list of lists. target_list_idx (int): Index of the list...
def key_prefix_replace(d, prefix, new_prefix=""): """ replaces the list of prefix in keys of a flattened dict :param d: the flattened dict :param prefix: a list of prefixes that are replaced with a new prefix. Typically this will be "" :type prefix: list of str :param new_prefix: The new prefix...
def get_parent_id(an_id: str) -> str: """ given an id - get the parent id. for most items - it will be the id before the last / for .json or .xml - it will be the id up to the .json/.xml """ parent_id = an_id.rsplit("/", 1)[0] if an_id.find(".xml") > 0: parent_id = an_id[: an_id.find...
def is_writable_file(obj): """Check if obj is a file""" try: obj.write("") except(AttributeError, OSError, IOError): return False else: return True
def getNrOfDictElements(thisdict): """ Will get the total number of entries in a given dictionary Argument: the source dictionary Output : an integer """ total = 0 for dicttype in thisdict: for dictval in thisdict[dicttype]: total += 1 return total
def S_convolute_values(_data_list, _transformer): """ Returns new data samples where values are transformed by transformer values. """ c_data = [] ds = len(_data_list) ts = len(_transformer) if ds != ts: return [] for i in range(ds): c_data.append(_data_list[i] + _tran...
def validate_links(link_dict, node_name): """ Validates the link structure to ensure same number of subgroups are added """ len_links = {} flag = True for key, val in link_dict.items(): len_links[key]= [len(v) for v in val] ref_link = len_links['name'] link_len = len(ref_...
def wrap_declarations(text, length=78): """ A simple-minded text wrapper for C function declarations. It views a declaration line as looking like this: xxxxxxxx(xxxxxxxxx,xxxxxxxxx) If called with length=30, it would wrap that line into xxxxxxxx(xxxxxxxxx, xxxxxxxxx) ...
def _to_multipart(name, value, multipart=False): """ Update the given :class:`~parameters` with a new inputs using the appropriate form based on `multipart`. """ if multipart: return ("tmp_file_%s" % name, value) else: return value
def _juniper_vrf_default_mapping(vrf_name: str) -> str: """ This function will convert Juniper global/default/master routing instance => master => default :param vrf_name: :return str: "default" if vrf_name = "master" else vrf_name """ if vrf_name == "master": return "default" ...
def create_checksum(name, inputs): """ Generate a checksum name for a given combination of task name and inputs. Parameters ---------- name : :obj:`str` Task name. inputs : :obj:`str` String of inputs. """ return "_".join((name, inputs))
def remove_item_tuple(data, index): """ Remove an item from the given tuple. Args: data (tuple): The tuple with item to remove. index (int): The index of item to remove from tuple. Returns: tuple: A new tuple with the item at index removed. """ list_data = list(data) ...
def tuple_to_string(the_tuple): """Converts tuple into one string.""" list_of_tuple_elements = [str(i) + ", " for i in the_tuple] the_string = "".join(list_of_tuple_elements) return the_string
def default_kmer(kmer, assembler): """Calculate default kmer argument.""" if assembler == 'velvet' and kmer > 31: kmer = 31 return kmer
def Returns1(target_bitrate, result): """Score function that returns a constant value.""" # pylint: disable=W0613 return 1.0
def union_of(lhs, rhs): """ Computes the union of two posting lists. """ i = 0 j = 0 answer = [] while (i < len(lhs) or j < len(rhs)): if (j == len(rhs) or (i < len(lhs) and lhs[i] < rhs[j])): answer.append(lhs[i]) i += 1 elif (i == len(lh...
def _query_set(query, results): """Search into result set for query. :param query: Query to search for :param results: A set with all possible items :type query: str :type resulsts: set :returns: Matched items :rtype: set """ return {result for result in results if result.startswith...
def find(collection, condition): """Return the first element in collection that satisfies condition""" return next((element for element in collection if condition(element)), None)
def gtid_enabled(slaves): """Function: gtid_enabled Description: Check to see that all slaves are GTID enabled. Arguments: (input) slaves -> Slave instance array. (output) is_enabled -> True|False - If all slaves are GTID enabled. """ slaves = list(slaves) is_enabled = Tru...
def triada(valores_acumulados): """ Regresa 1 si encuentra una triada, de lo contrario regresa 0 valores_acumulados es un arreglo con valores acumulados de la mano """ for val in valores_acumulados: if val == 3: return 1 return 0
def represent_2d_char_list(l): """Output a 2d character list as aligned multiline string. Can be used for printing.""" row_num = 0 repres = "" for rowlist in l: if row_num > 0: repres += "\n" for c in rowlist: repres += str(c) row_num += 1 return repres
def which(program): """ Function for checking if an executable exists on a system. Thanks: http://stackoverflow.com/questions/377017/test-if-executable-exists-in-python """ import os def is_exe(fpath): return os.path.isfile(fpath) and os.access(fpath, os.X_OK) fpath, fname = os...
def get_query_list_from_file(infp): """Get query list from file. """ query_list = [] with open(infp) as infh: for i in infh: if not i.startswith('#') and not i.startswith('\n'): query_list.append(i.strip()) return query_list
def Split(ar,size): """ split sequence into blocks of given size """ return [ar[i:i+size] for i in range(0, len(ar), size)]
def _normalize_input_name(input_name): """Remove :i suffix from input tensor names.""" return input_name.split(":")[0]
def _get_policy_actions(stat): """Get policy actions from stat information.""" def listit(value): return value if isinstance(value, list) else [value] actions = [listit(s.get("Action")) for s in stat if s.get("Action")] actions = list(set( item.replace("s3:", "") for sublist in actions ...
def dict2str(d, sep="-", sort_names=True): """ Concatenate key-value pairs to string. :param d: :param sep: string, separating the names (dict keys) (default = "-") :param sort_names: binary, indicating whether the names should be sorted alphabetically (default = ...
def dupe(annotations, rename_list, new_names): """annotations is a list of dictionaries, if entry["name"] is in rename_list copy over an entry for every name in new_names and rename the entry["name"] to the new name""" added = [] new_list = [] rename_count = 0 for entry in annotations: # if ...
def mean(values): """ returns mean value of a list of numbers >>> mean([1, 2, 3, 4, 1, 2, 3, 4]) 2.5 >>> round(mean([1, 2, 3, 4, 1, 2, 3, 4.1, 1000000]), 4) 111113.3444 """ mean = sum(values) / float(len(values)) return mean
def calc_errors_from_vd(errors: dict, data_on_validate: dict = {}) -> list: """ calc errors from validate-data (errors) by UnmarshalResult """ result_errors = [] # errors = {field_name: [errors-msgs]} for field_name in errors: if isinstance(errors[field_name], list): for msg in error...
def find_projects(company_name, project_list): """returns list of projects associated with company_name :param company_name: name of company to return projects for :type company_name: str :param project_list: list of projects as dictionaries :type project_list: list :return: list """ re...
def escape_html(val): """ Applies appropriate escaping to the supplied value to allow it to be included in HTML element text. """ # Also consider: # http://stackoverflow.com/questions/1061697/whats-the-easiest-way-to-escape-html-in-python return val.replace('<','&lt;').replace('>','&gt;')
def unicode_is_ascii(u_string): """Determine if unicode string only contains ASCII characters. :param str u_string: unicode string to check. Must be unicode and not Python 2 `str`. :rtype: bool """ assert isinstance(u_string, str) try: u_string.encode('ascii') return Tru...
def isDefined(varname): """Return true if the variable with the given name is defined (bound) either locally or globally.""" # This seems like it ought to work, but it doesn't always #return varname in locals().keys() or varname in globals().keys() # So try eval'ing the variable name and look for ...
def can_make_inline_uri(src_file: str) -> bool: """Returns whether or not the file can be transformed to an inline uri Args: src_file (str): The path to the source file Returns: bool: Returns True if the file can be transformed """ file_format = src_file.rstrip().split(".")[-1].low...
def is_ascii(word): """True if a word is only ascii chars """ def onlyascii(char): if ord(char) > 127: return '' else: return char for c in word: if not onlyascii(c): return False return True
def is_leap(year): """ return True for leap year, False for non-leap year """ return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
def noblanklines(s): """Remove blank lines from output. This is used to increase readability when some expected output would otherweise contain disturbing `<BLANKLINE>` which are not relevant to the test itself. """ return '\n'.join([ln for ln in s.splitlines() if ln.strip()])
def is_indented(line): """ Checks if line is indented :param line: str :return: bool """ return line.startswith(" ") and not line[4].startswith(" ")
def _normalization(norm, forward): """Returns the pypocketfft normalization mode from the norm argument""" if norm is None: return 0 if forward else 2 if norm == 'ortho': return 1 raise ValueError( "Invalid norm value {}, should be None or \"ortho\".".format(norm))
def _merge_params(current, new): """Merge parameters dictionary""" if not new: return current if not current: return new current = current.copy() current.update(new) return current
def change_list_to_dict(list_to_convert, key): """ Changes a list into a dictionary using the 'key' parameter as the dictionary keyself. Assumes the key is in each dictionary. Assumes the key is unique. """ dict_to_export = {} for each_obj_in_list in list_to_convert: # Check if ...
def remove_suffix_ness(word): """Remove the suffix from the word while keeping spelling in mind. :param word: str - of word to remove suffix from. :return: str - of word with suffix removed & spelling adjusted. For example: "heaviness" becomes "heavy", but "sadness" becomes "sad". """ word = ...
def dinic_dfs(capacity, flow, level, idx, sink, work, current_flow = 1 << 63): """ DFS function for Dinic algorithm. Finds new flow using edges that is not full. """ if idx == sink: return current_flow vertices = len(capacity) while work[idx] < vertices: nxt = work[idx] ...
def dimension(value, arg): """ Dimension integers If value, append arg, otherwise output nothing """ if value: return str(value) + " " + arg return ""
def findMax(val1, val2): """Returns tuple containing min, max of two values Args: val1: first integer or float. val2: second integer or float. Returns: tuple - containing: * lower value * higher value * False if not same or True if t...
def remove_line_break(src_str): """Replaces link breaks (NL, CR) into whitespaces. Args: src_str string: A source string. Returns: A modified string. """ dst_str = src_str return dst_str.replace('\n', ' ').replace('\r', '')
def _transpose2Dlist(mat): """transpose a matrix that is constructed as a list of lists in pure Python The inner lists represents rows. Parameters ---------- mat : list of lists (2-d list) the 2D list represented as | [[a_00, a_01, ..., a_0n], | [a_10, a_11, ..., a_1n]...
def freeze(obj): """Freeze a state (dict), for memoizing.""" if isinstance(obj, dict): return frozenset({k: freeze(v) for k, v in obj.items()}.items()) if isinstance(obj, list): return tuple([freeze(v) for v in obj]) return obj
def format_location(host_ip, folder_name, image_id, datacenter_path, datastore_name): """ Helper method that returns a VMware Datastore store URI given the component pieces. """ scheme = 'vsphere' return ("%s://%s/folder%s/%s?dsName=%s&dcPath=%s" % (scheme, host_i...
def codeblock(text: str, *, lang: str = '') -> str: """ Formats a codeblock. Parameters ---------- text The text to be inside of the codeblock. lang The language to use. Returns ------- str The formatted message. """ return f'```{lang}\n{text}\n```'
def total_calories(portions, calories): """ >>> total_calories(3, 300) 'For 3 portions your meal has 900 calories.' >>> total_calories(2, 100.75) 'For 2 portions your meal has 201.5 calories.' >>> total_calories(7, 250.35) 'For 7 portions your meal has 1752.45 calories.' >>> tota...
def len_mark(board, mark): """Function count marks of the player or AI on the board and return integer.""" counter = 0 for line in board: for cell in line: if cell == mark: counter += 1 return counter
def elimina_enter(lines): """ Elimina CR/LF do final de cada linha. Todas as linhas da lista deve possuir o caracter CR/LF """ newLines = [] for line in lines: newLines.append(line[0:len(line)-1]) return newLines
def expression_matter(a, b, c): """ Find the maximum value possible. :param a: an integer value. :param b: an integer value. :param c: an integer value. :return: the largest number obtained after inserting the following operators and brackets: +, *, (). """ return max(a * (b + c), (a + b...
def compare_two(objects, key1, key2): """Compares only a specific pair of objects for all the rankers. It is assumed that key1 is lower ranked than key2 in comparison. Hence, a flip is ordering key2 above key1. """ agree = 0 disagree = 0 for ranker in range(len(objects[key1])): r1 ...
def gcd(p, q): """ euclidean algorithm to find gcd of p and q """ while q: p, q = q, p % q return p
def get_etherscan_link(network, address): """Construct etherscan link""" if network == "mainnet": return "https://etherscan.io/address/" + address elif network == "ropsten": return "https://ropsten.etherscan.io/address/" + address elif network == "kovan": return "https://kovan.e...
def _ok(output=None): """Connection mock success""" if output is None: return 'ok', [] return 'ok', output
def image_proc_resize( image, width, height ): """ Resize the image. """ output_image = [] return output_image
def count_whitespace_prefix(string): """return the number of spaces at the beginning of the given string""" for i, ch in enumerate(string): if ch != ' ': return i return len(string)