content
stringlengths
42
6.51k
def bytesto(bytes, to, bsize=1024): """convert bytes to megabytes, etc. sample code: print('mb= ' + str(bytesto(314575262000000, 'm'))) sample output: mb= 300002347.946 """ a = {'k' : 1, 'm': 2, 'g' : 3, 't' : 4, 'p' : 5, 'e' : 6 } r = float(bytes) for i in range(...
def _checkplatform(platform): """ Check if the platform is valid. :param platform: The platform to check. """ if platform == 'origin' or platform == 'psn' or platform == 'xbl': return True else: return False
def travel_object(obj, key_functions=[], val_functions=[]): """Recursively apply functions to the keys and values of a dictionary Parameters ---------- obj : dict/list List or dict to recurse through. key_functions : list Functions to apply to the keys in 'obj'. val_functions : ...
def info_header(label): """Make a nice header string.""" return "--{0:-<60s}".format(" "+label+" ")
def remove_empty_items(dict_obj: dict): """Remove null values from a dict.""" return {k: v for k, v in dict_obj.items() if v is not None}
def is_not_null(value): """ test for None and empty string :param value: :return: True if value is not null/none or empty string """ return value is not None and len(str(value)) > 0
def _aggregate_nomad_jobs(aggregated_jobs): """Aggregates the job counts. This is accomplished by using the stats that each parameterized job has about its children jobs. `jobs` should be a response from the Nomad API's jobs endpoint. """ nomad_running_jobs = {} nomad_pending_jobs = {} ...
def get_distances(s1, s2): """Returns the distances from every atom to every other in the given set""" distances = [] for a in s1: for b in s2: x, y, p = a.x - b.x, a.y - b.y, a.neg != b.neg distances.append(((x, y, p), (a, b))) return distances
def _merge_two_dicts(x, y): """Given two dicts, merge them into a new dict as a shallow copy.""" z = x.copy() z.update(y) return z
def cast_tweet_id(tweet_id: str) -> int: """Cast a single Tweet ID to int. They may be prefixed with 'ID:' so try to remove this. """ if tweet_id.lower().startswith('id:'): tweet_id = tweet_id.lower()[3:] return int(tweet_id)
def attrgetter(x, attr): """Attrgetter as a function for verb This is helpful when we want to access to an accessor (ie. CategoricalAccessor) from a SeriesGroupBy object """ return getattr(x, attr)
def startOfInterval(time_ts, interval): """Find the start time of an interval. This algorithm assumes unit epoch time is divided up into intervals of 'interval' length. Given a timestamp, it figures out which interval it lies in, returning the start time. time_ts: A timestamp. The start of...
def humanize_time(secs): """ Convert seconds to hh:mm:ss format. """ secs = int(secs) mins, secs = divmod(secs, 60) hours, mins = divmod(mins, 60) return '{h:02d}:{m:02d}:{s:02d} (hh:mm:ss)'.format(h=hours, m=mins, s=secs)
def trapezoid_area(base_minor, base_major, height): """Returns the area of a trapezoid""" # You have to code here # REMEMBER: Tests first!!! return ((base_minor + base_major )* height)/2
def bubble_sort(arr): """Refresher implementation of buble-sort - in-place & stable. :param arr: List to be sorted. :return: Sorted list. """ for i in range(len(arr)): for j in range(len(arr) - 1): # check if elements are in relative out-of-order if arr[j] > arr[...
def split_by_group(a, start, end): """Split string a into non-group and group sections, where a group is defined as a set of characters from a start character to a corresponding end character.""" res, ind, n = [], 0, 0 new = True for c in a: if new: res.append("") new = False i = start.find(c) if n ==...
def convtransp_output_shape(h_w,kernel_size=1,stride=1,pad=0,dilation=1): """ Utility function for computing output of transposed convolutions takes a tuple of (h,w) and returns a tuple of (h,w) """ if type(h_w) is not tuple: h_w=(h_w,h_w) if type(kernel_size) is not tuple: kern...
def make_floats(params): """ pass list of params, return floats of those params (for caching) """ if params is None: return None if hasattr(params, "__len__"): return [float(p) for p in params] else: return float(params)
def convert_tags(tags): """Will convert tags so the article can be uploaded to dev.to. This involves removing the `-` and making the tag lowercase. Args: tags (list): The list of tags to convert. Returns: list: The list of converted tags """ new_tags = [] for tag in tags: ...
def parse_home(d): """ Used to parse name of home team. """ return str(d.get("tTNaam", ""))
def create_time_filter(create_time, comparator): """Return a valid createTime filter for operations.list().""" return 'createTime {} "{}"'.format(comparator, create_time)
def parse_concepts(api_concepts): """Parse the API concepts data.""" return {concept['name']: round(100.0*concept['value'], 2) for concept in api_concepts}
def rgb(red, green, blue): """Helper function that returns rgb strings to be used by color-specification headers. Arguments: red (int): Red color value. green (int): Green color value. blue (int): Blue color value. Returns: A string representing the specified color. ...
def generate_layer_name(layer_type, index): """ Generates a unique layer name """ # Generating a unique name for the layer return f"{layer_type.lower()}_layer_{index+1}"
def compoundedInterest(fv, p): """Compounded interest Returns: Interest value Input values: fv : Future value p : Principal """ i = fv - p return i
def gather_settings(pre='DJANGO_') -> dict: """ Collect dict of settings from env variables. """ import os return { k[len(pre):]: v for (k, v) in os.environ.items() if k.startswith(pre) }
def catch_start_end(s): """ input string is like: "start_char=2|end_char=8" """ parts = s.split("|") assert len(parts) == 2 start_char = "start_char=" end_char = "end_char=" pre, post = parts[0], parts[1] assert pre.startswith(start_char) assert post.startswith(end_char) star...
def sizeof_fmt(num, suffix='B'): """ Given `num` bytes, return human readable size. Taken from https://stackoverflow.com/a/1094933 """ for unit in ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi']: if abs(num) < 1024.0: return "%3.1f%s%s" % (num, unit, suffix) num /= 1024.0 ...
def clean_up_spacing(sentence: str) -> str: """ :param sentence: str a sentence to clean of leading and trailing space characters. :return: str a sentence that has been cleaned of leading and trailing space characters. """ return sentence.strip()
def format_ruckus_value(value, force_str=False): """Format a string value into None, int, or bool if possible.""" value = value.strip() if not value: return None if not force_str: if value.isnumeric(): return int(value) if value in ["true", "Enabled", "Yes"]: ...
def nest_list_to_tuple(nest): """Convert the lists in a nest to tuples. Some tf-agents function (e.g. ReplayBuffer) cannot accept nest containing list. So we need some utitity to convert back and forth. Args: nest (a nest): a nest structure Returns: nest with the same content as th...
def _decimal_year_to_mjd2000_simple(decimal_year): """ Covert decimal year to Modified Julian Date 2000. """ return (decimal_year - 2000.0) * 365.25
def the_last_50_entries(list_of_entries): """Simply returns the last 50 entries.""" return list_of_entries[-50:]
def component_col_regex(component_count): """ Match things like 'foo_bar_baz_corge' """ return '_'.join(([r'[^_\s]+'] * component_count))
def get_preferred_media_item_link(item): """ Guess the most useful link for a given piece of embedded media. :param item: a single media object, as decoded JSON :return: the best-guess link to output for optimum IRC user utility :rtype: str Twitter puts just a thumbnail for the media link if i...
def int2str(num,l): """ Given an integer num and desired length l, returns the str(num) with appended leading zeroes to match the size l. """ if len(str(num))<l: return (l-len(str(num)))*'0'+str(num) else: return str(num)
def _path_parts(path): """Takes a path and returns a list of its parts with all "." elements removed. The main use case of this function is if one of the inputs to _relative() is a relative path, such as "./foo". Args: path_parts: A list containing parts of a path. Returns: Returns a ...
def difference(dataset, interval=1): """ Differencing time series according to difference_order/interval dataset: type:list, Desc: list contaning timeseries values interval: type:integers Desc: Differencing order """ def do_diff(dataset): diff = list() ...
def create_batch_groups(test_groups, batch_size): """Return batch groups list of test_groups.""" batch_groups = [] for test_group_name in test_groups: test_group = test_groups[test_group_name] while test_group: batch_groups.append(test_group[:batch_size]) test_group =...
def escape_parameters(formula, escape_char='_'): """ Escapes the parameters of a category formula. Parameters ---------- formula : str Category formula. escape_char : str, optional Character string to escape parameters with (prepended and appended to variables). Note ...
def parse_version(v): """ Take a string version and conver it to a tuple (for easier comparison), e.g.: "1.2.3" --> (1, 2, 3) "1.2" --> (1, 2, 0) "1" --> (1, 0, 0) """ parts = v.split(".") # Pad the list to make sure there is three elements so that we get major, minor, point...
def inverseDict(d): """ Returns a dictionay indexed by values {value_k:key_k} Parameters: ----------- d : dictionary """ dt={} for k,v in list(d.items()): if type(v) in (list,tuple): for i in v: dt[i]=k else: dt[v]=k return dt
def ircLower(string): """ Lowercases a string according to RFC lowercasing standards. """ return string.lower().replace("[", "{").replace("]", "}").replace("\\", "|")
def g1(a, b): """Returns False eactly when a and b are both True.""" if a == True and b == True: return False else: return True
def symbol_match(sym1, sym2): """ Check whether two symbols match. If one argument is None they always match. :param sym1: symbol 1 :param sym2: symbol 2 :return: whether both symbol (sequences) match. """ if len(sym1) != len(sym2): return False for e1, e2 in zip(sym1, sym2): ...
def insertion_sort(x): """ Sorts an array x in non-decreasing order using the insertion sort algorithm. @type x: array @param x: the array to sort @rtype: array @return: the sorted array """ if len(x) <= 1: return x for i, v in enumerate(x): j = i wh...
def extra_domain_entries(domfilter, extrafilters): """Return extra queryset filters.""" if domfilter is not None and domfilter and domfilter != 'relaydomain': return {} if "srvfilter" in extrafilters and extrafilters["srvfilter"]: return {"relaydomain__service__name": extrafilters["srvfilter...
def stripcomments(line): """From a GROMACS topology formatted line, return (line, comments) with whitespace and comments stripped. Comments are given with ;. Parameters ---------- line : str GROMACS line to be stripped Returns ------- line : str GROMACS line with comments a...
def flatten_deps(deps): """Converts deps.lock dict into a list of go packages specified there.""" out = [] for p in deps['imports']: # Each 'p' here have a form similar to: # # - name: golang.org/x/net # version: 31df19d69da8728e9220def59b80ee577c3e48bf # repo: https://go.googlesource.com/...
def format_bytes(bytes, unit, SI=False): """ Converts bytes to common units such as kb, kib, KB, mb, mib, MB Parameters --------- bytes: int Number of bytes to be converted unit: str Desired unit of measure for output SI: bool True -> Use SI standard e.g. KB = 100...
def reduce_string(s): """ >>> assert(reduce_string(None) == 'Empty String') >>> assert(reduce_string('') == 'Empty String') >>> assert(reduce_string('abc') == 'abc') >>> assert(reduce_string('aabbc') == 'c') >>> assert(reduce_string('abcc') == 'ab') >>> assert(reduce_string('aabbcc') == 'Emp...
def all_tag_filter(tags): """Return a filter of the element by all the tags for a json post advance search. :param List of :class:`str` tags: Desired filtering tags :returns: json structure to call the asking tasks. """ if not isinstance(tags, list): tags = [tags] if len(tags) == 1: ...
def lengthOfLastWord(s): """ :type s: str :rtype: int """ index_list=[i for i in range(len(s)) if s[i] != " "] if not index_list: return 0 for i in range(len(index_list)-1,-1,-1): if index_list[i]-1 != index_list[i-1]: return index_list[-1]-index_list[i]+1
def compare_para_dict(para_dict_old, para_dict_new): """Compare two parameter dictionaries. Parameters ---------- para_dict_old : dictionary old parameter dictionary para_dict_new : dictionary new parameter dictionary Returns ------- status : bool True if same, ...
def pea_reject_image(img): """ Check if PEA would reject image (too narrow, too peaky, etc) """ # To be implemented return False
def get_color_dist(c1, c2): """Calculates the "distance" between two colors, where the distance is another color whose components are the absolute values of the difference between each component of the input colors. """ return tuple(abs(v1 - v2) for v1, v2 in zip(c1, c2))
def flatten_json(nested_json): """ Flatten json object with nested keys into a single level. Args: nested_json: A nested json object. Returns: The flattened json object if successful, None otherwise. """ out = {} def flatten(x, name=''): if type(x...
def generate_dmenu_options(optlist: list) -> str: """ Generates a string from list seperated by newlines. """ return "\n".join(optlist)
def rotate_right(x, y): """ Right rotates a list x by the number of steps specified in y. Examples ======== >>> from sympy.utilities.iterables import rotate_right >>> a = [0, 1, 2] >>> rotate_right(a, 1) [2, 0, 1] """ if len(x) == 0: return [] y = len(x) - y % l...
def getUser(ctx, *arg): """ returns a user id from either the arguments or if None is passed the sender """ if arg == (): # if no argument is passed go with sender return(ctx.author.id) else: return(arg[0].strip('<!@> '))
def exner(p): """use this to get the exner function exner * potential temperature = real temperature """ Rd=287.058 cp=1003.5 p0=1000.0 try: if p.max()>1200: p0*=100.0 except: if p>1200: p0*=100.0 return (p/p0)**(Rd/cp)
def maxing(corner): """ Return the Limits for the size rigth of the marker. To understand the idea of this you must debug the point returning from the detection marker. Else mantain this method """ x1 = corner[0][0] y1 = corner[0][1] x2 = corner[1][0] y2 = corner[1][1] ...
def whoTHIS(msg): """To know who sent the message. 'Self' for yourself, 'Human' for the other *human*. :param msg: unprocessed message :type msg: str :return: Who sent this message :rtype: str :Example: .. code-block:: python whoTHIS(x) *x is an unproce...
def filer_elements(elements, element_filter): """ Ex.: If filtered on elements [' '], ['a', ' ', 'c'] becomes ['a', 'c'] """ return [element for element in elements if element not in element_filter]
def check(local_env): """Validate expected results""" is_success = True if local_env["nativeCallTagA"] != 10 or local_env["nativeCallTagB"] != "second": is_success = False print("Error: Incorrect native call for threading timer") wrap_teapot = local_env["wrapObj"] if (local_env["nat...
def lower_note(note, num_semitones): """ Lowers the note passed in by the number of semitones in num_semitones. :param note: string: The note to be lowered :param num_semitones: The number of times the note passed in is to be lowered :return: string: A note one or more semitones lower...
def flatten(l): """ Flatten a list into a 1D list """ return [item for sublist in l for item in sublist]
def ACC_calc(TP, TN, FP, FN): """ Calculate accuracy. :param TP: true positive :type TP : int :param TN: true negative :type TN : int :param FP: false positive :type FP : int :param FN: false negative :type FN : int :return: accuracy as float """ try: result ...
def is_number(s): """ Returns True is string is a number. """ try: float(s) return True except ValueError: return False
def zeros_matrix(rows, cols): """ Creates a matrix filled with zeros. :param rows: the number of rows the matrix should have :param cols: the number of columns the matrix should have :return: list of lists that form the matrix """ M = [] while len(M) < rows: ...
def remove_duplicates(seq): """Remove duplicates from a sequence preserving order. Returns ------- list Return a list without duplicate entries. """ seen = set() seen_add = seen.add return [x for x in seq if not (x in seen or seen_add(x))]
def via_point_generate(path): """ path to linear via point generator (2, 4), (2, 5), (2, 6), (2, 7), (2, 8), (2, 9), (2, 10), (2, 11), (2, 12), (2, 13) | | V ...
def is_palindrome(phrase): """Is phrase a palindrome? Return True/False if phrase is a palindrome (same read backwards and forwards). >>> is_palindrome('tacocat') True >>> is_palindrome('noon') True >>> is_palindrome('robert') False Should ignore capi...
def ip_inputfiles(filenames, ipname): """Create input files per IP""" inputfiles = [None, "tmp.raw", "tmp.ui", "tmp.all"] num_infiles = 1 if ipname in ["pse", "fkm", "tccp"]: inputfiles.extend(["tmp.cmps", "tmp.guid"]) elif ipname in ["gop", "gfxpeim", "undi"]: inputfiles.remove("t...
def generate_res(body): """Wraps `body` in XML parent tags to mirror API response.""" return f'<?xml version="1.0" encoding="utf-8"?><MRData total="1">{body}</MRData>'
def normalize_hex(hex_color): """Transform a xxx hex color to xxxxxx.""" hex_color = hex_color.replace("#", "").lower() length = len(hex_color) if length in (6, 8): return "#" + hex_color if length not in (3, 4): return None strhex = u"#%s%s%s" % (hex_color[0] * 2, hex_color[1] *...
def clean_line(line): """ Removes existing <br> line breaks from the file so they don't multiply. """ return line.replace("<br>", "")
def build_path_split(path): """Return list of components in a build path""" return path.split('/')
def build_varint(val): """Build a protobuf varint for the given value""" data = [] while val > 127: data.append((val & 127) | 128) val >>= 7 data.append(val) return bytes(data)
def polar_partition(value, front_back): """ asymmetric partitioning of inclusion body """ # front aggregate goes to the front daughter if 'front' in front_back: aggregate = front_back['front'] return [aggregate, 0.0] # back aggregate goes to the back daughter elif 'back' in front_bac...
def _is_dependent_on_sourcekey(sourcekey, source_def): """Tests if 'source_def' is dependent on 'sourcekey'. """ # case: source_def is not a pseudo-column if not isinstance(source_def, dict): return False # case: sourcekey referenced directly if sourcekey == source_def.get('sourcekey'): ...
def format_size(size): """ :param float size: :rtype: str """ size = float(size) unit = 'TB' for current_unit in ['bytes', 'KB', 'MB', 'GB']: if size < 1024: unit = current_unit break size /= 1024 return '{0:.2f}'.format(size).rstrip('0').rstrip('...
def safe_max(*args, **kwargs): """ Regular max won't compare dates with NoneType and raises exception for no args """ non_nones = [v for v in args if v is not None] if len(non_nones) == 0: return None elif len(non_nones) == 1: return non_nones[0] else: return max(*non...
def _python2_load_cpkl(fpath): """ References: https://stackoverflow.com/questions/41720952/unpickle-sklearn-tree-descisiontreeregressor-in-python-2-from-python3 """ from lib2to3.fixes.fix_imports import MAPPING import sys import pickle # MAPPING maps Python 2 names to Python 3 name...
def get_texts(num): """get sample texts Args: num(int): number of texts to return Returns: list: list of sample texts """ return ["SAMPLE" for i in range(num)]
def get_word_reverse(text): """ >>> get_word_reverse('This is for unit testing') 'sihT si rof tinu gnitset' """ words = text.split() return ' '.join([word[::-1] for word in words])
def change_polarity(mutation): """ Return + if the protein mutation introduce a change in the polarity of the residue. """ groups = { "Ala": "Non polar", "Asn": "Polar", "Asp": "Acidic", "Arg": "Basic", "His": "Basic", "Cys": "...
def calculate_expected_duration(optimistic, nominal, pessimistic): """ Calculate the expected duration of a task. """ return round((optimistic + (4 * nominal) + pessimistic) / 6, 1)
def compute_alphabet(sequences): """ Returns the alphabet used in a set of sequences. """ alphabet = set() for s in sequences: alphabet = alphabet.union(set(s)) return alphabet
def es_vocal(letra): """ Valida si una letra es vocal >>> es_vocal('a') True >>> es_vocal('b') False >>> es_vocal('ae') Traceback (most recent call last): .. ValueError: ae no es una letra >>> es_vocal('1') Traceback (most recent call last): .. ValueError: 1 no e...
def calc_row_checksum(row_data): """ Method for calculating the checksum for a row. """ min_val = 0 max_val = 0 first = True for cell in row_data.split("\t"): if first: min_val = int(cell) max_val = int(cell) first = False else: ...
def fix_label_lists(tsv_file_lst_lsts): """ complex and anchor_files have first element of complex labels for an ID this list is imported as one string and needs to be list of integers, which is done in this function output is dict with ID as key and labels as value labels are ints """ ...
def pluralize(word, override): """Helper to get word in plural form.""" if word in override: return override[word] return word + 'es' if word[-1] == 's' else word + 's'
def nl(x, gamma): """ Nonlinearity of the form .. math:: f_{\\gamma}(x) = \\frac{1}{1-\\gamma x} Args: x (:class:`numpy.array`): signal gamma (float): Nonlinearity parameter Note: The integral of ``gamma * nl(x, gamma)`` is .. math:: \\int \\...
def pitch_to_str(pitch): """ Calculate the corresponding string representation of a note, given the MIDI pitch number Args: pitch (int): MIDI pitch number Returns: str: corresponding note name """ p_to_l_dic = {0: 'C', 1: 'C#', 2: 'D', ...
def subsets(l,ln, partial=[]): """ Generates the subsets of l that have ln elements. """ if len(partial) == ln: return [partial] results = [] for x in l: if not partial or x >= partial[-1]: nextp = partial[:] nextp.append(x) nextl = l[:] nextl.remove(x) results.extend(subse...
def format_date(date: str): """ This function formats dates that are in MM-DD-YYYY format, and will convert to YYYY-MM-DD, which is required sqlite. :param date: The date to modify. :return: The modified string. """ tmp = date.split("/") return "{}-{}-{}".format(tmp[2], tmp[0], tmp[1])
def length(*t, degree=2): """Computes the length of the vector given as parameter. By default, it computes the Euclidean distance (degree==2)""" s=0 for x in t: s += abs(x)**degree return s**(1/degree)
def is_object(value): """Checks if `value` is a ``list`` or ``dict``. Args: value (mixed): Value to check. Returns: bool: Whether `value` is ``list`` or ``dict``. Example: >>> is_object([]) True >>> is_object({}) True >>> is_object(()) ...
def lmap(f, xs): """A non-lazy version of map.""" return list(map(f, xs))