content
stringlengths
42
6.51k
def is_valid_input(barcode): """ This function verifies if the barcode is 12 digits and if they are all positive numbers. :param barcode: parameter that takes the user's input to check if it is a valid 12 digit or not :return: Fruitful. a True or False Boolean value. """ if len(barcode) == 12 a...
def heat_color (grade) : """Function to assign colors to coverage tables""" if grade < 10.0 : percentage_color = 'ff6666' elif grade < 30.0 : percentage_color = 'ffb366' elif grade < 50.0 : percentage_color = 'ffff66' elif grade < 70.0 : percentage_color = 'd9ff66' ...
def deleted_files(new, old): """The paths of all deleted files. new and old are folder hashes representing the new state (i.e. the local copy) and old state (i.e. what is currently on the web config.server)""" return [f for f in old.keys() if f not in new]
def _unparsed_dict_from_argv(argv): """Split command line arguments into a dict, without applying coercions. """ arg_dict = dict() for arg in argv: name, value = arg.split('=', 1) arg_dict[name] = value return arg_dict
def n_ary_mask(d, n, offset): """Create a n-ary mask with n entries (a list of bool with each nth entry True) Parameters ---------- d: int numbers of entries in the mask n: int period of the mask offset: int offset of the True entries Returns ------- list of...
def trim(lines): """ Remove lines at the start and at the end of the given `lines` that are :class:`~taxi.timesheet.lines.TextLine` instances and don't have any text. """ trim_top = None trim_bottom = None _lines = lines[:] for (lineno, line) in enumerate(_lines): if hasattr(lin...
def apply_mirror_boundary_conditions(coord, dim): """ Return the correct coordinate according to mirror boundary conditions coord: a coordinate (x or y) in the image dim: the length of the axis of said coordinate """ # If the coordinate is outside of the bounds of the axis, take its refl...
def parse_season_period(season_period_string): """Returns the season and period value from an id Argument -------- season_period_string : str A string representation of the season_period_id Returns ------- tuple A tuple of ``(season, period)`` """ season, period = sea...
def align_offset(offset, n): """given a byte offset, align it and return an aligned offset """ if n <= 0: return offset return n * ((offset + n - 1) // n)
def stripNonAlpha(s): """ Remove non alphabetic characters. E.g. 'B:a,n+a1n$a' becomes 'Banana' """ return ''.join([c for c in s if c.isalpha()])
def cache_hash(args: list, kargs: dict) -> int: """ Ensures that the hash calc does not trigger pickling which fails for FPLPandas objects. """ return hash((args, frozenset(kargs.items())))
def path(y): """Equation: x = a(y-h)^2 + k""" a = - 110.0 / 160.0**2 x = a*y**2 + 110.0 return x, y
def get_part_number(content) ->int: """Find part number""" pindex = content.find('part-') pnum = -1 if pindex > 0: pnum = int(content[pindex+5:pindex+10]) return pnum
def to_hex(string, spacer=" "): """ Converts a string to a series of hexadecimal characters. Use the optional spacer argument to define a string that is placed between each character. Example: >>> print to_hex("hello!", ".") 68.65.6C.6C.6F.21 >>> print to_hex("boop") ...
def error_email_subject_doi(identity, doi): """email subject for an error email""" return u"Error in {identity} JATS post for article {doi}".format( identity=identity, doi=str(doi) )
def get_percentage(dif: int) -> int: """Calculate the percentage to die or recover dependent on the average time Parameters ---------- dif: int contains the difference between the average and the current time Returns ------- int: percentage to die or recovers """ pe...
def changing_number_of_semicolons(number, digits=0): """ """ return f"{number:.{digits}f}"
def _create_html_file_content(translations): """Create html string out of translation dict. Parameters ---------- tralnslations : dict Dictionary of word translations. Returns ------- str: html string of translation """ content = [] for i1, t in enumerate(transl...
def str2bool (v): """ Convert string expression to boolean :param v: Input value :returns: Converted message as boolean type :rtype: bool """ return v.lower() in ("yes", "true", "t", "1")
def _match_url_start(ref, val): """ Checks that the val URL starts like the ref URL. """ ref_parts = ref.rstrip("/").split("/") val_parts = val.rstrip("/").split("/")[0:len(ref_parts)] return ref_parts == val_parts
def sum_of_squares(n: int) -> int: """ returns the sum of the first n squares using the mathematical fact that 1^2 + 2^2 + ... + n^2 = n(n+1)(2n+1)/6 """ return n * (n + 1) * (2 * n + 1) // 6
def _render(M): """Return a string representation of the matrix, M.""" return '\n'.join((''.join(row) for row in M))
def first_true_pred(predicates, value): """ Given a list of predicates and a value, return the index of first predicate, s.t. predicate(value) == True. If no such predicate found, raises IndexError. >>> first_true_pred([lambda x: x%2==0, lambda x: x%2==1], 13) 1 """ for num, pred in enu...
def make_variable_names_with_time_steps(number_of_lags, data_column_names): """ lagged W first, instantaneous W last, i.e., ..., x1_{t-2}, x2_{t-2}, ..., x1_{t-1}, x2_{t-1}, ..., x1_{t}, x2_{t}, ... """ variable_names = [] for i in range(number_of_lags, 0, -1): variable_names_lagged = [...
def hz2fft(fb, fs, nfft): """ Convert Bark frequencies to fft bins. Args: fb (np.array): frequencies in Bark [Bark]. fs (int): sample rate/ sampling frequency of the signal. nfft (int): the FFT size. Returns: (np.array) : fft bin numbers. """ return (n...
def _tasklines_from_tasks(tasks): """ Parse a set of tasks (e.g. taskdict.tasks.values()) into tasklines suitable to be written to a file. """ tasklines = [] for task in tasks: metapairs = [metapair for metapair in task.items() if metapair[0] != 'text'] meta_...
def _vax_to_ieee_single_float(data): """Converts a float in Vax format to IEEE format. data should be a single string of chars that have been read in from a binary file. These will be processed 4 at a time into float values. Thus the total number of byte/chars in the string should be divisible by 4...
def get_catch_message(percent_complete, creature) -> str: """ Used to generate the display message when we try to catch a creature. """ if percent_complete <= 25: return "Not even close!" elif percent_complete <= 50: return "Well, that could have gone worse" elif percent_comp...
def flattened_indices_from_row_col_indices(row_indices, col_indices, num_cols): """Get the index in a flattened array given row and column indices.""" return (row_indices * num_cols) + col_indices
def in_line(patterns, line): """Check if any of the strings in the list patterns are in the line""" return any([p in line for p in patterns])
def binary_search_recursive(array, lb, ub, target): """ Search target element in the given array by recursive binary search - Worst-case space complexity: O(n) - Worst-case performance: O(log n) :param array: given array :type array: list :param lb: index of lower bound :type lb: int ...
def get_parser_from_config(base_config, attributes, default_parser): """ Checks the various places that the parser option could be set and returns the value with the highest precedence, or `default_parser` if no parser was found @param base_config: a set of log config options for a logfile @param at...
def convert_to_boolean(string): """ Shipyard can't support passing Booleans to code, so we have to convert string values to their boolean values. """ if string in ['True', 'true', 'TRUE']: value = True else: value = False return value
def number_alleles(alleles, ref_allele): """ Add VCF_type numbering to alleles :param alleles: list List of alleles :param ref_allele: str Reference allele :return: dict A dictionary mapping alleles to number """ numbering = dict() counter = 1 for a in all...
def make_a_tweet(revision, message, url): """ Generate a valid tweet using the info passed in. """ return revision + ': ' + message + ' | ' + url
def reverse_recursive(lst): """Returns the reverse of the given list. >>> reverse_recursive([1, 2, 3, 4]) [4, 3, 2, 1] >>> import inspect, re >>> cleaned = re.sub(r"#.*\\n", '', re.sub(r'"{3}[\s\S]*?"{3}', '', inspect.getsource(reverse_recursive))) >>> print("Do not use lst[::-1], lst.reverse()...
def get_positions_to_update(screen_layout, table_position, delta): """ return dict of items representing categories and updated positions within screen layout """ positions = {} for category, data in screen_layout.items(): (y_pos, x_pos) = data.get('position', (0, 0)) if y_pos > table_po...
def to_swap_case(word: str): """ The 'swapcase()' method converts all uppercase characters to lowercase and all lowercase characters to uppercase characters of the 'word' string. :param word: the string to be swapcased :return: the swap-cased string """ return word.swapcase()
def defaultRecordSizer(recordLines): """ return the total number of characters in the record text """ size = 0 for line in recordLines: size += len(line) return size
def _create_udf_name(func_name: str, command_id: str, context_id: str) -> str: """ Creates a udf name with the format <func_name>_<commandId>_<contextId> """ return f"{func_name}_{command_id}_{context_id}"
def get_class_name(obj): """Get class name in dot separete notation >>> from datetime import datetime >>> obj = datetime.datetime(2000, 1, 1) >>> get_class_name(obj) -> "datetime.datetime" >>> from collections import deque >>> obj = deque([1, 2, 3]) >>> get_class_na...
def is_dict(d): """ additional template function, registered with web.template.render """ return type(d) is dict
def tree_checker(tree): """"Help function to check binary tree correctness.""" if tree is None or tree.value is None: return True if tree.right_child is not None and tree.right_child.value < tree.value: return False if tree.left_child is not None and tree.left_child.value > tree.va...
def is_foul_on_opponent(event_list, team): """Returns foul on opponent""" is_foul = False is_foul_pt2 = False for e in event_list[:2]: if e.type_id == 4 and e.outcome == 0 and e.team != team: is_foul = True elif e.type_id == 4 and e.outcome == 1 and e.team == team: is_foul_pt2 = True return is_foul and ...
def getValue(obj, path, defaultValue=None, convertFunction=None): """"Return the value as referenced by the path in the embedded set of dictionaries as referenced by an object obj is a node or edge path is a dictionary path: a.b.c convertFunction converts the value This function rec...
def location_to_index(location, spacing, shape): """Convert a location to an index. Parameters ---------- location: tuple of float or None Location of source in m. If None is passed at a certain location of the tuple then the source is broadcast along the full extent of that axi...
def replace_unknown_token(token, dictionary): """ Checks whether the token is in the given dictionary. If not it is replaced by an UNK token Arguments: token {string} -- the token to be checked and eventually replaced dictionary {dict} -- the dictionary Returns: string ...
def _number(string): """ Extracts an int from a string. Returns a 0 if None or an empty string was passed. """ if not string: return 0 elif string == "": return 0 else: try: return int(string) except ValueError: return float(st...
def get_nice_size(size, base=1000.0): """ Convert number of bytes to string with KB, MB, GB, TB suffixes """ if size < base: return '%sB' % (size) if size < base**2: return '%.2fKB' % (size / base) if size < base**3: return '%.2fMB' % (size / base**2) if size < bas...
def field_key(key): """Create the correct key for a field Needed because you cannot pass '*password' as a kwarg """ if key == "password": return "*password" else: return key
def inodefree(parameter='nodisk'): """ Get percentage of inodes free on filesystem """ return 'disk', '0'
def contains(value, lst): """ (object, list of list of object) -> bool Return whether value is an element of one of the nested lists in lst. >>> contains('moogah', [[70, 'blue'], [1.24, 90, 'moogah'], [80, 100]]) True """ found = False # We have not yet found value in the list. for i in...
def _stringify_tensor(obj): """Try to stringify a tensor.""" if hasattr(obj, 'name'): return obj.name else: return str(obj)
def splitList(listToSplit, num_sublists=1): """ Function that splits a list into a given number of sublists Reference: https://stackoverflow.com/questions/752308/split-list-into-smaller-lists-split-in-half """ length = len(listToSplit) return [ listToSplit[i*length // num_sublists: (i+1)*length ...
def parse_gff_attributes(attr_str): """ Parses a GFF/GTF attribute string and returns a dictionary of name-value pairs. The general format for a GFF3 attributes string is name1=value1;name2=value2 The general format for a GTF attribute string is name1 "value1" ; name2 "value2" Th...
def isMatch(text, pattern): """ :type s: str :type p: str :rtype: bool isMatch will return whether a string matches a provided patter. The pattern supports literals, ?, and * wildcard characters with the following rules: ? matches exactly one of any character * matches 0 or more of an...
def shake(iterable, cmp_function): """ The cocktail shaker sort is an improvement on the Bubble Sort. The improvement is basically that values "bubble" both directions through the array, because on each iteration the cocktail shaker sort bubble sorts once forwards and once backwards. Example: ...
def two_oldest_ages(ages): """Return two distinct oldest ages as tuple (second-oldest, oldest).. >>> two_oldest_ages([1, 2, 10, 8]) (8, 10) >>> two_oldest_ages([6, 1, 9, 10, 4]) (9, 10) Even if more than one person has the same oldest age, this should return two *distinct*...
def format_list(l): """pleasing output for dc name and node count""" if not l: return "N/A" return "{ %s }" % ", ".join(l)
def _is_inv_update_task(task_id, num_tasks): """Returns True if this task should update K-FAC's preconditioner.""" if num_tasks < 3: return False return task_id == num_tasks - 1
def validate_range(value, lower=None, upper=None): """ validate that the given value is between lower and upper """ try: if (lower is None or lower <= value) and (upper is None or value <= upper): return value except TypeError: pass return None
def _is_chrome_only_build(revision_to_bot_name): """Figures out if a revision-to-bot-name mapping represents a Chrome build. We assume here that Chrome revisions are always > 100000, whereas WebRTC revisions will not reach that number in the foreseeable future. """ revision = int(revision_to_bot_name.split('...
def InsertAtPos(src, pos, other): """Inserts C{other} at given C{pos} into C{src}. @note: This function does not modify C{src} in place but returns a new copy @type src: list @param src: The source list in which we want insert elements @type pos: int @param pos: The position where we want to start insert ...
def deepget(mapping, path): """Access deep dict entry.""" if ':' not in path: return mapping[path] else: key, sub = path.split(':', 1) return deepget(mapping[key], sub)
def file_as_bytes(file): """Reads file as binary. Args: file: File to read as binary Returns: binary file """ with file: return file.read()
def encode_rot13(string: str): """Encodes the string using ROT-13. Example: >>> encode_rot13('hello')\n 'uryyb' >>> decode_rot13('uryyb')\n 'hello' """ import codecs return codecs.encode(string, "rot13")
def tagsoverride(msg, override): """ Merge in a series of tag overrides, with None signaling deletes of the original messages tags """ for tag, value in override.items(): if value is None: del msg[tag] else: msg[tag] = value return msg
def tuple_to_string(coord): """Return a colon-delimited string. Parameters ---------- coord : tuple of 3 ints The coordinate to transform. Returns ------- str The colon-delimited coordinate string. """ return ":".join([str(x) for x in coord])
def categories_to_string(categories, queryset=False): """ Args: categories: [{"title": "Business"}, ...] OR [models.Category] (if queryset=True) Returns: ['<category.title', ...] """ if queryset: new_categories = [i.title for i in categories] else: ...
def get_pecha_num_list(pechas): """Extract all the pecha numbers from `catalog_data. Args: pechas (list): list of pecha metatdata in list. Returns: list: list of pecha numbers. """ return [int(pecha[0][2:8]) for pecha in pechas]
def _text_box(value, max_rows = 5, max_chars = 50): """ a = dictable(a = range(10)) * dict(b = range(10)) b = (dictable(a = range(5)) * dict(b = range(5))) * dict(c = range(10)) self = c = dictable(key = ['a', 'b'] * 5, rs = [a,b]*5) """ v = str(value) res = v.split('\n') if max_rows: ...
def filter_by_device_name(items, device_names, target_device_name): """Filter a list of items by device name. Args: items: A list of items to be filtered according to their corresponding device names. device_names: A list of the device names. Must have the same legnth as `items`. target_dev...
def parseMeasurement(messageLine, streamFormat): """Parses get_stream measurement line into list of tuples. Must contain same amount of items that the formatting has provided""" meas = messageLine.strip().split('\t') if len(meas) == len(streamFormat): # zip() is a neat python built in functio...
def validateLabel(value): """ Validate descriptive label. """ if 0 == len(value): raise ValueError("Descriptive label for friction model not specified.") return value
def make_carousel(columns, ratio=None, size=None): """ create carousel message content. reference - `Common Message Property <https://developers.worksmobile.com/jp/document/100500808?lang=en>`_ """ content = {"type": "carousel", "columns": columns} if ratio is not None: con...
def stripfalse(seq): """Returns a sequence with all false elements stripped out of seq. """ return [x for x in seq if x]
def build_query_string(query_words): """Builds an OR concatenated string for querying the Twitter Search API. Args: query_words (list): list of words to be concatenated. Returns: list: List of words concatenated with OR. """ result = ''.join( [q + ' OR ' for q in query_words...
def parse_description(description): """ Strip figures and alt text from description """ return "\n".join( [ a for a in description.split("\n") if ("figure::" not in a) and (":alt:" not in a) ])
def _depth_first_select(rectangles): """Find a rectangle of minimum area for bisection.""" min_area, j = None, None for i, (_, (u, v), (s, t), _, _, _, _) in enumerate(rectangles): area = (s - u)*(t - v) if min_area is None or area < min_area: min_area, j = area, i return ...
def is_roughly_water_color(color): """Water is black, land is white.""" r, g, b, *_ = color average_pixel_value = (r + g + b) / 3 return average_pixel_value <= 128
def validate_date(date: str) -> bool: """This method validates a date to be in yyyy-mm-dd format. Args: date (str): date string Returns: bool: True/False based on valid date string """ if "-" not in date: return False date_elements = date.split("-") if len(dat...
def parse_residue_spec(resspec): """ Light version of: vermouth.processors.annotate_mud_mod.parse_residue_spec Parse a residue specification: <mol_name>#<mol_idx>-<resname>#<resid> Returns a dictionary with keys 'mol_name', 'mol_idx', and 'resname' for the fields that are specified. Re...
def normalize(pair): """Convert the (count, species) pair into a normalized list of atomic and mass numbers. """ o_mass, o_atomic = pair if o_mass < 0: return [(o_mass, o_atomic)] if o_atomic == 0: return [(1, 0) for _ in range(o_mass)] if o_mass == o_atomic: return [...
def table_to_dict(opts, spec): """ Convert a table specification to a list of dictionaries of information. Enter: opts: a dictionary of options. spec: a table specification: one of n, l, m, n-l, l-m. Exit: speclist: a list, each of which has a dictionary of information with ...
def get_dict_buildin(dict_obj, _types=(int, float, bool, str, list, tuple, set, dict)): """ get a dictionary from value, ignore non-buildin object """ return {key: dict_obj[key] for key in dict_obj if isinstance(dict_obj[key], _types)}
def list_sample(collection, limit = 3): """ given an ordered collection (list, tuple, ...), return a string representation of the first limit items (or fewer), e.g. "itemA, itemB, itemC and 7 more" """ ln = len(collection) if ln > 1: if ln <= limit: return '%s and %s' % (', '.join(str(ws) for ws in collect...
def convert_currency(val): """ 125000.00 Convert the string number value to a float - Remove $ - Remove commas - Convert to float type """ new_val = val.replace(',', '').replace('$', '') return float(new_val)
def calc_s11_s22_s33(s2211, s1133): """Calculates s11, s22, s33 based on s22-s11 and s11-s33 using the constraint s11+s22+s33=0 """ s22 = 2.0*(s2211)/3.0 + s1133/3.0 s11 = s22 - s2211 s33 = s11 - s1133 return s11, s22, s33
def _replace_param_fixed_length(param): """ Generate a fixed length data element if param matches the expression [<type>_WITH_LENGTH_<length>] where <type> can be: STRING, INTEGER, STRING_ARRAY, INTEGER_ARRAY, JSON. E.g. [STRING_WITH_LENGTH_15] :param param: parameter value :return: tuple with ...
def escape_str(escape_func,s,*args): """ Applies escape_func() to all items of `args' and returns a string based on format string `s'. """ return s % tuple(escape_func(v) for v in args)
def parse(domain): """ Split domain into queryable parts in reverse. Arguments: domain (str): full domain name Examples: >>> parse('www.google.com') ['.', 'com.', 'google.com.', 'www.google.com.'] """ parts = domain.split('.') parts.extend('.') parts.reverse() ...
def bottom_node(nodes, y, x): """ find the first right node and returns its position """ try: return str(x) + " " + str(nodes.index('0', y+1)) except(KeyError, ValueError): return '-1 -1 '
def ddm_irref_score(a, score): """a <-- rref(a)""" # a is (m x n) m = len(a) if not m: return [] n = len(a[0]) i = 0 pivots = [] for j in range(n): # nonzero pivots nz_ip = [ip for ip in range(i, m) if a[ip][j]] # No pivots if not nz_ip: ...
def is_isogram(word: str) -> bool: """Determine if word is an isogram.""" lowercase_word = word.lower() distinct_letters = len(set(lowercase_word)) total_letters = len(lowercase_word) return distinct_letters == total_letters
def round_if_near(value: float, target: float) -> float: """If value is very close to target, round to target.""" return value if abs(value - target) > 2.0e-6 else target
def fix_string(code): """ Fix indentation and empty lines from string coming out of the function. """ lines = code.split('\n') # Remove first line if empty if not lines[0]: lines = lines[1:] # Detect tabsize size = 0 while lines[0][size] in ' ': size += 1 lines...
def find_separator(prompt, start, sep): """Find separator skipping parts enclosed in brackets.""" level = 1 length = len(prompt) while start < length: if start + 1 < length and prompt[start] == '\\': start += 1 elif level == 1 and prompt[start] == sep: return star...
def close(session_attrs, fulfillment_state, message): """ Close session in Lex. """ response = { 'sessionAttributes': session_attrs, 'dialogAction': { 'type': 'Close', 'fulfillmentState': fulfillment_state, 'message': {'contentType': 'PlainText', 'cont...
def _escape(data, entities={}): """ Escape &, <, and > in a string of data. You can escape other strings of data by passing a dictionary as the optional entities parameter. The keys and values must all be strings; each key will be replaced with its corresponding value. """ try: ...
def map_activity_model(raw_activity): """ Maps request data to the fields defined for the Activity model """ return { 'activity_id': raw_activity['key'], 'description': raw_activity['activity'], 'activity_type': raw_activity['type'], 'participants': raw_activity['participants']...