content
stringlengths
42
6.51k
def make_batches(size, batch_size): """Returns a list of batch indices (tuples of indices). @param size : (int) total size of the data @param batch_size : (int) batch size. @return batch_slices: (list) contains (begin_idx, end_idx) for every batch. """ num_batches = (size-1)//batch_siz...
def s3_truncate(text, length=48, nice=True): """ Nice truncating of text @param text: the text @param length: the maximum length @param nice: do not truncate words """ if len(text) > length: if nice: return "%s..." % text[:length].rsplit(" ", 1)[0][:45] ...
def map_or_default(value, mapper, default): """ Helps to avoid using a temporary variable in cases similiar to the following:: if slow_function() is not None: return mapper(slow_function()) else: return default """ return mapper(value) if value is not None else d...
def parse(l1, l2, l3, stats): """Parse JSON stats from dump978 Args: l1 (str): Level 1 name of JSON tree l2 (str): Level 2 name of JSON tree l3 (str): Level 3 name of JSON tree stats (str): JSON to parse Returns: int: Value of given stat """ raw = int() ...
def popcount(n=0): """ Computes the popcount (binary Hamming weight) of integer `n`. Arguments --------- n : a base-10 integer Returns ------- int Popcount (binary Hamming weight) of `n` """ return bin(n).count('1')
def mag_to_flux(mag, zeropoint): """Convert a magnitude into a flux. We get the conversion by starting with the definition of the magnitude scale. .. math:: m = -2.5 \\log_{10}(F) + C 2.5 \\log_{10}(F) = C - m F = 10^{\\frac{C-m}{2.5}} :param mag: magnitdue to be converted ...
def count_occurances(comment, word): """ A helper function to get the number of words in a comment. """ comment = comment.replace('?', ' ') comment = comment.replace('.', ' ') comment = comment.replace('-', ' ') comment = comment.replace('/', ' ') a = comment.split(" ") count = 0 ...
def tile_id(url): """Extract tile ID from its URL. Returns ------- str Tile ID. """ basename = url.split("/")[-1] return basename.split("_")[0]
def build_db_query(fields_names, field_values): """ method builds query dictionary by zipping together DB field names with the field values """ if not isinstance(fields_names, (list, tuple)): fields_names = [fields_names] if not isinstance(field_values, (list, tuple)): field_values = [field_...
def compare_acl(acl1, acl2): """ Compares two ACLs by comparing the role, action and allow setting for every ACE. :param acl1: First ACL :type acl1: dict with role, action as key and allow as value :param acl2: Second ACL :type acl2: dict with role, action as key and allow as value :return:...
def tuple_to_string(tuple_in: tuple) -> str: """Converts an RGB tuple to a latex-xcolor compatible string""" return ", ".join([f"{val:6.3f}" for val in tuple_in])
def validate_name(name: str) -> bool: """Validate full name. Requisites: Min words = 2.""" return len(name.split()) >= 2
def gc_content(sequence: str) -> float: """Calculate GC-content of a nucleotide sequence""" sequence = sequence.upper() return (sequence.count("G") + sequence.count("C")) / len(sequence)
def _postprocess_fn(nodes): """Merge any nodes.""" if nodes: return [True] else: return []
def fact(x): """ factorial of a number. """ if type(x) == int: flg = 'invalid for negative integers' if x > 0: return fact(x - 1) * x elif x < 0: raise Exception(flg) else: return 1 else: raise Exception('invalid for non-in...
def get_version_substitute(version_str: str): """Transform provider version str to universal version type.""" version_str = version_str.lower() # substitute edit and edition with version if "edition" in version_str or "edit" in version_str: version_str = version_str.replace(" edition", " version...
def pluralize(singular, plural, count): """Returns the plural if count is not 1:: pluraize('item', 'items', 1) -> 'item' pluraize('item', 'items', 2) -> 'items' pluraize('item was', 'items were', 2) -> 'items were' :param singular: singular form (returned when count in 1) ...
def _all_positions_distinct(positions): """Return whether all positions are distinct.""" return len(set(tuple(row) for row in positions)) == len(positions)
def merge_bins(distribution, limit): """Merges the bins of a regression distribution to the given limit number """ length = len(distribution) if limit < 1 or length <= limit or length < 2: return distribution index_to_merge = 2 shortest = float('inf') for index in range(1, length): ...
def train(train, test, datafraction, opts): """setup the resnet and run the train function, train and test will be None here as reading the files from disk needs to be part of the compute graph AFAIK """ return None # from deeprace.models.tf_details import cifar10_main as cfmain # from deeprace.models....
def hash_name(varlist, pserver_endpoints): """ hash variable names to several endpoints. :param varlist: a list of Variables :return: a map of pserver endpoint -> varname """ def _hash_block(block_str, total): return hash(block_str) % total eplist = [] for var in varlist: ...
def pretty_duration(hours: float) -> str: """Format a duration in days, hours, minutes, seconds.""" seconds = int(3600 * hours) days, seconds = divmod(seconds, 86400) hours, seconds = divmod(seconds, 3600) minutes, seconds = divmod(seconds, 60) if days > 0: return "%dd %dh %dm" % (days, ...
def stations_by_river(stations): """ This map the rivers to their respective stations """ rivers_to_stations_dict = dict() for station in stations: if station.river in rivers_to_stations_dict: rivers_to_stations_dict[station.river].append(station) else: rivers...
def list_to_str(a_list, sep=', '): """Converts a list to string. Args: a_list: The list to convert to string. sep: Separator between elements. Returns: String representation of the list. """ return sep.join(a_list)
def is_integer(mark_string): """Function to check if a supposed pk is an integer.""" try: mark_id = int(mark_string) except ValueError: return False return mark_id
def temp_conv(degrees,metric=True): """ Param "degrees" is the temperature as integer or float Param "metric" is the unit degrees is measured in Default "metric" is True, meaning Celcius "metric" = False, mean Fahrenheit """ d = degrees if metric == True: temp = (d * 9/5) ...
def snake_to_camel(snake_case_string: str) -> str: """ Takes in a `snake_case` string and returns a `camelCase` string. :params str snake_case_string: The snake_case string to be converted into camelCase. :returns: camelCase string :rtype: str """ initial, *temp = snake_case_string.spli...
def parse_resource_ids(resource_ids: str) -> list: """ Parses a string with comma separated ids to list of ids Args: resource_ids: Comma separated ids Returns: A list of ids """ if not resource_ids: return [] id_list = resource_ids.replace(" ", '') resourceIds = ...
def evaluate_micro_mask(matrix, matrix_size): """\ Evaluates the provided `matrix` of a Micro QR code. ISO/IEC 18004:2015(E) -- 7.8.3.2 Evaluation of Micro QR Code symbols (page 54) :param matrix: The matrix to evaluate :param matrix_size: The width (or height) of the matrix. :return int: The ...
def updateDatetime(year, doy): """ creates datetimes for updating NMHC info :param year: the year :param doy: the decimal day of year :return: datetime """ import datetime as dt import calendar start = dt.datetime(year - 1, 12, 31) # create starting datetime result = start + dt...
def sort(array: list) -> list: """Heapsort implementation. """ def sift(start: int, count: int) -> None: root: int = start while root * 2 + 1 < count: child = root * 2 + 1 if child < count - 1 and array[child] < array[child + 1]: child += 1 ...
def escape(s, to_escape, escape_with='\\'): """Returns ``s`` with characters in ``to_escape`` all prepended with ``escape_with``. """ return ''.join((escape_with + c if c in to_escape else c) for c in s)
def clear_spaces(comp): """ 'A + D' -> 'A+D' """ r = '' for c in comp: if c != ' ': r += c return r
def format_summary(translation): """ Transforms the output of the `from_batch` function into nicely formatted summaries. """ raw_summary, _, _ = translation summary = ( raw_summary.replace("[unused0]", "") .replace("[unused3]", "") .replace("[PAD]", "") .replace("[unu...
def is_empty(the_stack): """ (list) -> bool Returns True if <the_stack> empty, otherwise returns False. """ if the_stack == []: return True else: return False
def ofs_nbits(start, end): """ The utility method for ofs_nbits This method is used in the class to set the ofs_nbits. This method converts start/end bits into ofs_nbits required to specify the bit range of OXM/NXM fields. ofs_nbits can be calculated as following:: ofs_nbits = (start <...
def _get_character_pairs(text): """Returns a defaultdict(int) of adjacent character pair counts. >>> _get_character_pairs('Test is') {'IS': 1, 'TE': 1, 'ES': 1, 'ST': 1} >>> _get_character_pairs('Test 123') {'23': 1, '12': 1, 'TE': 1, 'ES': 1, 'ST': 1} >>> _get_character_pairs('Test TEST') ...
def read_next_token(s, pos): """This function, given a string s (probably a long string, like a line or a file) and a position 'pos', finds the next token in the string (defined as a nonempty sequence of whitespace characters delimited by whitespace), and advances the position to one character afte...
def fix_ensure_time_attrib(json): """Ensure that requested attributes include the 'time' attribute""" if 'attrs' not in json: json['attrs'] = [] if 'time' not in json['attrs']: json['attrs'].append('time') return json
def nutrition_times_portion(nutritional_info, portions): """ Simply multiplication Args: nutritional_info (dict): Nutritional info for 1 portion portions (int): portions to multiply by returns: dict with values multiplied by portions """ return {key: (float(value) * float...
def unique_list(list): """ Returns a unique version of a list :param list: Input list :return: Unique list """ new_list = [] for i in list: if i not in new_list: new_list.append(i) return new_list
def convert_gb_to_kb(mem_gb): """Convert from gb to kb.""" return mem_gb * 1024 * 1024
def formatList1(lst,width): """ Attempt to format a list on a single line, within supplied width, or return None if the list does not fit. """ out = "(" pre = "" ol = 2 for i in lst: o = pre+repr(i) ol += len(o) if ol > width: return None pre = ", " ...
def git_repo(repo): """ Tests if a repo is a git repo, then returns the repo url, possibly modifying it slightly. """ # generic (https://*.git) or (http://*.git) ending on git if (repo.startswith('https://') or repo.startswith('http://')) and repo.endswith('.git'): return repo # fo...
def distance2(x1, y1, z1, x2, y2, z2): """Calculates the distance^2 between point 1 and point 2.""" return (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2) + (z1 - z2) * (z1 - z2)
def bytes_to_int(bytestr: bytes) -> int: """Make an integer from a big endian bytestring.""" value = 0 for byte_intval in bytestr: value = value * 256 + byte_intval return value
def generate_data_and_constant_predictions(n, frac_positive): """ Generates data in a fixed positive:negative ratio, and returns the data and scores from a dummy model that predicts 0.5 for all examples. Parameters ---------- n : int Number of examples frac_positive : float ...
def _private_key_filename(file_prefix): """ Construct the name of a file for use in storing a private key. :param str file_prefix: base file name for the private key (without the extension) :return: private key filename :rtype: str """ return file_prefix + ".key"
def apply_perm(omega,fbn): """ omega contains a list which will be permuted (scrambled) based on fbm. fbm is a list which represents a factorial base number. This function just translates the pseudo code in the Rosetta Code task. """ for m in range(len(fbn)): ...
def parse_equal_statement(line): """Parse super-sequence statements""" seq_names = line.split()[1:] return seq_names
def bytes2int(b): """ Convert bytes to int. """ return int.from_bytes(b, byteorder='big')
def differences(s1, s2): """Calculate the Hamming distance between two bit strings returns the full list of booleans, where true indicates a mismatch""" #assert len(s1) == len(s2) # assume, since assert and try except don't work with jit return [c1 != c2 for c1, c2 in zip(s1, s2)]
def join(*args) -> str: """Concatenate a list of values using the key path separator '/'. Parameters ---------- args: list List of argument values. Returns ------- str """ return '/'.join([str(v) for v in args if v])
def _console_vars_to_str(console_dict): """ Printing values of variable evaluations to command line output. """ if not console_dict: return '' if isinstance(console_dict, dict): console_str = ', '.join('{}={}'.format(key, val) for (key, val) in console...
def format_time(duration): """Return a human friendly string from duration (in seconds).""" if duration > 4800: ret = '%s hours' % int(duration / 2400) elif duration > 2400: ret = '%s hour' % int(duration / 2400) elif duration > 120: ret = '%s mins' % int(duration / 60) elif ...
def uniq_stable(elems): """uniq_stable(elems) -> list Return from an iterable, a list of all the unique elements in the input, but maintaining the order in which they first appear. Note: All elements in the input must be hashable for this routine to work, as it internally uses a set for efficiency...
def flag(v): """Boolean flag. http://thedailywtf.com/Articles/What_Is_Truth_0x3f_.aspx """ return {0: False, 1: True, 2: None}[v]
def str2bool(flag): """ bool: convert flag to boolean if it is string and return it else return its initial bool value """ if not isinstance(flag, bool): if flag.lower() == 'false': flag = False elif flag.lower() == 'true': flag = True return flag
def even_after_odd(head): """ :param - head - head of linked list return - updated list with all even elements are odd elements """ odd_list = [] even_list = [] while head: if head.data % 2 == 0: even_list.append(head) else: odd_list.append(head) ...
def startswith_in_list(src, items): """ Comparaison de type "startswith" avec une liste de 'match' possibles """ for k in items: if src.startswith(k): return k return False
def avfi(data): """ AVFI - Request actual speed and motor force """ #print ("data: %s" % (data) ) return data
def get_hourly_ncname(year): """Get the daily netcdf filename for the given year""" return f"/mesonet/data/iemre/{year}_iemre_hourly.nc"
def too_many_visits(path): """Have we visited more than one small cave twice already? Or have we visited "start" or "end" more than once? """ if path.count("start") > 1: return True if path.count("end") > 1: return True small_caves = [p for p in path if p.islower()] if len(sm...
def end_of_group_reached(i, groups): """Determines whether the end of a group of neighboring genes is reached when displaying the table associated to trail grouping by genes. :param i: index of a gene on a chromosomal strand :param groups: list of lists of indexes of neighboring genes on a chro...
def __ConvertLocalToOBSG(e_local, n_local, Eo, No, CSF): """ Convert local grid to OSBG coordinates :param e_local: x coord in local grid :param n_local: y coord in local grid :param Eo: delta easting of local grid :param No: delta northing of local grid :param CSF: grid's associated scale...
def _make_plural(collection: str) -> str: """Returns a plural form of an object's `__name__` attribute if it is singular.""" return f"{collection}s"
def get_analysis_type(normal, umi): """ return analysis type """ return "paired" if normal else "single"
def find_closest_stores(friends, stores): """ Finds the closest store to each friend based on absolute distance from the store. Parameters: friends: Dictionary with friend names as keys and point location as values. stores: Dictionary with store names as keys and point l...
def check_array(array, check): """Checks if item is in array. Checks if an item has already been added to an array. Parameters ---------- array: array-type The array to check. check: str The item to try and find. Returns ------- bool true if the item is alr...
def problem_19_3(n): """ Write an algorithm which computes the number of trailing zeros in n factorial. Solution: It's enough to count the power of 5 in the factoring of n! That is the number of trailing zeros. """ cache = {} def get_pow_5(n): if n % 5 != 0: return 0 ...
def get_case_ids(items): """ Return TestRail ids from pytests markers """ tids = [] for item in items: if item.get_marker('testrail'): idmarker = item.get_marker('testrail') if idmarker is not None: tids.append(idmarker.args[0]) return tids
def _strip_quotes(s): """ Strips one set of outer quotes. INPUT: - ``s`` - a string OUTPUT: - a string with any single and double quotes on either side of ``s`` removed EXAMPLES: Both types of quotes work:: sage: import sage.repl.preparse sage: sage.repl.prep...
def _comment(line): """Adds the # [magic] prefix (line level) """ return f'# [magic] {line}'
def flatten(l): """Flatten a list of lists.""" return [item for sublist in l for item in sublist]
def convert_percentage_number(decimal_percentage: float) -> str: """ Convert a decimal percentage in a hundred percentage the percentage generated won't have fraction part For example: ``` convert_percentage_number(0.1) # 10 convert_percentage_number(0.05) # 5 convert_percentage_number...
def is_palindrome(n): """ >>> is_palindrome(12321) True >>> is_palindrome(99) True >>> is_palindrome(0) True """ s = str(n) return s == s[::-1]
def filter_metadata_categorical(metadata, metadata_labels): """ Return only the metadata that is categorical Args: metadata (lists of lists): A list of metadata. metadata_labels (dict): The labels for the metadata. Returns: metadata (lists of lists): Only the categoric...
def transform_tradeflow(tradeflow): """ replace tradeflow "import(s)" or "export(s)" by the corresponding numbers (1 / 2) """ if isinstance(tradeflow, str): if 'export' in tradeflow.lower(): tradeflow = 2 elif 'import' in tradeflow.lower(): tradeflow = 1 retur...
def range_filter(field, gt=None, gte=None, lt=None, lte=None): """ Filter ``field`` by a range. Pass in some sensible combination of ``gt`` (greater than), ``gte`` (greater than or equal to), ``lt``, and ``lte``. """ return {"range": {field: { k: v for k, v in {'gt': gt, 'gte': gte, 'lt': l...
def sum_loop(n): """Sum all the numbers between 0 and n using a for loop""" sum = 0 for i in range(n): if i % 2 == 1: sum += i return sum
def fission_processes_to_events(process_list): """ Define linear fission processes between compartments. Parameters ========== process_list : :obj:`list` of :obj:`tuple` A list of tuples that contains fission rates in the following format: .. code:: python [ ...
def mat_to(newtype, a): """ Converts the elements of a matrix to a specified scalar type Parameters ---------- newtype: class The new scalar type to which the elements of the matrix will be converted. a: list[list] A matrix of scalar values Returns ------- l...
def transcript_str(transcript_obj, gene_name=None): """Generate amino acid change as a string. Args: transcript_obj(dict) gene_name(str) Returns: change_str(str): A description of the transcript level change """ # variant between genes gene_part = "intergenic" part_...
def _splitVersionStr(ver): """!Split a version string into its components major, minor, and extra.""" major, rest = ver.split(".", 1) try: minor, extra = rest.split("-", 1) except ValueError: minor, extra = rest, "" return int(major), int(minor), extra
def dot(p1, p2): """ Dot product of two vectors """ return p1[0] * p2[0] + p1[1] * p2[1] + p1[2] * p2[2]
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 >>> check...
def lat_to_index_num(lat): """Input latitude in [-90, 90]. MERRA-2 latitude is 0.5 degree resolution, indexed [0:360]""" if lat < -90 or lat > 90: raise ValueError(f"latitude outside bounds [-90, 90]; given {lat}") return round((lat + 90) / 0.5)
def filter_sfv_duplicates(entries): """Accepts the entries list of the parse functions above. The result will be sorted.""" result = list() previous = None for entry in sorted(entries): if previous is None or not entry.__eq__(previous): result.append(entry) previous = entry return result
def lines(s): """ Split a string in lines using the following conventions: - a line ending \r\n or \n is a separator and yields a new list element - empty lines or lines with only white spaces are not returned. - returned lines are stripped. Because of these constraints "".split() cannot be use...
def add_hash_tags(tweet, entities): """For all entities add hashtags to words. Example: tweet: Thai startup Lightnet, which aims to provide remittance services in Southeast Asia through its Stellar based blockchain network, raises $31.2M Series A entities: return {'persons': [], 'organizations':...
def find_line_closest_to_point(point, lines): """ Finds the line from a list of lines that is closest to `point`. Returns a bunch of information about the closest line. """ d = float('inf') closest_vertex = None far_vertex = None closest_line_index = None for line_index, line in enum...
def parse_bool(val): """Parses a bool Handles a series of values, but you should probably standardize on "true" and "false". """ true_vals = ('t', 'true', 'yes', 'y') false_vals = ('f', 'false', 'no', 'n') val = val.lower() if val in true_vals: return True if val in false_...
def sign(x): """ np.sign(0) = 0 but here to avoid value 0, we redefine it as def sign(0) = 1 """ return 1.0 if x >= 0 else -1.0
def add_field(obj, path, value): """Insert a field into a nested dict and return the (outer) dict. Keys and sub-dicts are inserted if necessary to create the path. e.g. if obj, as passed in, is {}, path is "a.b.c", and value is "hello", obj will be updated to: {'a': {'b': { ...
def parse_outcar_time(lines): """Parse the cpu and wall time from OUTCAR. The mismatch between wall time and cpu time represents the turn-around time in VaspInteractive returns (cpu_time, wall_time) if the calculation is not finished, both will be None """ cpu_time = None wall_time = No...
def sign(x: float) -> float: """ signum function """ if x < 0: y = -1.0 elif x > 0: y = 1.0 else: y = 0.0 return y
def twoDigit(num): """ Will return a string representation of the num with 2 digits. e.g. 6 => 06 """ if num < 10: return "0" + str(num) return str(num)
def sp_run(cmd, stderr=None, stdout=None, check=True, timeout=None): """ Python 2 compatibility means we can't use subprocess.run """ from subprocess import Popen, CalledProcessError pope = Popen(cmd, stderr=stderr, stdout=stdout) try: stdo, stde = pope.communicate(timeout=timeout) excep...
def isVowel(letter): """ isVowel checks whether a given letter is a vowel. For purposes of this function, treat y as always a vowel, w never as a vowel. letter should be a string containing a single letter return "error" if the value of the parameter is not a single letter string, return True, if the...
def is_class_part_of_pylint_airflow(class_): """Expected input e.g. <class 'pylint_airflow.checkers.operator.OperatorChecker'>""" return class_.__module__.split(".")[0] == "pylint_airflow"