content
stringlengths
42
6.51k
def format_attributes(attributes): """ Takes an attribute dict and converts it to string :param attributes: dict with attributes :return: string with attributes in GFF3 format """ return ';'.join([k + '=' + v for k, v in attributes.items()])
def subv3s(vec, scalar): """subtract scalar from elements of 3-vector""" return (vec[0]-scalar, vec[1]-scalar, vec[2]-scalar)
def _maybe_format_css_class(val: str, prefix: str = ""): """ Create a CSS class name for the given string if it is safe to do so. Otherwise return nothing """ if val.replace("-", "_").isidentifier(): return f"{prefix}{val}" return ""
def pythagorean(a,b,c): """ Takes three side lengths and returns true if a^2 + b^2 = c^2, otherwise false :param a: int or float :param b: int or float :param c: int or float :return: bool """ a = 3 b = 1 c = 2 pie = a**2 cake = b**2 cookie = c**2 return True
def gcd2(a, b): """ Calculate the greatest common divisor of a and b. """ if a <= 0 or b <= 0 or not isinstance(a, int) or not isinstance(b, int): raise TypeError('Prameters must be positive integers.') while b: (a, b) = (b, a % b) return a
def common_start(sa, sb): """Return the longest common substring from the beginning of sa and sb.""" def _iter(): for a, b in zip(sa, sb): if a == b: yield a else: return return ''.join(_iter())
def is_placement_possible(y, x, n, board): """ Returns whether or not a number can be placed at a provided coordinate This function uses the following format: board[y][x] == is_placement_possible(n)? :param x: the provided x coordinate (the column number from left) :param y: the provided y coordinate (the row num...
def _make_divisible(v, divisor, min_value=None): """Make channels divisible to divisor. This function is taken from the original tf repo. It ensures that all layers have a channel number that is divisible by 8 It can be seen here: https://github.com/tensorflow/models/blob/master/research/slim/nets/m...
def isreal(obj): """ Tests if the argument is a real number (float or integer) :param obj: Object :type obj: any :rtype: boolean """ return ( ((obj is not None) and (not isinstance(obj, bool)) and ( isinstance(obj, int) or isinstance(obj, float))) )
def check_is_video(file_name): """ Ensures passed file inputs are of recognized media format. """ formats = ['flv', 'mp4', 'avi', 'mp3', 'flaac'] return any([extension for extension in formats if file_name.endswith(extension)])
def org_url(orgname, url_map): """ """ lst = url_map.get(orgname, []) for d in lst: if d["source"] == "wikidata_official_website": return d["url"] return ""
def index2string(index): """ Convert an int to string Parameter --------- index: int index to be converted Return ------ string: string string corresponding to the string """ if index == 0: string = 'BENIGN' elif index == 1: string = 'FTP-Pat...
def bxor(*args): """Return the bitwise xor of all arguments.""" res = 0 for arg in args: res ^= arg return res
def isflat(untyped): """tests if object is a flat set or list. Returns True for other types""" onlyelements = True if isinstance(untyped, (set, list)): for e_temp in list(untyped): if isinstance(e_temp, (set, list)): onlyelements = False return onlyelements
def calc_total_hours(entries): """ Calculates sum of hours from an array of entry dictionaries """ total_hours = 0.0 for entry in entries: total_hours = total_hours + float(entry['hours_spent']) return total_hours
def getExpandedAttrNames(attrs): """ Given a list of compound attribute names, return a list of all leaf attributes that they represent. Only supports the more common transform attributes. e.g. ['t', 'rx', 'ry'] -> ['tx', 'ty', 'tz', 'rx', 'ry'] Args: attrs (list of str): The attribute...
def foreground_color(bg_color): """ Return the ideal foreground color (black or white) for a given background color in hexadecimal RGB format. """ bg_color = bg_color.strip('#') r, g, b = [int(bg_color[c:c + 2], 16) for c in (0, 2, 4)] if r * 0.299 + g * 0.587 + b * 0.114 > 186: return '...
def node_name(row, col): """Return a unique node name""" return f"{row:03d},{col:03d}"
def addDegrees(heading, change): """ Calculate a new heading between 0 and 360 degrees :param heading: Initial compass heading :param change: Degrees to add :return: New heading between 0 and 360 degrees """ heading += change return heading % 360
def get_ratios(L1, L2): """ Assumes: L1 and L2 are lists of equal length of numbers Returns: a list containing L1[i]/L2[i] """ ratios = [] for index in range(len(L1)): try: ratios.append(L1[index]/float(L2[index])) except ZeroDivisionError: ratios.append(float...
def filter_based_on_query_coverage(query_length, query_start_index, query_stop_index, query_coverage_threshold): """ Determine if read should be filtered based on query coverage threshold """ if query_length > 1: query_coverage = ((abs(query_stop_index - query...
def percent_change(changed, total): """ :param changed: :param total: :return percent rate with 2 digits as precision: """ return "+{0:.2f}%".format(changed/total*100)
def info_from_OAuth2(token): """ Validate and decode token. Returned value will be passed in 'token_info' parameter of your operation function, if there is one. 'sub' or 'uid' will be set in 'user' parameter of your operation function, if there is one. 'scope' or 'scopes' will be passed to scope val...
def compress(word : str ) -> str : """ Returns compact representation of word. :code:`compress('LLRRRR')` Args: `word` (str): a word (supposedly binary L&R) Returns: list of str: list of circular shifts :Example: >>> compres('LLRRRR') L2 R4 """ lett...
def find_tree_root(tree, key): """Find a root in a tree by it's key :param dict tree: the pkg dependency tree obtained by calling `construct_tree` function :param str key: key of the root node to find :returns: a root node if found else None :rtype: mixed """ result = ...
def surround(string): """Surrounds a string with curly brackets, square brackets, and a space. :param string: String to be surrounded :type string: str :return: Surrounded string :rtype: str""" return "{[ " + string + " ]}"
def _safe_divide(numerator: int, denominator: int) -> float: """Normal division except anything/0 becomes 0.0.""" return numerator / denominator if denominator else 0.0
def mapValue(value, leftMin, leftMax, rightMin, rightMax): """ Function for mapping a value to a given range """ # Figure out how 'wide' each range is leftSpan = leftMax - leftMin rightSpan = rightMax - rightMin # Convert the left range into a 0-1 range (float) valueScaled = float(valu...
def is_video(filename): """Checks if filename is a video.""" vid_exts = ("avi", "flv", "m4v", "mkv", "mpg", "mov", "mp4", "webm", "wmv") return filename.casefold().endswith(vid_exts)
def to_cmd_string(unquoted_str: str) -> str: """ Add quotes around the string in order to make the command understand it's a string (useful with tricky symbols like & or white spaces): .. code-block:: python >>> # This str wont work in the terminal without quotes (because of the &) >>>...
def string_converter(value): """To deal with Courtney CTD codes""" return value.split(":")[-1].strip()
def reverse(deck): """deal into new stack""" return list(reversed(deck))
def validate_boolean(b): """ Convert b to a boolean or raise a ValueError. """ try: b = b.lower() except AttributeError: pass if b in ('t', 'y', 'yes', 'on', 'true', '1', 1, True): return True elif b in ('f', 'n', 'no', 'off', 'false', '0', 0, False): return F...
def concat_link(*args, token=None): """Helper to concat""" link = "http://" for i in args: link += i if token: link += "?token=" + str(token) return link
def get_prime_factors(num: int = 600851475143) -> list: """Get prime factor(s) of a number. Args: num (int, optional): the number, for which the prime factor(s) is to be found. Defaults to 600851475143. Returns: list: list of prime factor(s). """ prime_factors: list = [...
def find_dict(L, key, val, default=None): """Find first matching dictionary in a list of dictionaries. :param L: list of dictionaries :type L: list of dictionaries :param key: key to match for value :type key: valid dictionary key to index on :param val: value to compare against :type val: ...
def is_tainted(split_line_of_utt): """Returns True if this line in ctm-edit is "tainted.""" return len(split_line_of_utt) > 8 and split_line_of_utt[8] == 'tainted'
def get_translation_suggestions(vocabulary_article, translation_suggestions): """Returns XML with translate suggestions""" res = [] if len(vocabulary_article['def']) != 0: for article in vocabulary_article['def']: for translation in article['tr']: if 'ts' in article.keys(...
def gcd(a, b): """Returns the greatest common divisor of a and b. Should be implemented using recursion. >>> gcd(34, 19) 1 >>> gcd(39, 91) 13 >>> gcd(20, 30) 10 >>> gcd(40, 40) 40 """ big = max(a, b) small = min(a, b) if big % small == 0: return small ...
def prioritize_file_types(k): """ Give a proper priority to certain file types when sorting """ # BN databases should always go first if k.endswith('.bndb'): return 0 # Definition files matter more than raw files if any(k.endswith(e) for e in ('.def', '.idt')): return 5 return 10
def the_same_tool(tool_1_info, tool_2_info): """ Given two dicts containing info about tools, determine if they are the same tool. Each of the dicts must have the following keys: `name`, `owner`, and (either `tool_shed` or `tool_shed_url`). """ t1ts = tool_1_info.get('tool_shed', tool_1_inf...
def convert_or_none(value, type_): """Return the value converted to the type, or None if error. ``type_`` may be a Python type or any function taking one argument. >>> print convert_or_none("5", int) 5 >>> print convert_or_none("A", int) None """ try: return type_(value) ex...
def normalize_file_permissions(st_mode): """ Normalizes the permission bits in the st_mode field from stat to 644/755 Popular VCSs only track whether a file is executable or not. The exact permissions can vary on systems with different umasks. Normalising to 644 (non executable) or 755 (executable)...
def format(text, *args, **kw): """ Format a string using the string formatting operator and/or :func:`str.format()`. :param text: The text to format (a string). :param args: Any positional arguments are interpolated into the text using the string formatting operator (``%``). If no posi...
def serialize_modifiers(modifiers): """serialize_modifiers.""" lines = "" if modifiers: for modifier in modifiers: line = "attribute_in:%s attribute_out:%s reduction:%s" % \ (modifier.attribute_in, modifier.attribute_out, modifie...
def parse_cgminer_bracket_format_str(bs): """ this only parse to str:str pair, it will not break down value str. If needed, please ref parse_cgminer_bracket_format_str_into_json """ import re result = {} items = re.findall(r"\s*([^ \[\]]+)\[([^\[\]]+)\]\s*", bs) for item in items: ...
def merge(*dicts): """ Merge a collection of dictionaries >>> merge({1: 'one'}, {2: 'two'}) {1: 'one', 2: 'two'} Later dictionaries have precedence >>> merge({1: 2, 3: 4}, {3: 3, 4: 4}) {1: 2, 3: 3, 4: 4} """ rv = dict() for d in dicts: rv.update(d) return rv
def quote_es_field_name(name): """Elasticsearch does not allow `.` in field names.""" return name.replace('.', '__DOT__')
def make_image_carousel(columns): """ Image Carousel: reference - https://developers.worksmobile.com/jp/document/100500809?lang=en Request URL https://apis.worksmobile.com/r/{API ID}/message/v1/bot/{botNo}/message/push POST (Content-Type: application / json; charset = UTF-8) ...
def get_header_string(search_category, search_string): """Returns personalized heading text depending on the passed search category.""" header_string = "" csv_title_index = 0; csv_year_index = 1; csv_author_index = 2 if search_category == csv_title_index: header_string = "\n\nResults books with titles containing:...
def get_bucket_key(s3_loc): """ From a full s3 location, return the bucket and key """ if not s3_loc.startswith('s3://'): raise Exception(f"{s3_loc} is not a properly formatted key") bucket = s3_loc.split('/')[2] key = '/'.join(s3_loc.split('/')[3:]) return bucket, key
def concat_or_filters(filters): """Task for an OR filter list For more information see the API documentation :param filters: the filter list to be concat :type filters: List :return: A Json filter formated :rtype: Dict """ return {"operator": "Or", "filters": filters}
def merge_two_dicts(x, y): """ merges two dictionaries -- shallow """ z = x.copy() z.update(y) return z
def _decode(std): """Decodes the bytes-like output of a subprocess in UTF-8. This private function is wrapped in :func:`call_commandline()`. Args: std (bytes-like): The ``stdout`` or ``stderr`` (or whatever) of a subprocess. Returns: A list of decoded stri...
def dtype_to_json_type(dtype) -> str: """Convert Pandas Dataframe types to Airbyte Types. :param dtype: Pandas Dataframe type :return: Corresponding Airbyte Type """ if dtype == object: return "string" elif dtype in ("int64", "float64"): return "number" elif dtype == "bool": ...
def rating_identifier(fields): """Generates a string that would be found in the contents of an existing rating document""" identifier = '' relevant_fields = ['User msin', 'Job id', 'Rater msin'] for field in fields: if field['label'] in relevant_fields: identifier += field['label'] + ": " + field['value'] + "\...
def encrypt(txt, encode=True, rotation=21): """ by Daniel Bezerra dos Santos... dbsantos1981@gmail.com This function implements a simple version of "Caesar's Cryptography" :param txt: text to be encrypted or decrypted :param encode: if encode is true, it will encrypt. Otherwise it will decrypt ...
def roman_numerals_encoder(n): """ n: positive integer return: n translated into roman numerals """ roman_numerals_list = ['M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I'] roman_steps_list = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1] roman_numerals = [] if n > 0: fo...
def my_get_indexes(predicates, objects): """ input is predicates and objects returns the indexes of objects in predicates and -1 if it doesnt exist """ #return [predicates.index(object) for object in objects if object in predicates else -1] return [predicates.index(object) if object in predicates else -1 for obje...
def build_road_network(edges, allow_bidirectional=False): """Construct the directional road graph given a list of edges.""" graph = {} # Graph with bidirectional edges if allow_bidirectional: for edge in edges: graph.setdefault(edge.start_node, []).append(edge) graph.set...
def autocorrelate_negative(autocorrelation): """ Finds last positive autocorrelation, T. """ T = 1 for a in autocorrelation: if a < 0: return T - 1 T += 1 return T
def _CreateGroupLabel(messages, assignment_group_labels): """Create guest policy group labels. Args: messages: os config guest policy api messages. assignment_group_labels: List of dict of key: value pair. Returns: group_labels in guest policy. """ group_labels = [] for group_label in assignme...
def _async_request_completed(payload): """Looks into an async response payload to see if the requested job has finished.""" if payload["status"] == "COMPLETED": return True if payload["status"] == "ERROR": return True return False
def sum_freq(wl1, wl2): """ Input wavelength in nm """ return wl1 * wl2 / (wl1 + wl2)
def get_campaign_link(name, service): """ Return a link to a campaign in a given service """ if service == 'mc': return 'https://cms-pdmv.cern.ch/mcm/campaigns?prepid=%s' % (name) if service == 'rereco_machine': return 'https://cms-pdmv.cern.ch/rereco/subcampaigns?prepid=%s' % (name)...
def caselessSort(alist): """Return a sorted copy of a list. If there are only strings in the list, it will not consider case. """ try: return sorted(alist, key=lambda a: (a.lower(), a)) except TypeError: return sorted(alist)
def check_not_finished_board(board: list): """ Check if skyscraper board is not finished, i.e., '?' present on the game board. Return True if finished, False otherwise. >>> check_not_finished_board(['***21**', '4?????*', '4?????*', '*?????5', '*?????*',\ '*?????*', '*2*1***']) False >>> ch...
def vadd(*args): """Adds vectors "x", "y", ... together.""" assert len(args) >= 2 n = len(args[0]) rest = args[1:] for x in args: assert len(x) == n R = [] for i in range(n): s = args[0][i] for x in rest: s += x[i] R.append(s) return R
def ext_block(var, nblocks, ratio=3): """ Extend some variables defined in the bottom block only Input ----- var: float or int Variable in the bottom block nblocks: int Number of blocks, often 2 ratio: float ratio between upper block to the block below Return ...
def tied_at_rank_string(rank): """ Because we only work with numbers less than 10, we only have to write out casing for the simplest of numbers. """ return ( "(tied for 1st)" if rank == 1 else "(tied for 2nd)" if rank == 2 else "(tied for 3rd)" if rank == ...
def get_result_count(json_data): """Gets the number of results from @odata.count in the response""" return json_data['@odata.count']
def flipper(x: float) -> float: """Convert Tanimoto similarity into a distance Args: x (float): Tanimoto similarity Returns: float: Distance """ return x * -1 + 1
def pressure_medium(p0, pk): """Medium pressure psr :param p0: Absolute pressure at the beginning of the pipe section, Pa :param pk: Absolute pressure at the end of the pipe section, Pa :return: Medium absolute pressure, Pa """ return (2 / 3) * (p0 + (pk ** 2) / (p0 + pk))
def to_int_float_or_string(s): """ Convert string to int or float if possible If s is an integer, return int(s) >>> to_int_float_or_string("3") 3 >>> to_int_float_or_string("-7") -7 If s is a float, return float(2) >>> to_int_float_or_string("3.52") 3.52 >>> to_int_float_or_str...
def collate_single(batch): """ collate function for the ObjectDetectionDataSetSingle. Only used by the dataloader. """ x = [sample['x'] for sample in batch] x_name = [sample['x_name'] for sample in batch] return x, x_name
def factorial(n: int) -> int: """This function is for calculating n-factorial element Args: n (int): input, which element you want to calculate Returns: int: calculated n-factorial element """ if n < 1: return 1 else: return n * factorial(n - 1)
def mostProfitableCompanyRecursion(companyList, listIndex): """Recursive call determines which company ended with the most money""" if (listIndex > 0): return max(companyList[listIndex], mostProfitableCompanyRecursion(companyList, listIndex - 1)) else: return companyList[listIndex]
def response_plain_text_ga(output, continuesession): """ create a simple json plain text response """ return { "payload": { 'google': { "expectUserResponse": continuesession, "richResponse": { "items": [ { ...
def nice_time(time): """ Format a time in seconds to a string like "5 minutes". """ if time < 15: return 'moments' if time < 90: return '%d seconds' % time if time < 60 * 60 * 1.5: return '%d minutes' % (time / 60.) if time < 24 * 60 * 60 * 1.5: return '%d hours' ...
def uniq(lst): """ this is an order-preserving unique """ seen = set() seen_add = seen.add return [x for x in lst if not (x in seen or seen_add(x))]
def getThresholds(settings): """Given a FEAT settings dictionary, returns a dictionary of ``{stat : threshold}`` mappings, containing the thresholds used in the FEAT statistical analysis. The following keys will be present. Threshold values will be ``None`` if the respective statistical thresholdin...
def get_unique_list(input_list): """ Remove duplicates in list and retain order :param input_list: any list of objects :return: input_list without duplicates :rtype: list """ rtn_list_unique = [] for value in input_list: if value not in rtn_list_unique: rtn_list_uniqu...
def compute_zone(value, info): """ This function returns an integer depending on the threshold zone on which a value is located. """ zone = 0 if value <= info['low_warning_threshold']: zone = -2 elif value <= info['low_caution_threshold']: zone = -1 elif value <= info['high_...
def find_double_newline(s): """Returns the position just after a double newline in the given string.""" pos1 = s.find(b'\n\r\n') # One kind of double newline if pos1 >= 0: pos1 += 3 pos2 = s.find(b'\n\n') # Another kind of double newline if pos2 >= 0: pos2 += 2 if pos1 >= 0: ...
def isinteger(x): """ determine if a string can be converted to an integer """ try: a = int(x) except ValueError: return False else: return True
def get_non_null_value(value: str, default_value: str): """Return non null value for the value by replacing default value.""" return default_value if (value is None or value.strip() == '') else value
def str_remove_line_end(chars): """Remove one Line End from the end of the Chars if they end with a Line End""" line = (chars + "\n").splitlines()[0] return line
def elapar_hs2delta(vp1, vs1, ro1, vp2, vs2, ro2): """ Elastic parameterization, convert half-space to delta model. The half-space model has two layers, upper layers has P-wave velocity, S-wave velocity, density denoted by vp1, vs1, ro1, respectively. The lower layer has vp2, vs2, ro2. The delt...
def normalize_text(text): """Return turn in most comparative formatting - Strip whitespace - Lower case - Spaces, not "_" """ return str(text).strip().lower().replace("_", " ")
def unique_username(obj): """ Return a unique username for a test user. Return a randomly generated username that is guaranteed to be unique within a given test run. Uniqueness is necessary because usernames must be unique in the DB and generating random usernames in a not-guaranteed-to-be-unique ...
def find_numerator(cents, denom): """ This is the algebraic inverse of cents_from_interval(). """ return denom * 2 **(cents/1200)
def tree_unflatten(flat, tree): """Unflatten a list into a tree given the tree shape as second argument. Args: flat: a flat list of elements to be assembled into a tree. tree: a tree with the structure we want to have in the new tree. Returns: A pair (new_tree, rest_of_flat) where the new tree that ...
def arg_return_greetings(name): """ function which accepts argument and returns value :param name: :return: """ message = F"Hello {name}" return message
def gravity(z, g0, r0): """Relates Earth gravity field magnitude with the geometric height. Parameters ---------- z: float Geometric height. g0: float Gravity value at sea level. r0: float Planet/Natural satellite radius. Returns ------- g: float Gra...
def args_with_defaults(default_args, cli_args): """Inserts the specified default flags into the job submission. If a flag has already specified through CLI, it is not overwritten with the default-specified parameter.""" final_args = cli_args # Loop through default args. If not in CLI args already, t...
def get_keywords_from_topic(topic): """ Helper function for breaking up a phrase into keywords Args: topic: The phrase we'll break up Returns: List of words/phrases that are substrings of the topic. """ old_topic = topic topic = topic.strip("?").strip(".").strip("!...
def lsame(ca, cb): """LAPACK auxiliary routine (version 2.0) Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University September 30, 1994 Python replacement by K. KISHIMOTO (korry@users.sourceforge.net) Purpose ======= lsame returns .TRUE. if CA...
def pascalcase(value: str) -> str: """capitalizes the first letter of each _-separated component. This method preserves already pascalized strings.""" components = value.split("_") if len(components) == 1: return value[0].upper() + value[1:] else: components[0] = components[0][0].up...
def calc_accuracy(result_dict)->float: """ Count accuracy Args: result_dict: result dictionary Returns: accuracy """ right_num = 0 error_num = 0 for name, catagory in result_dict.items(): if (eval(name) < 1000 and catagory == False) or (eval(name) >= 1000 and catagory =...
def nextmonth(month,year): """return YYYYMMDD str for first day of next month, given month, year as strings""" month = int(month)+1 if month==13: month=1 year = str(int(year)+1) month = '{0:02d}'.format(month) return year+month+'01'