content
stringlengths
42
6.51k
def display_seconds(seconds: int, granularity: int = 1): """Display seconds as a string in hours, minutes and seconds Args: seconds: number of seconds to convert granularity: level of granularity of output Returns: string containing seconds in hours, minutes and seconds...
def calc_type(a: int, b: int, res: int) -> str: """Find the calculation type by the result. Examples: >>> assert calc_type(10, 2, 5) == 'division' """ return { a - b: 'subtraction', a + b: 'addition', a / b: 'division', a * b: 'multiplication', }[res]
def np_list_remove(cols, colsremove, mode="exact"): """ """ if mode == "exact": for x in colsremove: try: cols.remove(x) except BaseException: pass return cols if mode == "fuzzy": cols3 = [] for t in cols: ...
def average(values): """calculates average from a list""" try: return float(sum(values) / len(values)) except ZeroDivisionError: return 0
def find_ar_max(_ar, _ib=0, _ie=-1, _min=False): """ Finds array (or list) maximum (or minimum), index and value :param _ar: array (or list) to find max. or min. :param _ib: array index to start search :param _ie: array index to finish search :param _min: switch specifying that minimum (rather ...
def mutable_two(nums): """ Uses built-in max() method and extra storage. """ if len(nums) < 2: raise ValueError('Must have at least two values') idx = max(range(len(nums)), key=nums.__getitem__) my_max = nums[idx] del nums[idx] second = max(nums) nums.insert(idx, my_max) ...
def indent_lines( text: str ) -> str: """Indent the lines in the specified text.""" lines = text.splitlines() indented_lines = [f' {line}' for line in lines] return '\n'.join(indented_lines)
def divide(n, iterable): """split an iterable into n groups, per https://more- itertools.readthedocs.io/en/latest/api.html#grouping. :param int n: Number of unique groups :param iter iterable: An iterable to split up :return: a list of new iterables derived from the original iterable :rtype: li...
def _create_stage_table_command(table_name, target_table, selected_fields="*"): """ Create an redshift create temporary table command. Notes: - CREATE TABLE AS command does not inherits "NOT NULL" - CREATE TABLE LIKE statement also inherits sort key, distribution key. But the mai...
def parse_create_table(sql): """ Split output of SHOW CREATE TABLE into {column: column_spec} """ column_types = {} for line in sql.splitlines()[1:]: # first line = CREATE TABLE sline = line.strip() if not sline.startswith("`"): # We've finished parsing the columns ...
def in_seconds(days=0, hours=0, minutes=0, seconds=0): """ Tiny helper that is similar to the timedelta API that turns the keyword arguments into seconds. Most useful for calculating the number of seconds relative to an epoch. >>> in_seconds() 0 >>> in_seconds(hours=1.5) 5400 >>> in_sec...
def sextodec(xyz, delimiter=None): """Decimal value from numbers in sexagesimal system. The input value can be either a floating point number or a string such as "hh mm ss.ss" or "dd mm ss.ss". Delimiters other than " " can be specified using the keyword ``delimiter``. """ divisors = [1, 60.0, 3600...
def char_preprocess(texto, chars_inserted = []): """ DESCRIPTION: Normalizes some characters and adds . to headings INPUT: texto <string> - Text to be treated chars_inserted <list> - Positions of the chars inserted in the text OUTPUT: Returns the processed text """ #'.' = 46 #'\t'...
def _offset_rounding_error(figure): """ """ fig = [] pre_part = [] for line in figure: if not pre_part == []: fig.append((pre_part[3], line[1], line[2], line[3])) else: fig.append(line) pre_part = line return fig
def lines_to_text(receipt_lines): """ :param receipt_lines: takes a dictionary as input, where the key is a line_id and the value are objects containing the element text and bounding polygon :return: A list of text strings concatenated for each line, instead of goo...
def node_dict(nodes): """ :param nodes: :return: dict of frozenset(labels) to list(nodes) """ d = {} for node in nodes: key = frozenset(node.labels) d.setdefault(key, []).append(node) return d
def sizeof_fmt(num, suffix='B'): """ Converts byte size to human readable format """ for unit in ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi']: if abs(num) < 1024.0: return "%3.1f%s%s" % (num, unit, suffix) num /= 1024.0 return "%.1f%s%s" % (num, 'Yi', suffix)
def compare_users(user1, user2): """Comparison util for ordering user search results.""" # Any verified user is ranked higher if user1["is_verified"] and not user2["is_verified"]: return -1 if user2["is_verified"] and not user1["is_verified"]: return 1 return 0
def is_float(string): """ is the given string a float? """ try: float(string) except ValueError: return False else: return True
def post_process_remote_resources(resources): """ Process resources list from uframe before returning for display (in UI). """ try: if not resources: return resources for resource in resources: if '@class' in resource: del resource['@class'] re...
def to_asciihex(b): """ Convert raw binary data to a sequence of ASCII-encoded hex bytes, suitable for import via COPY .. CSV into a PostgreSQL bytea field. """ return '\\x'+''.join('%.2x' % ord(x) for x in b)
def asp_convert(string): """ Convert the given string to be suitable for ASP. Currently this means replacing - with _. It is a bit unsafe in that if name exist that are identical except one has a - and one has a _ in the same place, then this wont catch it, but if you do that stuff you. ...
def etag_matches(etag, tags): """Check if the entity tag matches any of the given tags. >>> etag_matches('"xyzzy"', ['"abc"', '"xyzzy"', 'W/"woof"']) True >>> etag_matches('"woof"', ['"abc"', 'W/"woof"']) False >>> etag_matches('"xyzzy"', ['*']) True Note that...
def fpr_score(conf_mtx): """Computes FPR (false positive rate) given confusion matrix""" [tp, fp], [fn, tn] = conf_mtx r = tn + fp return fp / r if r > 0 else 0
def separate_seq_and_el_data(line): """ Takes a string containing a nucleotide sequence and its expression level (el) - tab separated - and returns the sequence as a string and the expression level as a float. Args: ----- line (str) -- the input line containing the sequence and ...
def mem_format(memory, ratio=1.0): """Convert memory in G to memory requirement. Args: memory: Memory size in G. ratio: The percent that can be used. Returns: Formatted string of memory size if memory is valid, None otherwise. """ try: memory = float(memory) exc...
def compOverValueTwoSets(setA={1, 2, 3, 4}, setB={3, 4, 5, 6}): """ task 0.5.9 comprehension whose value is the intersection of setA and setB without using the '&' operator """ return {x for x in (setA | setB) if x in setA and x in setB}
def replace(original, old_word, new_word): """ If new_word is in original, this function will replace old_word with new_word. """ ans = '' for i in range(len(original)): if new_word == original[i]: ans += new_word else: ans += old_word[i] return ans
def extract_file_name(line: str): """ Extract the file name from a line getting by a line of string that contains a directory like `/path/to/file`, where `file` will be extracted. :param line: A line of string :return: The extracted tuple of absolute path and filename """ start_idx = line.rf...
def IsStringInt(string_to_check): """Checks whether or not the given string can be converted to a integer. Args: string_to_check: Input string to check if it can be converted to an int. Returns: True if the string can be converted to an int. """ try: int(string_to_check) return True excep...
def fizz_buzz(int_number): """ Return fizz if number is a multiple of 3 Return buzz if number is a multiple of 5 Return fizzbuzz if number is a multiple of 3 and 5 Else return the number If the number is NOT a number, then raise a ValueError """ # don't work with non-numeric input if...
def doc2str(document): """ document: list of list [n_sent, n_word] """ document = [" ".join(d) for d in document] return "\n".join(document)
def capturing(pattern): """ generate a capturing pattern :param pattern: an `re` pattern :type pattern: str :rtype: str """ return r'({:s})'.format(pattern)
def bold_large_p_value(data: float, format_string="%.4f") -> str: """ Makes large p-value in Latex table bold :param data: value :param format_string: :return: bolded values string """ if data > 0.05: return "\\textbf{%s}" % format_string % data return "%s" % format_string % d...
def check_clockwise(vertices): """Checks whether a set of vertices wind in clockwise order Adapted from http://stackoverflow.com/questions/1165647/how-to-determine-if-a-list-of-polygon-points-are-in-clockwise-order Args: vertices (list): A list of [x,y] vertices Returns: bool indicati...
def _add_missing_parameters(flattened_params_dict): """Add the standard etl parameters if they are missing.""" standard_params = ['ferc1_years', 'eia923_years', 'eia860_years', 'epacems_years', 'epacems_states'] for ...
def append_update_post_field_to_posts_list(d_included, l_posts, post_key, post_value): """Parse a dict and returns, if present, the desired value. Finally it updates an already existing dict in the list or add a new dict to it :param d_included: a dict, as returned by res.json().get("included", {}) :ty...
def get_stat_name(stat): """ Returns the stat name from an integer """ if stat == 2: return "attackdamage" elif stat == 10: return "maximumhealth"
def is_callable(value): """Returns whether the value is callable.""" return hasattr(value, '__call__')
def is_receiver(metric): """Is interface ``metric`` a receiver? :param dict metric: The metric. :rtype: :py:class:`bool` """ return metric.get("name", "").endswith("rx")
def acceptable_word(word, stopwords): """Checks conditions for acceptable word: length, stopword.""" accepted = bool(2 <= len(word) <= 40 and word.lower() not in stopwords) return accepted
def sort_by_value(d,reverse=False): """ One of many ways to sort a dictionary by value. """ return [(k,d[k]) for k in sorted(d,key=d.get,reverse=reverse)]
def line_to_type(fobject_or_string, d_type=str, no_split=False): """ Grab a line from a file like object or string and convert it to d_type (default: str). Parameters ---------- fobject_or_string : object A file like object or a string containing something that is to be converted to a s...
def comma_separated_list(value): """ Transforms a comma-separated list into a list of strings. """ return value.split(",")
def ishtml(filename): """Is the file an HTMLfile""" return filename.lower()[-5:] == '.html'
def get_md5_bytes(data: bytes) -> str: """Gets the MD5 hash of a bytes object holding data Args: data: Data as a bytes object Returns: str: MD5 hash of data """ import hashlib return hashlib.md5(data).hexdigest()
def same_type(arg1, *args): """Compares the class or type of two or more objects.""" t = getattr(arg1, '__class__', type(arg1)) for arg in args: if getattr(arg, '__class__', type(arg)) is not t: return False return True
def get_time(fld): """input a date field, strip off the date and format :From - 2017-06-17 20:35:58.777353 ... 2017-06-17 :Returns - 20 h 35 m 58.78 s """ if fld is not None: lst = [float(i) for i in (str(fld).split(" ")[1]).split(":")] return "{:02.0f} h {:02.0f} m {: 5.2...
def fix_conf(jgame): """Fixture for a standard configuration""" # XXX This line exists to fool duplication check return jgame["configuration"]
def is_gr_line(line): """Returns True if line is a GR line""" return line.startswith('#=GR')
def add_inputs(input_1: float, input_2: float, *extra) -> float: """ adds 2 or more numbers together :param input_1: first number :type input_1: float :param input_2: second number :type input_2: float :return: all the inputs added together :rtype: float """ ...
def multiply_by_exponent(val, exponent=3, base=10): """ Simple template tag that takes an integer and returns new integer of base ** exponent Return int Params: val: int The integer to be multiplied exponent: int The exponent base: int ...
def desolve_rk4_determine_bounds(ics,end_points=None): """ Used to determine bounds for numerical integration. - If end_points is None, the interval for integration is from ics[0] to ics[0]+10 - If end_points is a or [a], the interval for integration is from min(ics[0],a) to max(ics[0],a) ...
def tolatin1(what): """ convert to latin1. """ return what.encode('latin-1', 'replace')
def extract_thread_list(trace_text): """Removes the thread list from the given trace data. Args: trace_text: The text portion of the trace Returns: a map of thread ids to thread names """ threads = {} # start at line 1 to skip the top of the ps dump: text = trace_text.splitlines() for line in...
def compare_fields(field1, field2): """ compare 2 fields if they are same then return true """ if field1 is None and field2 is None: return True if (field1 is None and field2 is not None) or\ (field2 is None and field1 is not None): return False if fi...
def list_creator(nbBins): """Create the necessary number of lists to compute colors feature extraction. # Arguments : nbBins: Int. The number of bins wanted for color histogram. # Outputs : lists: A list of 2*3*`nbBins` empty lists. """ nbLists = 2*3*nbBins return [[] for _ in ...
def choose3(n, k): """ (int, int) -> int | c(n-1, k-1) + c(n-1, k), if 0 < k < n c(n,k) = | 1 , if n = k | 1 , if k = 0 Precondition: n > k >>> binomial(9, 2) 36 """ c = [0] * (n + 1) c[0] = 1 for i in range(1, n...
def get_itemid(itemlist, itemname, itemtype): """Summary - generic function to get id from name in a list Args: itemlist (TYPE): python list itemname (TYPE): k5 item name to be converted to an id itemtype (TYPE): keyname ...eg. groups/users/roles etc Returns: TYPE: Descript...
def hw_uint(value): """return HW of 16-bit unsigned integer in two's complement""" bitcount = bin(value).count("1") return bitcount
def _fix_coords(coords, offset): """Adjust the entity coordinates to the beginning of the sentence.""" if coords is None: return None return tuple([n - offset for n in coords])
def search_opentag(line, pos=0, tag="tu"): """search opening tag""" tag1 = f"<{tag} ".encode() tag2 = f"<{tag}>".encode() try: pos1 = line.index(tag1, pos) except ValueError: pos1 = -1 try: pos2 = line.index(tag2, pos) except ValueError: pos2 = -1 if po...
def is_capitalized(text: str): """ Given a string (system output etc.) , check whether it is lowercased, or normally capitalized. """ return not text.islower()
def count_bytes(binary_data): """Return the length of a string a string of bytes. Should raise TypeError if binary_data is not a bytes string. """ if not isinstance(binary_data, bytes): raise TypeError("expected bytes, got %s" % type(binary_data)) return len(binary_data)
def distance_score(pos1: list, pos2: list, scene_x_scale: float, scene_y_scale: float): """ Calculate distance score between two points using scene relative scale. :param pos1: First point. :param pos2: Second point. :param scene_x_scale: X s...
def level_tag(list_tags, level_int ): """ Tags if the are nois or signal """ if len(list_tags)==0: return 'noise' try: return list_tags[level_int] except: return 'noise'
def check_str(names, aliases): """ Check if names match the simbad alias list. Args: names (list of str): object names in data headers aliases (list of str): aliases separated by '|' for each object. """ # Basic string check match = [] for name, alist in zip(names, aliases): ...
def _different_phases(row_i, row_j): """Return True if exon start or end phases are different.""" value = (row_i['StartPhase'] != row_j['StartPhase']) or \ (row_i['EndPhase'] != row_j['EndPhase']) return value
def array_merge_recursive(array1, *arrays): """Emulates the array_merge_recursive function.""" for array in arrays: for key, value in array.items(): if key in array1: if isinstance(value, dict): array[key] = array_merge_recursive(array1[key], value) ...
def bin2int(alist): """ convert a binary string into integer """ answer = 0 temp = alist temp.reverse() for i in range(len(temp)): answer += 2**int(temp[i]) temp.reverse() return answer
def generate_probabilities(alpha, beta, x): """Generate probabilities in one pass for all t in x""" p = [alpha / (alpha + beta)] for t in range(1, x): pt = (beta + t - 1) / (alpha + beta + t) * p[t - 1] p.append(pt) return p
def valuedict(keys, value, default): """ Build value dictionary from a list of keys and a value. Parameters ---------- keys: list The list of keys value: {dict, int, float, str, None} A value or the already formed dictionary default: {int, float, str} A defa...
def _newer_than(number: int, unit: str) -> str: """ Returns a query term matching messages newer than a time period. Args: number: The number of units of time of the period. unit: The unit of time: 'day', 'month', or 'year'. Returns: The query string. """ return f'new...
def find_max_min(my_list): """ function to get the minimum nd maximum values in a list and return the result in alist """ min_max_result = [] if type(my_list) == list: """ checks if the input is alist in order to perform the intended task use max() and min() methods to fi...
def hex_encode_bytes(message): """ Encode the binary message by converting each byte into a two-character hex string. """ out = "" for c in message: out += "%02x" % ord(c) return out
def _process_shape_and_axes(shape, axes): """ :returns: shape, axes, nbatch """ if axes is None: # if invalid, return shape, axes, 1 elif len(axes) > 3: raise ValueError( "FFTs with dimension greater than three are unsupported.") elif 0 in axes: if le...
def _get_groups(verb): """ Return groups """ try: return verb.data.plydata_groups except AttributeError: return []
def get_next_version(current_version) -> str: """ Get the next version that we can use in the requirements file. """ release, major, minor = [int("".join(o for o in i if o.isdigit())) for i in current_version.split(".")] if release == 0: return f"0.{major + 1}.0" return f"{release + 1}....
def readFileIntoList(fileName): """ Reads a single file into a single list, returns that list, strips newline character """ inFile = open(fileName) items = list() for line in inFile: items.append(line.rstrip('\n')) inFile.close() return items
def transpose_results(result): """Given a query result (list of strings, each string represents a row), return a list of columns, where each column is a list of strings.""" split_result = [row.split('\t') for row in result] return [list(l) for l in zip(*split_result)]
def hello(friend_name): """Say hello to the world :param friend_name: String :rtype: String """ return f"Hello, {friend_name}!"
def flatten_list(l): """Flatten a 2D sequence `l` to a 1D list that is returned""" return sum(l, [])
def slash_join(a, b): """ Join a and b with a single slash, regardless of whether they already contain a trailing/leading slash or neither. """ if not b: # "" or None, don't append a slash return a if a.endswith("/"): if b.startswith("/"): return a[:-1] + b r...
def datatype_percent(times, series): """ returns series converted to datatype percent ever value is calculated as percentage of max value in series parameters: series <tuple> of <float> returns: <tuple> of <float> percent between 0.0 and 1.0 """ max_value = max(series) try: ...
def indent_block(text, indention=' '): """ This function indents a text block with a default of four spaces """ temp = '' while text and text[-1] == '\n': temp += text[-1] text = text[:-1] lines = text.split('\n') return '\n'.join(map(lambda s: indention + s, lines)) + temp
def elmult(v1, v2): """ Multiply two vectors with the same dimension element-wise. """ assert len(v1) == len(v2) return [v1[i] * v2[i] for i in range(len(v1))]
def normal_from_lineseg(seg): """ Returns a normal vector with respect to the given line segment. """ start, end = seg x1, y1 = start x2, y2 = end dx = x2 - x1 dy = y2 - y1 return (dy, -dx)
def Pluralize(num, word, plural=None): """Pluralize word based on num. Args: num: int, the number of objects to count. word: str, the word to pluralize. plural: str, the plural form of word if not "add s" Returns: str: the plural or singular form of word in accord with num. """ if num == 1: ...
def compute_metric_deltas(m2, m1, metric_names): """Returns a dictionary of the differences of metrics in m2 and m1 (m2 - m1)""" return dict((n, m2.get(n, 0) - m1.get(n, 0)) for n in metric_names)
def RPL_LUSERUNKNOWN(sender, receipient, message): """ Reply Code 253 """ return "<" + sender + ">: " + message
def _public_coverage_ht_path(data_type: str, version: str) -> str: """ Get public coverage hail table. :param data_type: One of "exomes" or "genomes" :param version: One of the release versions of gnomAD on GRCh37 :return: path to coverage Table """ return f"gs://gnomad-public-requester-pay...
def lg_to_gpa(letter_grade): """Convert letter grade to GPA score Example: B+ => 3.3""" return {'A': '4.0','A-': '3.7','B+': '3.3', 'B': '3.0', 'B-': '2.7', 'C+': '2.3', 'C': '2.0','D': '1.0','F': '0'}[letter_grade]
def bitshift_left(case, caselen): """Shift bit by bit to left, adding zeroes from the right""" bitshifts = [] for bit in range(1, caselen + 1): shift = case[bit:] + "0" * bit bitshifts.append(shift) return bitshifts
def fibo(n): """Calculate Fibonacchi numbers :param int n: Which position in the series to return the number for :returns: The Nth number in the Fibonacchi series """ if n == 1: return 1 elif n == 2: return 1 elif n > 2: return fibo(n - 1) + fibo(n - 2)
def is_slice_index(index): """see if index is a slice index or has slice in it""" if isinstance(index, slice): return True if isinstance(index, tuple): for i in index: if isinstance(i, slice): return True return False
def inputs(form_args): """ Creates list of input elements """ element = [] html_field = '<input type="hidden" name="{}" value="{}"/>' for name, value in form_args.items(): if name == "scope" and isinstance(value, list): value = " ".join(value) element.append(html_fiel...
def _google_spreadsheet_url(key): """ Returns full editing URL for a Google Spreadsheet given its key """ return "https://docs.google.com/spreadsheets/d/{key}/edit".format(key=key)
def alphabet_position(text): """ In this kata you are required to, given a string, replace every letter with its position in the alphabet. If anything in the text isn't a letter, ignore it and don't return it. "a" = 1, "b" = 2, etc. :param text: a string value. :return: the index of each character i...
def _compute_nfp_uniform(l, u, cum_counts, sizes): """Computes the expected number of false positives caused by using u to approximate set sizes in the interval [l, u], assuming uniform distribution of set sizes within the interval. Args: l: the lower bound on set sizes. u: the upper bo...
def to_hex(cmd): """Return the hexadecimal version of a serial command. Keyword arguments: cmd -- the serial command """ return ' '.join([hex(ord(c))[2:].zfill(2) for c in cmd])