content
stringlengths
42
6.51k
def grad_refactor_while(x): """ grad_refactor_while """ rval = x while rval < 4: rval = rval * rval return rval
def _unpad(string: str) -> str: """Un-pad string.""" return string[: -ord(string[len(string) - 1 :])]
def _clean_tags(tags, remove, keep): """ In all tags list, replace tags in remove with keep tag. """ original_tags = tags[:] for index, tag in enumerate(original_tags): if tag in remove: tags.remove(tag) if len(original_tags) != len(tags) and keep not in tags: tags.append(ke...
def import_module(name): """Helper module to import any module based on a name""" mod = __import__(name) components = name.split('.') for comp in components[1:]: mod = getattr(mod, comp) return mod
def ensure_list(x): """If not a list, convert to one""" if isinstance(x, str): return [x] try: x[0] except TypeError: return [x] return x
def _get_dns_services(subnet): """Get the DNS servers for the subnet.""" services = [] if not subnet.get('dns'): return services return [{'type': 'dns', 'address': ip.get('address')} for ip in subnet['dns']]
def print_name(first_name: str, last_name: str, age: int) -> str: """[summary] Args: first_name (str): [description] last_name (str): [description] age (int): [description] Returns: str: [description] """ a = 1 b = 2 if ((a==1) and (b == (a+1)) ...
def lrefs_to_srefs(refs): """Converts a list of references into a string""" sref = '' for s in refs: if isinstance(s, dict): sref += s['$ref'] + " ," return sref
def _delchars(p_str, p_chars): """ Returns a string for which all occurrences of characters in chars have been removed. """ # Translate demands a mapping string of 256 characters; # whip up a string that will leave all characters unmolested. l_table = dict.fromkeys(map(ord, p_chars), None) ret...
def spec_sila_rezanja(fs1x1, debljina_strugotine, eksponent_Kienzlea): """ spec_sila_rezanja [N/mm2] \tfs1x1 [N/mm2]\n \tdebljina_strugotine [mm]\n \teksponent_Kienzlea [/] """ return fs1x1/(debljina_strugotine)**eksponent_Kienzlea
def format_call(__fn, *args, **kw_args): """ Formats a function call, with arguments, as a string. >>> format_call(open, "data.csv", mode="r") "open('data.csv', mode='r')" @param __fn The function to call, or its name. @rtype `str` """ try: name = __fn.__name__...
def strbool(val): """ convert bool to string. """ return "true" if val else "false"
def dot_product(a,b): """calculate dot product from two lists""" # optimized for PyPy (much faster than enumerate/map) s = 0 i = 0 for x in a: s += x * b[i] i += 1 return s
def create_software_id(regid, unique_id): """ Create a Software-ID by joining the Regid and the Unique-ID with a double underscore. Args: regid (str): The Regid string. unique_id (str): The Unique-ID string. Returns: The Software-ID string. """ ...
def dust_view(dusts): """ create bus arrival view from arrivals :param arrivals: (arrival, arrival, arrival...) :return: string "arrival_str/arrival_str/arrival_str..." """ view = "" for index, element in enumerate(dusts): if index != 0: view += '/' view += st...
def get_positive_int(obj: dict, name: str) -> int: """Get and check the value of name in obj is positive integer.""" value = obj[name] if not isinstance(value, int): raise TypeError( f'{name} must be integer: {type(value)}') elif value < 0: raise ValueError( f'{na...
def valid_brackets(s: str) -> bool: """only up to one open/ close square bracket allowed""" cnt, cnt_closed = 0, 0 for l in s: if l == "[": cnt += 1 if cnt > 1: return False if l == "]": cnt -= 1 if cnt == 0: cnt...
def calculate_seed_name(path: str) -> str: """ Calculate the seed name based on the path to it. Args: path: The path to the seed. Returns: The name of the seed. """ suffixes = ["example-spec", "-", "/"] for suffix in suffixes: if path.endswith(suffix): ...
def compare_response(exp_resp, act_resp): """ False if the keys are different in the nested dicts as well """ print(exp_resp) print(act_resp) test = True for key in act_resp.keys(): print(key) if not key in exp_resp.keys(): print(key) return False ...
def site_code2name(code): """ Get the full site name from a given code (e.g. GAW ID) """ d = { 'CMN': 'Monte Cimone', 'CGO': 'Cape Grim', 'BRW': 'Barrow', 'HFM': 'Havard Forest', 'SUM': 'Summit', 'NWR': 'Niwot Ridge', 'KUM': 'Cape Kumukahi', ...
def time_format_ymdhms(dt): """ Return time format as y.m.d h:m:s. :param dt: The timestamp or date to convert to string :type dt: datetime object or timestamp :return: Timeformat as \"y.m.d h:m:s\" :rtype: str """ if dt is None: return "UUPs its (None)" import datetime ...
def bold(x): """Format a string boldly. Returns: The string `x` made bold by terminal escape sequence. """ return f"\033[1m{x}\033[0m"
def to_list(obj, split_strings=True): """ Converts a obj, an iterable or a single item to a list. Args: obj (mixed): Object to convert item or wrap. split_strings (bool, optional): Whether to split strings into single chars. Defaults to ``True``. Returns: list: Conv...
def verify_user(username): """Verify username to check whether it is the same user.""" if not username: return False ans = input('Is ' + username + ' the correct username? (y/n) ') if ans in ('y', 'n') and ans == 'y': return True return False
def _cif_parse_float_with_errors(x): """ Strip bracketed errors from end of float. """ return float(x.split('(')[0])
def _bitfield_limits(hint): """Return extremal integer values of bitfield.""" width = hint['width'] if hint['signed']: n = width - 1 limits = (- 2**n, 2**n - 1) return limits # unsigned: so variable ranges over values of same sign min_, max_ = hint['dom'] # flip ? if ...
def moon(day): """ Given the total number of days in the session it works out if their is a full moon or not. :param day: Total number of days in the session :return: Boolean based on weather the moon is full or not. """ if day % 29 == 0: return True else: return False
def calc_us_in_name(name): """ calculate how many underscore is in name. :param name: a string. :return: a number """ cnt = 0 for ch in name: if ch == '_': cnt += 1 return cnt
def generate_stack_id(stack_name: str) -> str: """Generate a stack ID from the stack name""" return ( f"arn:aws:cloudformation:ap-southeast-2:123456789012:stack/{stack_name}/" "bd6129c0-de8c-11e9-9c70-0ac26335768c" )
def rgb_to_brightness(r, g, b, grayscale=False): """ Calc a brightness factor according to rgb color """ if grayscale: return 0.2126*r + 0.7152*g + 0.0722*b else: return 0.267*r + 0.642*g + 0.091*b
def addRevComplement(motifList): """ Take list of DNA motif strings and return unique set of strings and their reverse complements. """ revcompl = lambda x: ''.join([{'A': 'T', 'C': 'G', 'G': 'C', 'T': 'A', 'N':'N'}[B] for B in x][::-1]) setList = list() for motif in motifList: setList.a...
def duration_to_string(duration_seconds): """Converts a number of seconds into a duration string. Serializes an amount of time in seconds to a human-readable string representing the time in days, hours, minutes, and seconds. Args: duration_seconds: (int) Total number of seconds. Returns: ...
def pl(wavlen, plslp, const): """Define power-law in flux density per unit frequency.""" return const*wavlen**plslp
def _parseStage2(bPattern): """ This function takes as input a bPattern, pattern generated by _parseStage1. This function checks and converts bPattern into cPattern which is later used for matching tree structures. This function: 1. Checks if each subtree sequence has three parts (preceding ...
def asFloatOrNone(value): """Answers a float if it can be converted. Answer None otherwise. >>> asFloatOrNone(123) 123.0 >>> asFloatOrNone('123') 123.0 >>> asFloatOrNone('123a') is None True """ try: return float(value) except (ValueError, TypeError): return None
def count(element, seq): """Counts and returns the number of times element occurs in the sequence""" return seq.count(element)
def read_lines(csv_lines): """read lines from csv file""" items = [] count = 0 for line in csv_lines: if count > 0: if line: items.append((line[0], line[1])) count += 1 return items
def timeSortingFunction(tuple): """[summary] :param tuple: [description] :type tuple: [type] :return: [description] :rtype: [type] """ return int(tuple[1]["end_time"])
def pluralize(n, s, ss=None): """Make a word plural (in English)""" if ss is None: ss = s + "s" if n == 1: return s else: return ss
def vapPrToRH(vp, sat_vp): """ Calculate relative humidity from vapour pressure and saturated vapour pressure. :param float vp: Vapour pressure (hPa) :param float sat_vp: Saturation vapour pressure (hPa) :returns: Relative humidity (%) Example:: >>> from metutils import vapPrToRH...
def PlaceHolders(sql_args): """Return a comma-separated list of %s placeholders for the given args.""" return ','.join('%s' for _ in sql_args)
def _calculate_intervals(last_index_pre_history, amount_of_iterations, scope_len): """ Function calculate :param last_index_pre_history: last id of the known part of time series :param amount_of_iterations: amount of steps for time series forecasting :param scope_len: amount of elements in every time s...
def decimal_to_binary(number): """ Calculates the binary of the given decimal number. :param number: decimal number in string or integer format :return : string of the equivalent binary number """ if isinstance(number, str): number = int(number) binary = [] while num...
def selection_rule(l1, _p1, l2, _p2, lmax=None, lfilter=None): """ selection rule :return: list from |l1-l2|... to l1+l2 """ if lmax is None: l_max = l1 + l2 else: l_max = min(lmax, l1 + l2) ls = list(range(abs(l1 - l2), l_max + 1)) if lfilter is not None: ls = li...
def base_digits_decoder(alist: list, b: int) -> int: """ The inverse function of 'to_base'. This function will take a list of integers, where each element is a digit in a number encoded in base 'b', and return an integer in base 10 """ p = 0 ret = 0 for n in alist[::-1]: ret...
def _get_empty(value, empty_value): """Check if a protobuf field is "empty". :type value: object :param value: A basic field from a protobuf. :type empty_value: object :param empty_value: The "empty" value for the same type as ``value``. """ if value == empty_value:...
def get_final_ranks(rank_probs): """Orders final rank probabilities into a list and trims decimal places. """ ranks = [] for team, prob_dict in sorted(rank_probs.items(), key=lambda x: -sum([i*p for i,p in enumerate(x[1].values())])): ranks.append({"team": team, "prob...
def flatten(seq): """ >>> flatten([0, [1, 2, 3], [4, 5, [6, 7]]]) [0, 1, 2, 3, 4, 5, 6, 7] """ ans = [] for i in seq: if (i.__class__ is list): ans.extend(flatten(i)) else: ans.append(i) return ans
def importify_params(param_arg): """Convert parameter arguments to what CARTO's Import API expects""" if isinstance(param_arg, bool): return str(param_arg).lower() return param_arg
def sorted_if_possible(iterable, **kwargs): """Create a sorted list of elements of an iterable if they are orderable. See `sorted` for details on optional arguments to customize the sorting. Args: Iterable of a finite number of elements to sort. kwargs: Keyword arguments are passed on ...
def get_ep_next(ep_latest, ep_num): """ for provided episode name and number return which should be the next episode Parameters ---------- ep_latest: string the full name of the episode ep_num: the current episode number Returns ------- : string the name of the nex...
def manhattenPath(position1, position2): """ calculates grid deltas between two positions relative to first position :param position1: :param position2: :return: dx (int), dy (int) """ dx = position2[0] - position1[0] dy = position2[1] - position1[1] return dx,dy
def format_series(time_series): """ Formats a time series as a string for output. """ data = "" for x,y in enumerate(time_series): data += "{}\t{}\n".format(x,y) data += "\n" return data
def find_angle(ab: float, bc: float) -> int: """ >>> find_angle(10, 10) 45 >>> find_angle(1, 10) 6 """ from math import atan2, degrees return round(degrees(atan2(ab, bc)))
def smooth(scalars, weight=0.95): """ Smoothing of a list of values, similar to Tensorboard's smoothing """ last = scalars[0] # First value in the plot (first timestep) smoothed = list() for point in scalars: smoothed_val = last * weight + (1 - weight) * point # Calculate smoothed valu...
def sc_and_bcc_kps(kmax): """Lists the k-point densities up to kmax for the sc and bcc cases. Args: kmax (int): The largest allowed k-point density. Returns: kpds (list): List of the allowed k-points for sc and bcc systems. """ kpds = [] for k in range(kmax): for m in ...
def _massage_school_name(school_name: str) -> str: """Given a school name, massage the text for various peculiarities. * Replace the trailing dot of school names like Boise St. * Handle "Tourney Mode" where school names have their seed in the name. """ # Replace the trailing dot in `Boise St.` so ...
def select_stack_report(objects, what): """Select the first or the last stack report.""" assert what in ("first", "last") if what == "first": return objects[0] else: return objects[-1]
def isStandaloneFunctionHeader( targetDescriptor ): """ Identifies a string representing a standalone function. Usually a text line for a mod description header, but may also be used to help recognize the latter half (i.e. target descriptor) of a special branch syntax (such as the '<ShineActionState>' from 'bl ...
def flatten(d): """Recursively flatten a dictionary of varying depth, putting all keys at a single level. """ flatd = {} for k, v in d.items(): if isinstance(v, dict): flatd.update(flatten(v)) else: flatd[k] = v return flatd
def to_int16(y1, y2): """ Convert two 8 bit bytes to a signed 16 bit integer. Args: y1 (int): 8-bit byte y2 (int): 8-bit byte Returns: int: 16-bit integer """ x = (y1) | (y2 << 8) if x >= 32768: x = -(65536 - x) return x
def unparse_url(U): """ Convert a :class:`.Url` into a url The input can be any iterable that gives ['scheme', 'auth', 'host', 'port', 'path', 'query', 'fragment']. Unused items should be None. This function should more or less round-trip with :func:`.parse_url`. The returned url may not be ex...
def n_i_j(pixel_index, offset): """ Args: pixel_index (int): Current pixel index. block_size (int): Block size to use. Returns: int """ if pixel_index - offset < 0: samp_out = 0 else: samp_out = pixel_index - offset return samp_out
def count_vowels(s): """Used to count the vowels in the sequence""" s = s.lower() counter=0 for x in s: if(x in ['a','e','i','o','u']): counter+=1 return counter
def linepoint(t, x0, y0, x1, y1): """Returns coordinates for point at t on the line. Calculates the coordinates of x and y for a point at t on a straight line. The t parameter is a number between 0.0 and 1.0, x0 and y0 define the starting point of the line, x1 and y1 the ending point of the l...
def link_fedora_file_md(sid): """ Creates a html link tag to the EASY_FILE_METADATA of a file with the given sid. http://easy01.dans.knaw.nl:8080/fedora/objects/easy-file:6364865/datastreams/EASY_FILE_METADATA/content :param sid: a file id :return: link to the file metadata """ return '<a...
def get_doc_name(doc): """ Get actual document name from dict like {'receipt': {//actual body//}} :param doc: dict like {'doc_name': {//actual body//}} """ if doc is None: return None return next(iter(doc))
def sign(a): """ Return the sign of *a* """ if a == 0.0: return 1 else: return a/abs(a)
def get_transpose_graph(graph): """Get the transpose graph""" transpose = {node: set() for node in graph.keys()} for node, target_nodes in graph.items(): for target_node in target_nodes: transpose[target_node].add(node) return transpose
def highest_rank(arr: list) -> int: """ This function returns the number which is most frequent in the given input array. """ number_with_frequent: dict = {} most_frequent_number: list = [] for i in arr: if i not in number_with_frequent: number_with_frequent[i] = 1 else: ...
def parse_lldpd_output(output): """http://stackoverflow.com/questions/20577303/parse-lldp-output-with-python """ result = {} entries = output.strip().split('\n') for entry in entries: path, value = entry.strip().split('=', 1) path = path.split('.') components, final = path...
def _same_value(obj1, obj2): """ Helper function used during namespace resolution. """ if obj1 is obj2: return True try: obj1 = obj1.get_value() except (AttributeError, TypeError): pass try: obj2 = obj2.get_value() except (AttributeError, TypeError): ...
def bytesize2human_en(num): """ this function will convert bytes to MB.... GB... etc """ for x in ['bytes', 'KB', 'MB', 'GB', 'TB']: if num < 1024.0: return "%3.1f %s" % (num, x) num /= 1024.0
def required_for_output(inputs, outputs, connections): """ Collect the nodes whose state is required to compute the final network output(s). :param inputs: list of the input identifiers :param outputs: list of the output node identifiers :param connections: list of (input, output) connections in the...
def gather(x, indices): """ Return the sequence [x[i] for i in indices]. >>> gather([8, 16, 32, 64, 128], [3, 0, 2]) [64, 8, 32] >>> gather([8, 16, 32, 64, 128], []) [] """ return [x[i] for i in indices]
def format_non_null_ratio(rows, nulls): """Format percentage of non-null value of the column Args: rows (int): number of rows nulls (int): number of null-values Returns: str: non-null ratio with the format '%.2f'. """ if rows is None or nulls is None: return 'N/A' ...
def abtest(*abtests): """Select a (list of) abtest(s).""" vabtest = [t for t in abtests] return {"abtest": vabtest}
def vecs2tuples(vecs): """ Convert list of vectors into set of tuples """ return set(tuple(v) for v in vecs)
def replace_string(original, start, end, replacement): """Replaces the specified range of |original| with |replacement|""" return original[0:start] + replacement + original[end:]
def accuracy_metrics(act, exp): """Return precision and recall for a single query Args: act (set): actual result exp (set): expected result Returns: float, float: precision and recall """ if act == exp: # Consider the edge case: act=[] exp=[] ...
def getFWInventoryAttributes(rawFWInvItem, ID): """ gets and lists all of the firmware in the system. @return: returns a dictionary containing the image attributes """ reqActivation = rawFWInvItem["RequestedActivation"].split('.')[-1] pendingActivation = "" if reqActivation == "No...
def clean_repository_clone_url( repository_clone_url ): """Return a URL that can be used to clone a tool shed repository, eliminating the protocol and user if either exists.""" if repository_clone_url.find( '@' ) > 0: # We have an url that includes an authenticated user, something like: # http:/...
def get_default_query_ids(source_id, model): """ Returns set of Strings, representing source_id's default queries Keyword Parameters: source_id -- String, representing API ID of the selection source model -- Dict, representing current DWSupport configuration >>> from copy import deepcopy ...
def isOutputDeep(node): """check if node is outputing deep data @node: (obj) root node of the tree return: (bool) True if is deep, False otherwise """ outputdeep=None try: node.deepSampleCount(0,0); outputdeep = True except: outputdeep = False return outputdeep
def xl_col_to_name(col, col_abs=False): """ Convert a zero indexed column cell reference to a string. Args: col: The cell column. Int. col_abs: Optional flag to make the column absolute. Bool. Returns: Column style string. """ col_num = col if col_nu...
def one_dict(list_dict): """ converts a list of dictionaries on a dictionary of lists. Example: [ {'a_key': 'a_value_1', 'b_key': 'b_value_1'}, {'a_key': 'a_value_2', 'b_key': 'b_value_2'} ] becomes: { 'a_key': ['a_value_1', 'a_value_2'], 'b_key':...
def insertShiftArray(arr, num): """insert into middle of list""" if type(arr) is not list or type(num) is not int: raise TypeError('Argument(s) invalid.') output = [0] * (len(arr) + 1) middle = (len(arr) + len(arr) % 2) // 2 for i in range(len(output)): if i < middle: out...
def get_iou(boxA, boxB): """ Calculate the Intersection over Union (IoU) of two bounding boxes. Parameters ---------- boxA = np.array( [ xmin,ymin,xmax,ymax ] ) boxB = np.array( [ xmin,ymin,xmax,ymax ] ) Returns ------- float in [0, 1] """ bb1 = dict() bb1['x1'] = boxA[0] bb1['y1'] = boxA[...
def replace(serverName, itemId, value, date, quality): """Replaces values on the OPC-HDA server if the given item ID exists. Args: serverName (str): The name of the defined OPC-HDA server. itemId (str): The item ID to perform the operation on. value (object): The value to replace. ...
def _get_match_id(p1, p2, round_id): """Return a unique integer for each pair of p1 and p2 for every value of round_id. Property: _get_match_id(p1, p2, r) == _get_match_id(p2, p1, r) for all p1, p2, r """ return hash("".join(sorted(str(p1) + str(p2) + str(round_id))))
def subkey(dct, keys): """Get an entry from a dict of dicts by the list of keys to 'follow' """ key = keys[0] if len(keys) == 1: return dct[key] return subkey(dct[key], keys[1:])
def add_nones(word): """Change word into a list and add None at its beginning, end, and between every other pair of elements. Works whether the word is a str or a list. """ def yield_it(word_string): yield None it = iter(word_string) yield next(it) ...
def user_editor(context, request, leftcol_width=4, rightcol_width=8): """ User editor panel. Usage example (in Chameleon template): ${panel('user_editor')} """ return dict(leftcol_width=leftcol_width, rightcol_width=rightcol_width)
def string_to_numbers(string): """ Convert a string to a list of numbers :param string: Message as string :return: Message as numbers """ vals = [ord(s) for s in string] return vals
def calculate_interest_amount_in_years(starting_amount, number_of_years, interest_rate, stipend_rate): """ After X number of years, how much would I have in the bank? :param starting_amount: The amount of money the bank has to start with. :type starting_amount: double :param number_of_years: The amo...
def format_passport_data(data): """Helper function to format passport data""" passports = data.split('\n\n') formatted_passports = [] for passport in passports: split_passport = str(passport.strip().lower()).split() # print(split_passport) dictionary_passport = dict(pair.split(':...
def chef_api_url(name, version, registry='https://supermarket.chef.io/api/v1'): """ Return a package API data URL given a name, version and a base registry URL. For example: >>> c = chef_api_url('seven_zip', '1.0.4') >>> assert c == u'https://supermarket.chef.io/api/v1/cookbooks/seven_zip/versions/...
def has_anagram_substring(a: str, b: str) -> bool: """ Time: O((a - b)(b^2)) Space: O(b) """ def make_freq_dist(string: str) -> dict: dist = dict() for letter in string: letter = letter.lower() if letter not in dist: dist[letter] = 1 ...
def create_hash(key, size): # O(1) """ Creates a hash by taking the first character in a string, getting its ASCII value and apply a modular function to the provided size >>> create_hash(42, 5) 4 >>> create_hash(42, 4) 0 >>> create_hash(122.12, 4)...
def color_clamp(color): """ Ensures a three part iterable is a properly formatted color. Parameters: color (tuple): RGB tuple Returns: color (tuple): Same color as input, as integers between 0 and 255 """ clamped_color = [max(min(int(i), 255), 0) for i in color] return tuple(clampe...