content
stringlengths
42
6.51k
def gcd_fast(a: int, b: int) -> tuple: """ GCD using Euler's Extended Algorithm generalized for all integers of the set Z. Including negative values. :param a: The first number. :param b: The second number. :return: gcd,x,y. Where x and y are bezout's coeffecients. """ gcd=0 x=0 y=0 x=0 """ if a < 0: s...
def first_half(dayinput): """ first half solver: """ lines = dayinput.split('\n') registers = {} max_max = 0 for line in lines: register = line.split(' ')[0] amount = int(line.split(' ')[2]) if register not in registers: registers[register] = 0 equ...
def config_tag(iteration=1): # type: (int) -> str """Marks this field as a value that should be saved and loaded at config Args: iteration: All iterations are sorted in increasing order and done in batches of the same iteration number """ tag = "config:%d" % iteration return...
def unix_epoch(epoch): """Converts embedded epoch since 2000-01-01 00:00:00 to unix epoch since 1970-01-01 00:00:00 """ return str(946684800 + epoch)
def endSwap(b): """ change endianess of bytes """ if type(b) is bytes: return bytes(reversed(b)) elif type(b) is bytearray: return bytearray(reversed(b)) else: assert False,"Type must be byte or bytearray!"
def get_ship_name(internal_name): """ Get the display name of a ship from its internal API name :param internal_name: the internal name of the ship :return: the display name of the ship, or None if not found """ internal_names = { "adder": "Adder", "alliance-challenger": "Allianc...
def cdb_hash(buf): """CDB hash function""" h = 5381 # cdb hash start for c in buf: h = (h + (h << 5)) & 0xFFFFFFFF h ^= c return h
def _filter_size_out(n_prev, filter_size, stride, padding): """Calculates the output size for a filter.""" return ((n_prev + 2 * padding - filter_size) // stride) + 1
def make_sql_jinja2_filename(file_name: str) -> str: """ Add .sql.jinja2 to a filename. :param file_name: the filename without an extension. :return: the filename. """ return f'{file_name}.sql.jinja2'
def createPacketReport(packet_list): """ Takes as input a packet a list. Returns a dict containing a dict with the packet summary and the raw packet. """ report = [] for packet in packet_list: report.append({'raw_packet': str(packet), 'summary': str(packet.summary())}) ...
def to_str(obj): """ Turn the given object into a string. If the obj is None the result will be an empty string. @return a string representation of obj. If obj is None the string is empty. """ if obj is None: return "" return str(obj)
def format_keys(d, format_string): """ Creates a new dict with all keys from an original dict reformatted/mapped. :param d: a dict. :param format_string: a normal python format string (i.e. str().format() style). :return: a new dict (of the same type as the original) containing the original dict's ...
def ngrams(w_input, n): """ Generate a set of n-grams for more complex features """ output = [] for i in range(len(w_input) - n + 1): output.append(w_input[i: i + n]) return [''.join(x) for x in output]
def fix_ext_py(filename): """Given a .pyc filename converts it to the appropriate .py""" if filename.endswith('.pyc'): filename = filename[:-1] return filename
def manage_data_button(mission_id, testcase_id, number_of_attachments, as_button=False): """ Returns the text that should be displayed regarding attachments to a test case. """ return { 'mission_id': mission_id, 'test_detail_id': testcase_id, 'supporting_data_count': number_of_attachment...
def get_label(char): """Change character to a number between 0 and 25. A = 0 B = 1 ... Y = 24 Z = 25""" value = ord(char) - 65 return value
def formulas_to_string(formulas): """Convert formulas to string. Takes an iterable of compiler sentence objects and returns a string representing that iterable, which the compiler will parse into the original iterable. """ if formulas is None: return "None" return " ".join([str(for...
def isNull(s): """ Checks to see if this is a JSON null object """ if s == 'null': return True else: return False
def is_variant(call): """Check if a variant position qualifies as a variant 0,1,2,3==HOM_REF, HET, UNKNOWN, HOM_ALT""" if call == 1 or call == 3: return True else: return False
def get_or_default(arr, index, default_value=None): """ Get value at index from list. Return default value if index out of bound :type arr: list :param arr: List to get value from :type index: int :param index: Index to get value for :type default_value: Any :param default_value: Defaul...
def constr_container_process_head(xml_str, container, operation): """construct the container update string process """ xml_str += "<" + container + "s>\r\n" xml_str += "<" + container + " xc:operation=\"" + operation + "\">\r\n" return xml_str
def arrangements(n, max_jump=3): """ Calculate the number of permutations of N contiguous numbers, where the max jump is the maximum difference for a valid permutation. """ current = [0] perms = 0 end = n-1 while len(current) != 0: new = [] for c in current: i...
def get_cluster_sizes(clusters): """ Calculates all the sizes of a clusters list and returns it in a tuple in which the first element is the total number of elements, and the second a list containing the size of each cluster (maintaining the ordering). """ total_elements = 0 cluster_sizes = ...
def session(context_name="session", request=None, **kwargs): """Returns the session associated with the current request""" return request and request.context.get(context_name, None)
def get_toc_parameter_dict(definitions): """ Process the uframe toc['parameter_definitions'] list into a list of dict keyed by pdId. Return dict and pdids. """ result = {} pdids = [] if not definitions: return {} for definition in definitions: pdid = definition['pdId'] if...
def time_float_to_text(time_float): """Convert tramscript time from float to text format.""" hours = int(time_float/3600) time_float %= 3600 minutes = int(time_float/60) seconds = time_float % 60 return f'{hours}:{minutes:02d}:{seconds:05.2f}'
def change_ext(file, ext) : """ altera a extensao do arquivo file para ext """ return file[0:len(file)-4] + '.' + ext
def indg(x): """Return numbers with digit grouping as per Indian system.""" x = str(int(x)) result = x[-3:] i = len(x) - 3 while i > 0: i -= 2 j = i + 2 if i < 0: i = 0 result = x[i:j] + ',' + result return result
def parse_date(git_line: str) -> str: """ Return the author/committer date from git show output >>> parse_date('AuthorDate: Thu Jun 6 14:31:55 2019 +0300') 'Thu Jun 6 14:31:55 2019 +0300' """ date = git_line.split(":", 1)[1].strip() return date
def generate_hash(tmpstr): """Generate hash.""" hash_val = 1 if tmpstr: hash_val = 0 # pylint: disable=W0141 for ordinal in map(ord, tmpstr[::-1]): hash_val = ( (hash_val << 6) & 0xfffffff) + ordinal + (ordinal << 14) left_most_7 = hash_val & ...
def count_combination(visit_to_fid_to_sequence_type_to_filename, nb_augmented_images): """ Description: Counts the number of combinations for the T2, DWI and ADC images of a specific patient. Params: - visit_to_fid_to_sequence_type_to_filename: dictionary {'visit': {'fid': {'t2': [filenames], 'dwi':...
def _prepare_shape_for_expand_dims(shape, axes): """ Creates the expanded new shape based on the shape and given axes Args: shape (tuple): the shape of the tensor axes Union(int, tuple(int), list(int)): the axes with dimensions expanded. Returns: new_shape(tuple): the shape wit...
def alexnet_params(model_name): """ Map AlexNet model name to parameter coefficients. """ params_dict = { # Coefficients: dropout, res "alexnet": (0.2, 224), } return params_dict[model_name]
def add(x, y, **kwargs): """add""" print(kwargs) return x + y
def naivemult(x, y, base=10): """ Function to multiply 2 numbers using the grade school algorithm.""" if len(str(x)) == 1 or len(str(y)) == 1: return x*y else: n = max(len(str(x)),len(str(y))) # that's suboptimal, and ugly, but it's quick to write nby2 = n // 2 # spl...
def class_import_string(o): """Returns a fully qualified import path of an object class.""" return f'{o.__class__.__module__}.{o.__class__.__qualname__}'
def make_list(obj): """ :param it: :return: empty list if obj is None, a singleton list of obj is not a list, else obj """ if obj is None: return [] return obj if isinstance(obj, list) else [obj]
def capitalize_by_mapping(string: str) -> str: """ Capitalizes a string by mapping between a set of lowercase characters and a set of uppercase characters. :param string: an input string :return: the capitalized string """ lowercase = "abcdefghijklmnopqrstuvwxyz" uppercase = "ABCDEFGHIJ...
def _longest_line_length(text): """Return the longest line in the given text.""" max_line_length = 0 for line in text.splitlines(): if len(line) > max_line_length: max_line_length = len(line) return max_line_length
def _get_entities(run, **kwargs): """ Get BIDS-entities from run object """ valid = ['number', 'session', 'subject', 'acquisition', 'task_name'] entities = { r: v for r, v in run.items() if r in valid and v is not None } if 'number' in entities: entities['run'] =...
def side_of_line(l, p): """Returns on which side of line `l` point `p` lies. Line `l` must be a tuple of two tuples, which are the start and end point of the line. Point `p` is a single tuple. Returned value is negative, 0, or positive when the point is right, collinear, or left from the li...
def format_duration_ms(ms): """Format milliseconds (int) to a human-readable string.""" def _format(d): d = str(d) if len(d) == 1: d = '0' + d return d s = int(ms / 1000) if s < 60: return '00:{}'.format(_format(s)) m, s = divmod(s, 60) return '{}:{}...
def items_string(items_list): """Convert a list of Id, number pairs into a string representation. items_string(list((str, int))) -> str """ result = [] for itemid, num in items_list: result.append("{0}:{1}".format(itemid, num)) return ','.join(result)
def parse_extension(extension): """Parse a single extension in to an extension token and a dict of options. """ # Naive http header parser, works for current extensions tokens = [token.strip() for token in extension.split(';')] extension_token = tokens[0] options = {} for token in token...
def bresenham_line(x, y, x2, y2): """Brensenham line algorithm""" steep = 0 coords = [] dx = abs(x2 - x) if (x2 - x) > 0: sx = 1 else: sx = -1 dy = abs(y2 - y) if (y2 - y) > 0: sy = 1 else: sy = -1 if dy > dx: steep = 1 x,y = y,x dx,dy = dy,dx sx,sy = sy,sx d = (2 * dy) - dx for ...
def duplicar(valores): """duplica os valores em uma lista >>> duplicar([1, 2, 3, 4]) [2, 4, 6, 8] >>> duplicar([]) [] >>> duplicar('a', 'b', 'c') ['aa', 'bb', 'cc'] >>> duplicar([True, None]) Traceback (most recent call last): ... TypeError: unsupporte...
def _match_authorizables(base_authorizables, authorizables): """ Method to check if authorizables (entity in CDAP) is contained (the children) of base_authorizables If so, base_authorizables should be exactly the same as the leading part of authorizables :return: bool: True if match else False """ return au...
def add_search_filters(search, filters): """This helper method iterates through the filters and adds them to the search query""" result_search = search for filter_name in filters: if filter_name != 'page' and filter_name != 'sort': # .keyword is necessary for elastic search filt...
def deep_merge_in(dict1: dict, dict2: dict) -> dict: """Deeply merge dictionary2 into dictionary1 Arguments: dict1 {dict} -- Dictionary female dict2 {dict} -- Dictionary mail to be added to dict1 Returns: dict -- Merged dictionary """ if type(dict1) is dict and type...
def get_tags_gff(tagline): """Extract tags from given tagline in GFF format""" tags = dict() for t in tagline.split(';'): tt = t.split('=') tags[tt[0]] = tt[1] return tags
def is_triangle(sides): """ Check to see if this is a triangle :param sides: list[*int] - the length of the three sides of a triangle? :return bool - whether it is a triangle or not >>> is_triangle([1, 2, 3]) True >>> is_triangle([0, 0, 0]) False All sides have to be of length > ...
def validate_params(params): """assert that json contains all required params""" keys = params.keys() result = True if not "artist" in keys: print('An artist must be provided in jobs_jukebox job params') result = False if not "genre" in keys: print('A genre must be provided i...
def _has_relation_and_head(row): """Does this token participate in a relation?""" return row[-1] != "0" and row[-2] != "0"
def replace_newline(text): """Just used for debugging, make sure to not use this elsewhere because it is dangerous since it turns unicode into non-unicode.""" return str(text).replace("\n", '\\n')
def add_rowcount_limit(sql, limit=300, delimeter=';'): """ Sets the rowcount limit. Can be used in lieue of adding a `TOP` clause for databases that support it. Args: sql (str): The sql statement. limit (int): The row number limit. delimiter (str): The sql statement delimeter. ""...
def get_mismatch_type(a_base, b_base): """ For two given nucleotide values (A, T, C, G, and -) representing a mismatch or indel, return the type of mismatch. For substitutions, return transition or transversion. Otherwise, return insertion or deletion. """ type_string = "".join(sorted((a_base, b...
def looks_like_a_license(text): """ Check if TEXT is likely to be a license header. Note that TEXT does not contain initial /final horizontal rules, but does contain comment markers in each non-empty line. """ return 'Copyright' in text
def ris_defaultValue_get(fieldsTuple): """ params: fieldsTuple, () return: fieldVaule_dict, {} """ # ris_element = fieldsTuple[0] if len(fieldsTuple[1]) != 0: default_value = fieldsTuple[1][0] else: default_value = [] fieldValue_dict = {} fieldValue_dict[ris_eleme...
def importModule(name): """ Just a copy/paste of the example my_import function from here: http://docs.python.org/lib/built-in-funcs.html """ mod = __import__(name) components = name.split('.') for comp in components[1:]: mod = getattr(mod, comp) return mod
def expand_var(v, env): """ If v is a variable reference (for example: '$myvar'), replace it using the supplied env dictionary. Args: v: the variable to replace if needed. env: user supplied dictionary. Raises: Exception if v is a variable reference but it is not found in env. """ if len(v...
def is_tool(name): """Check whether `name` is on PATH and marked as executable.""" # from whichcraft import which from shutil import which return which(name) is not None
def get_item(obj, key): """ Obtain an item in a dictionary style object. :param obj: The object to look up the key on. :param key: The key to lookup. :return: The contents of the the dictionary lookup. """ try: return obj[key] except KeyError: return None
def moments_get_skew(m): """Returns the skew from moments.""" return m['mu11']/m['mu02']
def list_public_methods(obj): """Returns a list of attribute strings, found in the specified object, which represent callable attributes""" return [ member for member in dir(obj) if not member.startswith('_') and hasattr(getattr(obj, member), '__call__') ]
def revalueOutlier(x,mean,stddev,alpha=0.95): """ replace null and outlier with mean """ if abs(float(x)-mean)<=1.96*stddev: return float(x) else: return float(mean)
def get_function_name(f): """ Get name for either a function or a functools.partial. """ try: return f.__name__ except AttributeError: pass # this works for functools.partial objects try: return f.func.__name__ except AttributeError: pass return type...
def make_label(expr, node_type): """ Make a graph label to replace named variable values and variable functions. If it is a variable function (node_type = 'internal'), the label is '<var_func>'. If it is a variable value (node_type = 'leaf'), the label is: <var_ev> if the variable name starts wi...
def decode_encap_ethernet(value): """Decodes encap ethernet value""" return "ethernet", int(value, 0)
def qname_to_extended(qname, namespaces): """ Maps a QName in prefixed format or a local name to the extended QName format. Local names are mapped if *namespaces* has a not empty default namespace. :param qname: a QName in prefixed format or a local name. :param namespaces: a map from prefixes to n...
def filter_point(x, y, xlower, xupper, ylower, yupper): """ Used in case we want to filter out contours that aren't in some area. Returns True if we _should_ ignore the point. """ ignore = False if (x < xlower or x > xupper or y < ylower or y > yupper): ignore = True return ignore
def remove_first_word(text): """Given a string, remove what is found before the first space""" l = text.split(" ", 1) return l[1] if len(l) > 1 else ""
def _clean_table_name(table_name): """Cleans the table name """ return table_name.replace("'","''")
def progress_bar(progress, size = 20): """ Returns an ASCII progress bar. :param progress: A floating point number between 0 and 1 representing the progress that has been completed already. :param size: The width of the bar. .. code-block:: python >>> ui.progress_bar(0.5, 10) ...
def get_config_option(option_name, options, optional=False): """Given option_name, checks if it is in app.config. Raises ValueError if a mandatory option is missing""" option = options.get(option_name) if option is None and optional is False: err = "'{0}' is mandatory and is not set in ~/.resilient...
def calculateBBCenter(bb): """ **SUMMARY** Calculates the center of the given bounding box **PARAMETERS** bb - Bounding Box represented through 2 points (x1,y1,x2,y2) **RETURNS** center - A tuple of two floating points """ center = (0.5*(bb[0] + bb[...
def _bool(raw_bool): """ Parse WPS boolean string.""" return raw_bool == "true"
def is_self(user, other): """ Check whether `user` is performing an action on themselves :param user User: The user to check :param other User: The other user to check """ if other is None: return True return user == other
def string_to_array(str_val, separator): """ Args str_val : string value separator : string separator Return List as splitted string by separator after stripping whitespaces from each element """ if not str_val: return [] res = str_val.split(separator) return ...
def namify_config(obj, **cfg): """ Prepend everything in cfg's keys with obj.name_, and remove entries where the value is None. """ return {obj.name + "_" + k: v for k, v in cfg.items() if v is not None}
def parse_node_coverage(line): # S s34 CGTGACT LN:i:7 SN:Z:1 SO:i:122101 SR:i:0 dc:f:0 # "nodeid","nodelen","chromo","pos","rrank",assemb """ Parse the gaf alignment Input: line from gaf alignment Output: tuple of nodeid, nodelen, start_chromo, start_pos, coverage """ l...
def _is_primary(s): """Indicates whether a sequence is a part of the primary assembly. Args: s (dict): A dictionary of sequence data, e.g. those in assembly['sequences']. Returns: bool: True if the sequence is part of the primary assembly, False otherwise. Examples: ...
def get_scenario_number_for_tag(tag): """ only for logging in tensorboard - gets scenario name and retrieves the number of the scenario Arguments: tag String - string with the scenario name Return: int - number of the scenario """ scenario_dict = { "sc1_coop": 1, ...
def matrix_sum(mat_a: list, mat_b: list): """ Compute the sum of two compatible matrices. """ n: int = len(mat_a) if n != len(mat_b): print("ERROR: cannot add incompatible matrices. Stop.") return None results = [] for col in range(n): column = [] for row in r...
def wrapper(field, wrap_txt): """ Wrap a field in html. """ answer = "<%s>" % wrap_txt answer += field answer += "</%s>" % wrap_txt return answer
def lerp(a: float, b: float, t: float) -> float: """ Linearly interpolates (unclamped) between a and b with factor t. Acts such that `lerp(a, b, 0.0)` returns `a`, and `lerp(a, b, 1.0)` returns `b`. """ return (1 - t) * a + t * b
def _get_ngrams(n, text): """Calcualtes n-grams. Args: n: which n-grams to calculate text: An array of tokens Returns: A set of n-grams """ ngram_set = set() text_length = len(text) max_index_ngram_start = text_length - n for i in range(max_index_ngram_st...
def parse_json_body(data, basekey=None): """ Takes nested json object and returns all key names associated with them. Parameters: data(json): JSON object that may or may not have nested data structures in it. Returns: list: List of dictionaries that are key:value pairs. """ ...
def convert_bounding_box_to_xyxy(box: dict) -> list: """ Converts dictionary representing a bounding box into a list of xy coordinates Parameters ---------- box: dict Bounding box in the format {x: x1, y: y1, h: height, w: width} Returns ------- bounding_box: dict List ...
def get_investigation_data(investigation_response): """Get investigation raw response and returns the investigation info for context and human readable. Args: investigation_response: The investigation raw response Returns: dict. Investigation's info """ investigation_data = { ...
def get_pos_constants(tag: str): """ Static function for tag conversion :param tag: The given pos tag :return: The corresponding letter """ if tag.startswith("J"): return "a" elif tag.startswith("V"): return "v" elif tag.startswith("N"): return "n" elif tag....
def create2D(rowCount, colCount, value=None): """ Create and return a 2D array having rowCount rows and colCount columns, with each element initialized to value. """ a = [None] * rowCount for row in range(rowCount): a[row] = [value] * colCount return a
def format_lines(text): """Returns list of list of ints""" return [[int(i) for i in str.split(line, 'x')] for line in str.split(text)]
def _BuildForceFieldTrialsSwitchValue(trials): """Generates --force-fieldtrials switch value string. This is the opposite of _ParseForceFieldTrials(). Args: trials: A list of _Trial objects from which the switch value string is generated. """ return ''.join('%s%s/%s/' % ( '*' if trial.st...
def to_base36(obj): """ Converts an integer to base 36 (a useful scheme for human-sayable IDs). :param obj: int :return: str """ if obj < 0: raise ValueError('must supply a positive integer') alphabet = '0123456789abcdefghijklmnopqrstuvwxyz' converted = [] while obj != 0: ...
def pre_text(string, lang=None): """ Encapsulate a string inside a Markdown <pre> container """ s = "```{}```" if lang is not None: s = s.format(lang+"\n{}") return s.format(string.rstrip().strip("\n").replace("\t", ""))
def py2_replace_version(argv): """ Workaround for Python 2.7 argparse, which does not accept empty COMMAND If `-V` or `--version` present and every argument before it begins with `-`, then convert it to `version. """ try: ind = argv.index('--version') except ValueError: try...
def touch(name): """Create a file and return its name.""" with open(name, 'w') as f: return f.name
def add_prefix(key, prefix): """Add prefix to key.""" if prefix: key = "{}_{}".format(prefix, key) return key
def uniq(ls): """ uniqify a list """ return list(set(ls))
def cup_vs_cups(left, right): """ Simple type error. """ return "Cup can only witness adjunctions between simple types. "\ "Use Diagram.cups({}, {}) instead.".format(left, right)