content
stringlengths
42
6.51k
def sum_ignore_none(iterable): """ Sum function that skips None values :param iterable: An iterable to sum, may contain None or False values :return: the sum of the numeric values """ return sum([x for x in iterable if x])
def get_account_idx_for_deploy(accounts: int, deploy_idx: int) -> int: """Returns account index to use for a particular transfer. :param accounts: Number of accounts within batch. :param deploy_idx: Index of deploy within batch. :returns: Ordinal index of account used to dispatch deploy. """ ...
def gen_whats_this(data): """Generate the "What's this" text for the variable discribed in data @param[in] data A dictionary with the caracteristics of the variable @param[out] WhatThis String with the "What's this" texte from data """ return data["desc"]
def find_last(s, sub): """s and sub are non-empty strings Returns the index of the last occurrence of sub in s. Returns None if sub does not occur in s""" if s.find(sub) == -1: # this is the return value for s.find if it's not there return None else: ans = s.find(sub) # found...
def spin_energy(J = -2, mu = 1.1, k = 1, state = [1,-1,1,-1]): """Computes the energy of some spin configuration. Note, all lists should be in the format of a sequential list where 1 is spin up and -1 is spin down :param J: Ferromagnetic constant, defaults to -2 :type J: int or float :p...
def isOctDigit(s): """ isOctDigit :: str -> bool Selects ASCII octal digits, i.e. '0'..'7'. """ return s in "01234567"
def error(context, *infos): """Print a brief error message and return an error code.""" messages = ["An error occurred when when " + context + ":"] messages.extend(infos) print("\n\t".join(map(str, messages))) return 1
def ver_date_cmp(ver1, date1, ver2, date2, ver_cmp): """ Compare versions either by looking at the version string, or by looking at the release dates. """ # if the package module provided a native compare function # then compare the version strings. This should be more # accurate an...
def bubble_sort(numbers): """Sorts a list of numbers using bubble sort. Args: numbers: a list of numbers. Returns: A sorted list of numbers. """ sorted_numbers = numbers.copy() swapped = True while swapped: swapped = False for i in range(1, len(sorted_number...
def make_slip_wfs_name(dataset_name): """ Extract the SLIP WFS layer name from a dataset name. >>> make_slip_wfs_name('LGATE-001') 'slip:LGATE-001' """ return "slip:{0}".format(dataset_name.upper())
def human_size(byte_size): """Convert number of bytes into human-readable size (base 1024).""" for suffix in ["bytes", "KiB", "MiB", "GiB", "TiB"]: if byte_size < 1024.0: return f"{byte_size:-6.1f} {suffix}" byte_size /= 1024.0 return f"{byte_size:-6.1f} PiB"
def str_remove_accents(s): """Utility to remove accents from characters in string""" import unicodedata return unicodedata.normalize('NFD', s).encode('ascii','ignore').decode('ascii')
def hcf(a, b): """Computes the highest common factor of two numbers""" if a < b: a, b = b, a while b > 0: r = a % b a = b b = r return a
def str2list(s, sep=","): """Converts a string representing a list with floats to a Python list object filled with floats.""" return [float(x.strip()) for x in s.split(sep)]
def _replaceImages(logsort_list, image_list): """ Replaces images from logsort with ones provided in the list. """ if len(logsort_list) == len(image_list): new_logsort = [] for i, line in enumerate(logsort_list): new_logsort.append(line[:4] + [image_list[i]] + line[5:]) ...
def dayOfWeek(year, month, day): """Zellers congruence""" date = '%d-%d-%d' % (year, month, day) if month <= 2: month += 12 year -= 1 q = day m = month k = year % 100 j = year // 100 h = (q + ((13 * (m + 1)) // 5) + k + (k // 4) + (j // 4) - (2 * j)) % 7 return h
def dict_to_list(input): """Convert resource dict into list.""" # return sorted(input.values(), key=lambda x: locale.strxfrm(x.get("name_sv"))) return list(input.values())
def check_valid_table(schema, name, dump_tables): """ check if table is valid (can be from schema level restore) """ if (schema, name) in dump_tables or (schema, '*') in dump_tables: output = True else: output = False return output
def deep_merge(*dicts): """ Recursively merge all input dicts into a single dict. """ result = {} for d in dicts: if not isinstance(d, dict): raise Exception('Can only deep_merge dicts, got {}'.format(d)) for k, v in d.items(): # Whenever the value is a dict, ...
def make_markdown_matrix(sheets: list) -> str: """ Args: sheets (list) : a list of the spreadsheets sheets after process of context_single_get_parse Returns (str): This function returns a table representation of the sheet. if the sheet is empty the function will return Empty...
def snake_to_camel(string): """ Convert string from snake to camel type """ words = string.split('_') return words[0] + ''.join(word.title() for word in words[1:])
def _paramify(param_name, param_value): """If param_value, return &param_name=param_value""" if isinstance(param_value, bool): param_value = str(param_value).lower() if param_value: return "&" + param_name + "=" + str(param_value) return ""
def check_paragraph(index: int, line: str, lines: list) -> bool: """Return True if line specified is a paragraph """ if index == 0: return bool(line != "") elif line != "" and lines[index - 1] == "": return True return False
def c_schar(i): """ Convert arbitrary integer to c signed char type range as if casted in c. >>> c_schar(0x12345678) 120 >>> (c_schar(-128), c_schar(-129), c_schar(127), c_schar(128)) (-128, 127, 127, -128) """ return ((i + 128) % 256) - 128
def _ms_to_s(n): """Convert from milliseconds to seconds.""" if n is not None: n = float(n) / 1000 return n
def parseGenomeRegion(regionStr) : """ parse a samtools region string and return a hash on keys ("chrom","start","end") missing start and end values will be entered as None """ assert(regionStr is not None) word=regionStr.strip().rsplit(':',1) if len(word) < 1 : raise Exception("...
def _is_library_product(product): """Returns a boolean indicating whether the specified product dictionary is a library product. Args: product: A `dict` representing a product from package description JSON. Returns: A `bool` indicating whether the product is a library. ...
def _fixplatform(p): """ Fix the platform. :param platform: The platform to fix. """ if p == 'pc' or p == 'PC' or p == 'ORIGIN': return 'origin' elif p == 'ps4' or p == 'PSN' or p == 'PS5' or p == 'ps5': return 'psn' elif p == 'x1' or p == 'xbox' or p == 'XBOX' or p == 'XBOX1...
def find_nth_term_for_an_arithmetic_sequence(first_term: int, common_difference: int, requested_term: int) -> int: """ Find the nth term in an arithmetic sequence :param first_term: :param common_difference: :param requested_term :return: the nth term """ return first_term + (req...
def serialize_tipo_relacion(tipo_relacion): """ #/components/schemas/tipoRelacion """ if tipo_relacion: return tipo_relacion.codigo return "DECLARANTE"
def denormalize(body): """ Unflatten constraint field in given JSON """ new = {} new["constraint"] = {} for key, value in body.items(): if "constraint_" in key: new["constraint"][key[11:]] = value else: new[key] = value return new
def _format_size(num, suffix='B'): """ Format sizes """ for unit in ['','K','M','G','T','P','E','Z']: if abs(num) < 1024.0: return "%3.1f%s%s" % (num, unit, suffix) num /= 1024.0 return "%.1f%s%s" % (num, 'Yi', suffix)
def _dict_depth(d): """ Get the nesting depth of a dictionary. For example: >>> _dict_depth(None) 0 >>> _dict_depth({}) 1 >>> _dict_depth({"a": "b"}) 1 >>> _dict_depth({"a": {}}) 2 >>> _dict_depth({"a": {"b": {}}}) 3 Args:...
def merge_arg_and_const_arg(arg, const_arg): """ prepares data from arg and const_arg such that they can be passed to the general integration routine arg and const_arg are both assumed to be dictionaries the merge process must not alter arg nor const_arg in order to be used in the jobm...
def expandCallable(fun, self, other): """ If the 'other' argument is a callable object call it with self.shape as the only argument. """ return ( fun(self, other(self.shape)) if callable(other) else fun(self, other) )
def triangulateSquares(F, a=[0, 1, 2], b=[2, 3, 0], c=[1, 0, 2], d=[3, 2, 0] ): """ Convert squares to triangles """ FT = [] for face in F: FT.append([face[a[0]], face[a[1]], face[a[2]]]) FT.append([face[b...
def make_a_string(item): """Convert tuple or list or None to a string. Important: elements in tuple or list are separated with ; (not ,) for compatibility with csv.""" if isinstance(item, tuple) or isinstance(item, list): return ';'.join([str(i) for i in item]) elif item is None: return ...
def remove_xmlns(string, xmlns): """Removes a specified xmlns url from a string.""" output = string.replace('{' + xmlns + '}', '') return output
def cleanup_whitespace(text): """ Cleanup excess docstring whitespace. """ if text: if "\n" in text: lines = [] for line in text.splitlines(): line = line.rstrip() if line: lines.append(line) text = "\n".join...
def file_as_string(file: str) -> str: """Returns contents of file as string.""" with open(file, "r") as f: return f.read()
def _FieldsToKey(fields): """Converts a list of field values to a metric key.""" return tuple(fields) if fields else ()
def thermal_diffusivity(k, rho, C_p): """ Calculates thermal diffusion coefficient of a fluid. Input variables: T : Thermal conductivity rho : Fluid density C_p : Specific heat capacity """ alpha = k / (rho * C_p) return alpha
def secret_file(api_name): """ returns a path to the file where the client secret is stored. """ return 'api_keys/' + api_name + '_secret.json'
def grad_refactor__while_1(x): """ _while """ ret = x * x i = 2 while i <= 3: ret = ret * i i = i + 1 return ret
def os2ip(x: bytes) -> int: """ Convert an octet string `x` to a nonnegative integer. https://tools.ietf.org/html/rfc8017#section-4.2 """ return int.from_bytes(x, byteorder='big', signed=False)
def _is_earlyboot_pc(pc): """ Early boot if the top 32-bit is zero """ return not (pc >> 32)
def parse_order(order_str): """ Given a repr string representing a TurnOrder, return the object. Args: order_str: A string that contains a pickled TurnOrder object. Return: If the string is actually a parsable TurnOrder, return the object. Otherwise return None """ if order_str...
def fold(s): # function fold: auxiliary function: shorten long option values for output """auxiliary function: shorten/fold long option values for normal output""" offset = 64 * " " maxlen = 70 sep = "|" parts = s.split(sep) line = "" ...
def get_year_month_day(node): """ Retorna os valores respectivos dos elementos "year", "month", "day". Parameters ---------- node : lxml.etree.Element Elemento do tipo _date_, que tem os elementos "year", "month", "day". Returns ------- tuple of strings ("YYYY", "MM", "...
def rotmat(original): """ Rotate clockwise >>> rotmat([[1, 2], [3, 4]]) [(3, 1), (4, 2)] """ return list(zip(*original[::-1]))
def cocktail_shaker_sort(unsorted): """ implementation of cocktail shaker sort algo in pure python :param unsorted: unsorted list :return: sorted list """ for i in range(len(unsorted)-1,0,-1): swapped = False for j in range(i,0,-1): if unsorted[j] < unsorted[j-1]: ...
def sdk_normalize(filename): """ Normalize a path to strip out the SDK portion, normally so that it can be decided whether it is in a system path or not. """ if filename.startswith('/Developer/SDKs/'): pathcomp = filename.split('/') del pathcomp[1:4] filename = '/'.join(pathc...
def guess_multi_value(value): """ Make the best kind of list from `value`. If it's already a list, or tuple, do nothing. If it's a value with new lines, split. If it's a single value without new lines, wrap in a list """ if isinstance(value, (tuple, list)): return value if isinstanc...
def promote_index(rshapes, rdimensions, rstrides, roffset, rindex): """Return the index of the original array that corresponds to the given index of the dimensionality reduced array. """ dimensionality = sum(map(len, rdimensions)) index = [None] * dimensionality if isinstance(rindex, int): ...
def tokenize_options(options_from_db, option_name, option_value): """ This function will tokenize the string stored in database e.g. database store the value as below key1=value1, key2=value2, key3=value3, .... This function will extract key and value from above string Args: options_fro...
def value(value): """ Return value unless it's None in which case we return 'No Value Set' """ if value is None or value == '': return '-' else: return value
def filtertime(timestamp, interval): """Check if timestamp is between timestamp_range - (time1,time2) Args: timestamp --> UNIX timestamp value. interval --> `Tuple` of 2 UNIX timestamp values. Returns: `bool` --> True/False """ T0, T1 = interval if (timestamp <= T1) an...
def delete_satellite_gateway(vpn, elements): """ Delete a satellite gateway. :param PolicyVPN vpn: policy VPN reference :param list elements: list of Element instances :return: True | False depending on whether an operation taken :raises PolicyCommandFailed: failure during deletion """ ...
def get_deviation_id(deviation_url): """Extract the deviation_id from the full deviantart image URL. Args: deviation_url (str): Deviation URL. Returns: str: Deviation ID. """ url_parts = deviation_url.split('-') return url_parts[-1]
def mongo_db_name(base_fname): """Use the corpus filename to create the database name.""" fname = base_fname.replace('\\', '/').rsplit('/', 1)[1] fname = fname.replace('.', '_') return fname
def _get_adjacent_item(l, o): """Finds object |o| in collection |l| and returns the item at its index plus 1. """ index = l.index(o) return l[index + 1]
def partition(l, size): """ Partition the provided list into a list of sub-lists of the provided size. The last sub-list may be smaller if the length of the originally provided list is not evenly divisible by `size`. :param l: the list to partition :param size: the size of each sub-list :retur...
def _get_from_email_(message: dict) -> str: """ Returns the email address of the from message :param message: a dict that represents a message :return: an string containing the email or an empty string """ if message.get("@msg_from"): email = message["@msg_from"].get("emailAddress") ...
def end_detect(x): """ return false if the location is NaN """ if x=="NaN": return False else: return True
def is_valid_rtws(rtws): """ Given a clock-valuation timedwords with reset-info, determine its validation. """ if len(rtws) == 0 or len(rtws) == 1: return True current_clock_valuation = rtws[0].time reset = rtws[0].reset for rtw in rtws[1:]: if reset == False and rtw.time...
def format_help(help): """ Reformat the given help text ready to be placed in an embed. Replace single newlines with spaces, and replace double newlines with a single newline. This has the effect of removing line wrapping and only having a line break between paragraphs instead of leaving a blank li...
def create_index_regex(input_symbol: str) -> str: """Creates a regular expression pattern to match the index symbology. To create the regular expression pattern, the function uses the fact that within the ICE consolidated feed, all the indices are identified by the root symbol (a unique mnemonic based ...
def work_root(session): """Return the default root to browse for work files.""" return session["AVALON_WORKDIR"]
def GenerateClientLoginAuthToken(http_body): """Returns the token value to use in Authorization headers. Reads the token from the server's response to a Client Login request and creates header value to use in requests. Args: http_body: str The body of the server's HTTP response to a Client Login r...
def _average_pixels(data): """Calculate an average color over all ambilight pixels.""" color_c = 0 color_r = 0.0 color_g = 0.0 color_b = 0.0 for layer in data.values(): for side in layer.values(): for pixel in side.values(): color_c += 1 color_...
def byteCalc(bytes:int) -> str: """ Transform Bytes in MB or KB Parameters ---------- bytes : int number of bytes Returns ------- str a byte converted with yours measure """ if bytes >= 100000: return f"{(b...
def _normalise_config(config: dict) -> dict: """ Removes special characters from config keys. """ normalised_config = {} for k in config: normalised_config[ k.replace("--", "").replace("<", "").replace(">", "") ] = config[k] return normalised_config
def escape_special_characters(input_string): """ Escape special characters to avoid unwanted behavior. Note that they are not stored in the index so you cannot search for them. Args: input_string (str): String to escape special characters of Returns: str: Input string that has its spe...
def distance_between_points_meters(x1, x2, y1, y2): """Distance between two points. Example of coordinate reference system in meters: SWEREF99TM """ return (((x2 - x1) ** 2) + ((y2 - y1) ** 2)) ** 0.5
def spherocylinder_aspect_ratio(l, R): """Return the aspect ratio of a spherocylinder, Parameters ---------- l: float Length of the cylinder section. R: float Radius of the hemispheres and cylinder sections. Returns ------- ar: float Aspect ratio. This i...
def _to_distrf(broadening): """ Translate to qmmlpack distrf format.""" return ("normal", (broadening,))
def _valid_orders_from_keys(key_list): """ :param key_list: :return: """ key_list = list(key_list) # remove keys whose type string return [eo for eo in key_list if not isinstance(eo, type(''))]
def _gen_type_octet(hn, ln): """Generates a type octet from a high nibble and low nibble.""" return (hn << 4) | ln
def parse_hjulet(res_data): """ Parse the menu of Restaurang Hjulet. Currently no menu available. """ data = {"menu": []} return data
def is_filetype(filename: str) -> bool: """ Return true if fname is ends with .csv, .xlsx, or .xls. Otherwise return False. :filename: filename string Returns bool """ cfname = filename.lower() if cfname.endswith(".csv") and not cfname.startswith("pdappend"): return True ...
def is_an_upcast(type1, type2): """Given two data types (as strings), check if converting to type2 from type1 constitutes an upcast. Differs from aesara.scalar.upcast """ category = { # The first number in the pair is the dtype (bool, uint, int, float, # complex). Conversion from hi...
def svn_repo(repo): """ Tests if a repo URL is a svn repo, then returns the repo url. """ # we can just go for known providers of svn services = ('svn://', 'https://svn.code.sf.net/p/', 'http://svn.savannah.gnu.org/svn/', 'https://svn.icculus.org/', 'http://svn.icculus.org/', 'http://svn.uktrainsim...
def sphere_to_plane_car(az0, el0, az, el): """Project sphere to plane using plate carree (CAR) projection. The target point can be anywhere on the sphere. The output (x, y) coordinates are likewise unrestricted. Please read the module documentation for the interpretation of the input parameters an...
def read_int(field: str) -> int: """Read an integer.""" return int(field) if field != "" else 0
def left_to_right_check(input_line: str, pivot: int): """ Check row-wise visibility from left to right. Return True if number of building from the left-most hint is visible looking to the right, False otherwise. input_line - representing board row. pivot - number on the left-most hint of th...
def ubids(specs): """Extract ubids from a sequence of specs Args: specs (sequence): a sequence of spec dicts Returns: tuple: a sequence of ubids """ return tuple(s['ubid'] for s in specs if 'ubid' in s)
def to_lower_camel(name: str) -> str: """Converts snake_case string into lowerCamelCase.""" head, *tail = name.split("_") return head.lower() + "".join(x.title() for x in tail)
def from_bamstats(stats, value): """Return percentage that a part represents of a total.""" if value == "mean target coverage": return stats.get("summary", {}).get("mean coverage") elif value == "total target size": return stats.get("summary", {}).get("total target size") elif value == "...
def _combine_meta(meta, flattened_meta, idx): """ Combine newly flattened metadata with existing metadata. This Function is designed to keep the indexing of the different metadata fields consistent for each node within the sample node tree s.t. all the fields in index (idx) 0 will be from item 0 in ...
def parse_motsfusion_seg(seg_json): """ Returns class, score, mask, bbox and reid parsed from input If throws error, need to run methods in adapt_input.py to adapt MOTSFusion segmentations - to have a class field taken from the corresponding TrackRCNN files, see functions below: * add_detection_...
def make_func_obj(func_ref, host): """Create function object to call in call func""" return { 'func_ref': func_ref, 'host': host }
def autocomplete_getarg(line): """ autocomplete passes in a line like: get_memory arg1, arg2 the arg2 is what is being autocompleted on so return that """ # find last argument or first one is seperated by a space from the command before_arg = line.rfind(',') if(before_arg == -1): bef...
def _elevation_color(elevation, sea_level=1.0): """ Calculate color based on elevation :param elevation: :return: """ color_step = 1.5 if elevation < sea_level/2: elevation /= sea_level return 0.0, 0.0, 0.75 + 0.5 * elevation elif elevation < sea_level: elevation ...
def dict_list_to_list_dict(dict_list): """Transform a list of dictionaries to a dictionary of list""" list_dict = {} key_list = set(key for d in dict_list for key in d) for dictionary in dict_list: for key in key_list: val = dictionary.get(key) if key in list_dict: ...
def calc_scalar_product_by_complex_vectors( vector_1, vector_2, flag_vector_1=False, flag_vector_2=False): """Scalar product by complex vectors. The vector is given as tuple of its coordinates defined in Chartezian coordinate system. """ product_comp = tuple([v_1*v_2 for v_1, v_2 in zip(vec...
def reset_encoding(str_): """ :param str_: str; :return: str; """ return str_.replace(u'\u201c', '"').replace(u'\u201d', '"')
def _try_format_web_vocabulary(text): """Replace old CBV URNs by new web vocabulary equivalents.""" return text.replace( 'urn:epcglobal:cbv:bizstep:', 'https://ns.gs1.org/voc/Bizstep-' ).replace( 'urn:epcglobal:cbv:disp:', 'https://ns.gs1.org/voc/Disp-' ).replace( 'urn:epcglobal:...
def union_box(box_a, box_b): """ Calculates the union box from two bounding boxes with the format ((x_min, x_max), (y_min, y_max)). Source code mainly taken from: https://www.pyimagesearch.com/2016/11/07/intersection-over-union-iou-for-object-detection/ `box_a`: the first box `box_b`: the second...
def manhattan_dist(coordinates): """calculates manhattan distance in multiple dimensions""" return sum(abs(coordinate) for coordinate in coordinates)
def distance_matrix(data, dist): """ Distance matrix (all-to-all), dictionary form """ return {(elem1, elem2): dist(elem1, elem2) for elem1 in data for elem2 in data if elem1 != elem2}