content
stringlengths
42
6.51k
def format_duration(seconds: float) -> str: """ Nicely format a given duration in seconds. Args: seconds: The duration to format, in seconds. Returns: The duration formatted as a string with unit of measurement appended. """ return f"{seconds:.2f} sec"
def isempty(prt_r): """Test whether the parent of a missingness indicator is empty""" return len(prt_r) == 0
def factorial_recursive(n): """ :param n: Integer :return: n * n-1 * n-2 * n-3..........1 """ if n==1: return 1 else: return n * factorial_recursive(n-1)
def strip_outer_matching_chars(s, outer_char): """ If a string has the same characters wrapped around it, remove them. Make sure the pair match. """ s = s.strip() if (s[0] == s[-1]) and s.startswith(outer_char): return s[1:-1] return s
def path_to_history_file(ctypedir, ctype) : """Returns path to HISTORY file in the calib store. e.g. /some-path/calib/Jungfrau::CalibV1/CxiEndstation.0:Jungfrau.0/pedestals/HYSTORY See parameters description in :py:meth:`history_record`. """ return '%s/%s/HISTORY' % (ctypedir, ctype)
def level_numeric_value(level): """ Convert string levels like 'debug' to number. :param level: :return: """ if level is "debug": level = 10 elif level is "info": level = 30 elif level is "warning": level = 50 return level
def steps_cancel_out(prev_step: str, step: str) -> bool: """ >>> steps_cancel_out(None, "U") False >>> steps_cancel_out("U", "U'") True >>> steps_cancel_out("U'", "U") True >>> steps_cancel_out("U2", "U2") True >>> steps_cancel_out("U", "U") False Returns: Tr...
def subsets(nums): """ O(2**n) """ def backtrack(res, nums, stack, pos): if pos == len(nums): res.append(list(stack)) else: # take nums[pos] stack.append(nums[pos]) backtrack(res, nums, stack, pos+1) stack.pop() # do...
def _average(values): """ Return average of a list of numbers """ return sum(values)/len(values)
def _contains(prop_value, cmp_value, ignore_case=False): """ Helper function that take two arguments and checks if :param cmp_value: is in :param prop_value:. :param prop_value: Property value that you are checking. :type prop_value: :class:`str` :param cmp_value: Value that you are checking if...
def hill_equation(l, emax, kd, n): """Hill receptor-response equation. Args: l (float, numpy.array): The input concentration of an ligand in concentration units. emax (float): The maximum response in response units. Bounds fot fitting: 0 <= emax <= inf kd (float)...
def checkPrime(number: int, i: int = 2): """This function checks if a number is prime. Returns --bool Arguments: number {int} -- number to be checked Keyword Arguments: check {int} -- check situation (default: {number}) """ try: if number <= 2: ...
def range_overlap(range1, range2): """ determine range1 is within range2 (or is completely the same) :param range range1: a range :param range range2: another range :rtype: bool :return: True, range1 is subset of range2, False, not the case """ result = all([ range1.start >= ra...
def _power_of_two(value): """Returns whether the given value is a power of two.""" return (value & (value - 1)) == 0
def get_denom(cc, related_chart=False): """Get the numerator and denominator map.""" # If chart requires denominator, use it for both primary and related charts. if 'denominator' in cc: result = {} if len(cc['denominator']) != len(cc['statsVars']): raise ValueError('Denominator n...
def decintfix(decorint=0): """ Fix The Formatting Of Decimals And Integers """ if str(decorint)[-2:] == '.0': return int(decorint) return float(decorint)
def get_converter_type_path(*args, **kwargs): """ Handle converter type "path" :param args: :param kwargs: :return: return schema dict """ schema = { 'type': 'string', 'format': 'path', } return schema
def merge_dicts(lst): """ Combine a list of dictionaries together to form one complete dictionary """ dall = {} for d in lst: dall.update(d) return dall
def get_import_errors(error_container, index_name, total_count): """Returns a string with error message or an empty string if no errors. Args: error_container: dict with error messages for each index. index_name: string with the search index name. total_count: integer with the total amount of...
def bondfilter(motif, bond, bondpattern): """ For a given linear sequence of atoms it tests whether the bond orders match pattern bondpattern. E.g., bondpattern can be 1, 1, 2, 1 for a 5-long motif. """ for atomi in range(len(motif)-1): if bondpattern[atomi] == 'X': continue ...
def individual_collate(batch): """ Custom collation function for collate with new implementation of individual samples in data pipeline """ data = batch # Assuming there's at least one instance in the batch add_data_keys = data[0].keys() collected_data = {k: [] for k in add_data_keys} ...
def convert_em(element, text): """ Italicizes the text """ if text: text = "*%s*" % text return text
def _pad_post_array(input_array, length): """ Pads the input 2D list with 0's at the end so that is is of shape (None, length) :param input_array: 2D list :param length: length to pad to :return: (None, length) padded array """ output_array = [] for arr in input_array: padded = a...
def check_format(json_string, correct_value): """takes the first key from json formatted string and compares it to a desired value""" string_start = json_string.split(":", 1)[0] first_value = string_start.strip("{") return first_value == correct_value
def percentage(value): """Returns the number as percentage with two-digit precision""" try: value = float(value) except (ValueError, TypeError, UnicodeEncodeError): return '' return '{0:.2%}'.format(value)
def get_cell_numbers(contained): """Retrieve non-overlapping cell numbers from the output of `get_overlapping`. None may appear at the ends of the output, indicating that the corresponding target cells are not overlapping with any source cells. These should be ignored when regridding. Cell numbers...
def check_valid_key_name(name): """ Ensure the key name provided is legal :param name: a potential key name :return: boolean indicating legality of name :rtype: bool """ if type(name) not in [str]: return False bad_chars = ["*", ".", "&&&&"] if any(k in name for k in bad_char...
def poly_area_calculation(points): """gets Area and CG""" l = len(points) if len(points) < 3: raise ValueError('NOT SUFFICIENT POINTS!') sum = [0.0, 0.0] area = 0 for i in range(l): j = i + 1 if i == l - 1: j = 0 m = points[i][0]*points[j][1] - points[j][0]*points[i][1...
def _get_all_committers(commits_info): """ Returns all committers' information The information includes name and Email """ committers_unduplicated = [{'name': commit_info['committer'], 'email': commit_info['committerEmail']} for commit_info in commits_info] all_names = ...
def isPalindrome(s): """ Return True, if a given text is a Palindrom. """ def onlyChars(text): """ Check only letters in lower case """ text = text.lower() feedback = '' for letter in text: if letter in "abcdefghijklmnopqrstuvwxyz": #string.ascii_lowercase ...
def which(program): """Check if the excutable exists in the users path """ import os def is_exe(fpath): return os.path.isfile(fpath) and os.access(fpath, os.X_OK) fpath, fname = os.path.split(program) if fpath: if is_exe(program): return program else: ...
def gps_format_datetime(datetime_str): """convert CGNS GGA date time into format for REST post""" year = datetime_str[:4] month = datetime_str[4:6] day = datetime_str[6:8] hours = datetime_str[8:10] minutes = datetime_str[10:12] seconds = datetime_str[12:14] return '{}%2F{}%2F{}+{}%3A{}%...
def mean(mylist): """ Returns the mean value of a list """ total = 1.0 * sum(mylist) length = len(mylist) if length == 0.0: raise ArithmeticError( "Attempting to compute the mean of a zero-length list") return (total / length)
def parse_individual(arg): """ Try to open arg as a file and return list of each line, otherwise assume it is a comma separated list and use split to return an actual list """ inds=[] try: file=open(arg, "r") inds=file.readlines() inds=[i[:-1] for i in inds] # remove ne...
def InvertDepthNorm( depth, maxDepth=1000.0, minDepth=10, transform_type='inverse' ): """Renormalizes predictions back to targets space""" if transform_type == 'inverse': return maxDepth / depth elif transform_type == 'scaled': return depth * minDepth elif transform_type == 'log': ...
def json_table_to_text(table): """ Transform JSON table to text :param table: table to transform into text :type table: list :return: content of the table in plain text :rtype: str """ if not len(table): return "" header = table[0] text = ' '.join(hea...
def get_run_and_tag_from_filename(filename): """e.g. SFX_each_193441_79553414.h5""" import os sp = os.path.splitext(os.path.basename(filename))[0].split("_") if len(sp) >= 2: run = int(sp[-2]) tag = int(sp[-1]) return run, tag else: return -1, -1
def is_valid_misra_violation(misra_violation): """Check if misra violation is formatted correctly""" return isinstance(misra_violation, str)
def fill_byte(byteA, n:int): """ Fill byte till length n. Output: bytes """ if not isinstance(byteA,bytearray): byteA = bytearray(byteA) while n > len(byteA) : byteA.insert(0,0) return bytes(byteA)
def ternary_operator_v(x, iflogic, assertion, elselogic): """ Apply ternary operator logic executing functions. Functions should receive a single value: `x`. Better if you see the code: `return iflogic(x) if assertion(x) else elselogic(x)` Parameters ---------- x The value to...
def count_padding_bases(seq1, seq2): """Count the number of bases padded to report indels in .vcf Args: seq1, seq2 (str): alleles in .vcf Returns: n (int): Examples: REF ALT GCG GCGCG By 'left-alignment', REF and ATL are alignmed: ...
def peak_to_subpeak_list(chrom,start,end,size=60): """ Take the given peak, split into a list of subregions that make up the peak """ num_subpeaks = int(end) - int(start) // int(size) start_list = list(range(start,end,size)) end_list = start_list[1:] last_endpoint = start_list[-1] + size i...
def rgb_to_ansi(r, g, b): """ Convert an rgb color to ansi color """ (r, g, b) = int(r), int(g), int(b) if r == g & g == b: if r < 8: return int(16) if r > 248: return int(230) return int(round(((r - 8) / 247) * 24) + 232) to_ansi_range = lambda a...
def deol(s): """Remove any EOL from a line.""" return s.rstrip("\r").rstrip("\n")
def transform_detection(p0,detections,detect_thresh): """Convert the result of the detection from a cropped part of image to the original image coordinates. Parameters ---------- p0 : tuple The top-left point used for cropping the image (x,y) detections : list A list of lists f...
def greet(name): """Make a function that will return a greeting statement that uses an input. Args: name (str): A persons name. Returns: str: "Hello, <name> how are you doing today?". """ return "Hello, {} how are you doing today?".format(name)
def convert_from(client, denomination, amount): """ Convert the amount from 18 decimals to the dedsired precision """ if denomination == 'nct': return client.from_wei(amount, 'ether') elif denomination == 'nct-gwei': return client.from_wei(amount, 'gwei') elif denomination == 'nc...
def get_slack_user_fields(user_info): """ Get SlackUser fields from Slack 'user' type https://api.slack.com/types/user """ return { "username": user_info["id"], "readable_name": user_info["profile"]["real_name"], "avatar": user_info["profile"]["image_24"], }
def time2sample(time: float, sample_rate: int) -> int: """converts time to number of sample Args: time (float): time in seconds to be converted into samples sample_rate (int): sample rate to use Returns: int: sample """ return round(time * sample_rate)
def remove_line_break(text): """Remove line breaks from text""" return text.replace("\n", "")
def dict2tuple(d): """Build a tuple from a dict. :param d: The dict to coherence into a tuple. :returns: The dict d in tuple form. """ items = list(d.items()) items.sort() return tuple(items)
def sequence_pairs_of_minibatches(minibatches, direction="forward_val"): """ turn minibatches into pairs. ((x_i, y_i), (x_i+1, y_i+1)) """ pairs = [] if "forward" in direction: for i in range(len(minibatches)): if i == len(minibatches) - 1: continue j = i + 1 if i < (len(minibatches) - 1) else 0 xi, y...
def fformat(float_num, precision): """ https://stackoverflow.com/a/44702621/3453033 """ assert isinstance(precision, int) and precision > 0 return ('{{:.{}f}}' .format(precision) .format(float_num) .rstrip('0') .rstrip('.'))
def deepcopy_basic_type(obj: object) -> object: """ deepcopy an object without copy the complicated objects. This is useful when you want to generate Qlib tasks and share the handler NOTE: - This function can't handle recursive objects!!!!! Parameters ---------- obj : object ...
def get_order(order): """ All the orders they create look something like this: "milkshakepizzachickenfriescokeburgerpizzasandwichmilkshakepizza" Their preference is to get the orders as a nice clean string with spaces and capitals like so: "Burger Fries Chicken Pizza Pizza Pizza Sandwich Milksha...
def strip_string(val: str) -> str: """ Returns ``val`` as a string, without any leading or trailing whitespace. :param val: """ return str(val).strip()
def _element_fill_join(elements, width): """Create a multiline string with a maximum width from a list of strings, without breaking lines within the elements""" s = '' if(elements): L = 0 for i in range(len(elements) - 1): s += str(elements[i]) + ', ' L += len(el...
def size(obj): """Returns the size of an object in bytes""" try: return obj.__sizeof__() except: return 0
def echo(value, prompt="Value"): """Debug function to print a value, then return it. Talon debugging is limited. Wrap any value with this function to echo it without affecting functionality. """ print(f"{prompt}: {value}") return value
def sample(i): """Helper method to generate a meaningful sample value.""" return 'sample{}'.format(i)
def AppIdWithDefaultPartition(app_id, default_partition): """Add a partition to an application id if necessary.""" if not default_partition: return app_id if '~' in app_id: return app_id return default_partition + '~' + app_id
def parse_game_features(s): """ Parse the game features we want to detect. """ game_features = ['target', 'enemy', 'health', 'weapon', 'ammo'] split = list(filter(None, s.split(','))) assert all(x in game_features for x in split) return [x in split for x in game_features]
def odd_even_sum(numbers): """Returns the sum of all even and all odd digits in the given number""" numbers_list = [int(num) for num in str(numbers)] odd_nums = [] even_nums = [] for index in range(len(numbers_list)): if numbers_list[index] % 2 == 0: even_nums.append(numbe...
def netloc_parser(data): """Parse the netloc parameter. :returns: username, url. """ if data and '@' in data: first_at = data.index('@') return (data[0:first_at] or None), data[first_at + 1:] or None else: return None, data or None
def replace_escape_codes(input_str): """Replace escape codes function Parameters ---------- input_str : str String of input Returns ------- str Sting to replace escape codes to print properly """ return input_str.replace('&quot;', '"').replace('&#039;', "'").replace...
def getfields(comm): """get all the fields that have the key 'field' """ fields = [] for field in comm: if 'field' in field: fields.append(field) return fields
def merge_dict_of_dicts(list_of_dicts): """ merges list of dicts arg: list of dicts (to be merged) returns: merged dict """ final_dict = {} for d in list_of_dicts: for k, v in d.items(): final_dict.setdefault(k, []).append(v) final_dict.update((k, [item for sublist i...
def mode(data): """ function to get mode of data, only returns the first it encounters if there are more than 1 mode """ mode = max(data, key=data.count) return mode
def _format_size(size): """ Format size in bytes, kb, or mb """ if size < 1000: return f"{size} bytes" if size >= 1000000: return f"{size/1000000:.2f} MB" if size >= 1000: return f"{size/1000:.2f} kB"
def unwrap(url): """unwrap('<URL:type://host/path>') --> 'type://host/path'.""" url = str(url).strip() if url[:1] == '<' and url[-1:] == '>': url = url[1:-1].strip() if url[:4] == 'URL:': url = url[4:].strip() return url
def isValidTCSresponse(response): """ Argumets: response Verifies if the argument is valid, returns a boolean """ if "UNR EOF" in response: print('Request cannot be answered, try change language') return False return True
def _get_p_survival(block=0, nb_total_blocks=110, p_survival_end=0.5, mode='linear_decay'): """ See eq. (4) in stochastic depth paper: http://arxiv.org/pdf/1603.09382v1.pdf """ if mode == 'uniform': return p_survival_end elif mode == 'linear_decay': return 1 - ((block + 1) / n...
def constructUniformAllelicDistribution(numalleles): """Constructs a uniform distribution of N alleles in the form of a frequency list. Args: numalleles (int): Number of alleles present in the initial population. Returns: (list): Array of floats, giving the initial freq...
def crc64(inpkt) : """ Returns 64 bit crc of inpkt binary packed string inpkt inpkt is bytes in python3 or str in python2 returns tuple of two 32 bit numbers for top and bottom of 64 bit crc """ inpkt = bytearray(inpkt) polytop = 0x42f0e1eb polybot = 0xa9ea3693 crctop = 0xffffff...
def _validate_usecols_names(usecols, names): """ Validates that all usecols are present in a given list of names. If not, raise a ValueError that shows what usecols are missing. Parameters ---------- usecols : iterable of usecols The columns to validate are present in names. nam...
def gradY(x, y): """ Evaluates Y-gradient of Beale at x, y @ In, x, float, value @ In, y, float, value @ Out, gradY, float, Y-gradient of Beale """ tot = 0 consts = (1.5, 2.25, 2.625) for i in range(1, 4): tot += 2 * i * x * (x * (y**i - 1) + consts[i-1]) return tot
def pre_measure(node, q, anc, mes): """mes is either I, X, Y, or Z""" # Create ancilla if mes == "I": return None elif mes == "X": q.H() q.cnot(anc) q.H() elif mes == "Y": q.K() q.cnot(anc) q.K() # q.rot_X(-64) # Rotation -pi/2 elif...
def get_ground_truth_module_source(target_name, command_str, array_strs): """Gets the source of a module that will contain the ground truth. Args: target_name: Name of the target. command_str: String of the command name used to generate the ground truth values. array_strs: List of strings that en...
def ConvertPrivateIpv6GoogleAccess(choice): """Return PrivateIpv6GoogleAccess enum defined in mixer. Args: choice: Enum value of PrivateIpv6GoogleAccess defined in gcloud. """ choices_to_enum = { 'DISABLE': 'DISABLE_GOOGLE_ACCESS', 'ENABLE_BIDIRECTIONAL_ACCESS': 'ENABLE_BIDI...
def _merged_maxderiv(maxA,maxB): """ Calculate the maxderiv of a merged DFun. Parameters ---------- maxA, maxB : int or None maxderiv of merged DFun. Returns ------- int or None The maxderiv of the merger. """ if maxA is None and maxB is None: maxd...
def format_percentage(rid, adata, bdata): """Method to calculate percentage of bdata out of adata.""" try: fdata = ['0'] * len(bdata) for i, itm in enumerate(bdata): d_data = float(int(adata[i])) n_data = float(int(bdata[i])) p_data = (n_data / d_data) * 100 i...
def validMountainArray(A): """ :type A: List[int] :rtype: bool """ N = len(A) i = 0 # walk up while i+1 < N and A[i] < A[i+1]: i += 1 # peak can't be first or last if i == 0 or i == N-1: return False # walk down while i+1 < N and A[i] > A[i+1]: ...
def seconds(seconds=0, minutes=0, hours=0, days=0, weeks=0): """Returns a value in seconds given some minutes, hours, days, or weeks.""" return seconds + minutes*60 + hours*3600 + days*86400 + weeks*604800
def calculate_fantasy_points(player) -> float: """ Calculate the fantasy points this player earned from the formula Kill = 0.3 Death = -0.3 Assist = 0.15 Last Hit = 0.003 Gold per minute = 0.002 EXP per minute = 0.002 Seconds of enemy stuns = 0.07 Every 1000 allied healing done ...
def _webwallet_support(coin, support): """Check the "webwallet" support property. If set, check that at least one of the backends run on trezor.io. If yes, assume we support the coin in our wallet. Otherwise it's probably working with a custom backend, which means don't link to our wallet. """ ...
def target_tensor(len, labels, scores): """ create the target by labels and scores """ target = [0]*len for id, l in enumerate(labels): target[l] = scores[id] return target
def crear_cola(ncola): """Crear cola.""" primer = [10, 400] listpos = [primer] for i in range(1, ncola): pos = [listpos[i - 1][0] + 72, 400] listpos.append(pos) return listpos
def without_tests(tests, without): """Exclude tests from a list.""" return [t for t in tests if t not in without]
def is_anagram(word1, word2): """Two words are anagrams if you can rearrange the letters from one to spell the other. Write a function called is_anagram that takes two strings and returns True if they are anagrams.""" chars1 = list(word1) chars1.remove(" ") chars2 = list(word1) chars2.remove(" ") ...
def version_tuple_to_str(version_tuple, separator='.'): """ Turns something like (X, Y, Z) into "X.Y.Z" :param version_tuple: the tuple identifying a software Semantic version :type version_tuple: tuple :param separator: the character to be used as separator :type separator: str, defaults to '.'...
def is_valid(isbn): """ Given a string the program will check if the provided string is a valid ISBN-10. :param isbn: :return: """ # ISBN is invalid in case input string is empty if not isbn or isbn == '': return False # Converting from strings to numbers digits = [] ...
def is_overlapping(segment_time, previous_segments): """ Checks if the time of a segment overlaps with the times of existing segments. Arguments: segment_time -- a tuple of (segment_start, segment_end) for the new segment previous_segments -- a list of tuples of (segment_start, segment_end) f...
def process_enclitics(word): """ Not yet able to process enclitics """ word = word.split('-') #print(word) return(''.join(word[0]))
def is_matching_set(cards): """Determine if the set of 3 `Card`s defines a valid matching set (that can be redeemed). A set is matching if the symbols on the 3 cards are either all the same or all different. (e.g. `[1, 1, 1]` matches, `[1, 0, 1]` does not, but `[0, 1, 2]` is a matching set. `cards` --...
def _smartquote(s, quoteit=True, qchar='"'): """ smartquote a string so that internal quotes are distinguished from surrounding quotes for SPSS and return that string with the surrounding quotes. qchar is the character to use for surrounding quotes. if quoteit is True, s is a string that needs quoting;...
def species_icon_url_for_dimension(species_icon_key, width, height): """ Return the icon URL for a specific species icon 'key' (the 'icon' field in species definitions). """ return "/static/img/species_icons/%s_%dx%d.png" % (species_icon_key, width, height);
def finder(parent, starts_with, matching_object): """ignores unique numbers in keys""" candidates = {k for k in parent.keys() if k.startswith(starts_with)} nested_candidates = {} for candidate in candidates: split_candidate = candidate[len(starts_with)+1:].split('.', 1) if len(split_ca...
def partition_linkedlist_around_value(linked_list, x): """Patitions a linkedlist around a given value x.data Travese the linked list, insert nodes with node.data >= x at the end. Args: linked_list: An instace object of class LinkedList. x: value of type LinkedList.data Returns: ...
def scrubSuffixes(name): """ Removes commonly seen suffixes. """ suffixes = ["I", "II", "III", "IV", "Jr.", "Sr.", "Jr", "Sr", "MA", "MD", "1st", "2nd", "3rd"] names = name.split() if names[-1] in suffixes: names = names[:-1] else: names = names[0:] return ' '.join(names...
def map_type(ansible_type: str) -> str: """Return JSON date type for a given Ansible type.""" # https://json-schema.org/understanding-json-schema/reference/type.html # raw is used for file mode by ansible if ansible_type in ['str', 'filename', 'path', 'raw', 'sid']: return 'string' if ansibl...