content
stringlengths
42
6.51k
def divides_evenly(a: int, b: int) -> bool: """Determine if a can be divided by b evenly.""" return bool(a % b == 0)
def mean_difference(own_team_scores, enemy_team_scores, neutral_scores, assassin_scores, weights=(1, 1, 1, 1)): """ Calculates the difference between the mean of own_team_scores and the mean of the combination of enemy_team_scores, neutral_scores and assassin_scores. """ own_team_scores, enemy_team_scores, neutral_sc...
def reverse_table(theTab): """ This function reverse the table Returns : the reverse of theTab """ for i in range(len(theTab)//2): tmp = theTab[i] endVal = len(theTab)-i-1 theTab[i] = theTab[endVal] theTab[endVal] = tmp #r...
def remove_between_sequence(sequence, distance): """Return a resource to remove from the sequence, given the distance, or None if no resource seems worthy to remove""" id_to_remove = None val_to_remove = None for i in range(1,len(sequence)-1): value_distance = min(distance(sequence[i-1],sequence...
def padlist(container, size, default=None): """Pad list with default elements. Examples: >>> first, last, city = padlist(["George", "Costanza", "NYC"], 3) ("George", "Costanza", "NYC") >>> first, last, city = padlist(["George", "Costanza"], 3) ("George", "Costanza", None) ...
def bucket_sort(list_to_sort, function): """ Bucket sort algortihm When used with uniform distribution expected linear time """ buckets = [[] for _ in range(len(list_to_sort))] max_value = max([function(el) for el in list_to_sort]) # put each value in proper bucket for j in list_to_sor...
def revcomp(seq): """ Reverse Complement a string Parameters: ----------- seq :: str Returns: -------- str """ comp = {'A':'T', 'C':'G', 'G':'C', 'T':'A', 'N':'N'} return ''.join(comp[nuc] for nuc in seq[::-1])
def velocity_transformation(frame_velocity: float, observed_velocity: float) -> float: """ Computes the velocity transformation for a given frame velocity and observed velocity. The frame velocity is the velocity of the new frame relative to this frame. The observed velocity is a velocity measured in th...
def is_set(obj) -> bool: """Checks if the given object is either a set or a frozenset.""" return isinstance(obj, (set, frozenset))
def get_number_of_residues(residues): """ Return number of residues from residue list. Parameters ---------- residues : list can be list or strings e.g.: ["1", "1", "2", "3", "3"] or sequenece of chars e.g.: "aaacccdddaaa" Returns ------- int ...
def sign(x: int) -> int: """Return the sign of the argument. [-1, 0, 1]""" return x and (1, -1)[x < 0]
def get_word2index(vocab): """ :param vocab: list of vocabulary :return: dictionary of word to index """ start_idx = 4 word2idx = dict([(word, idx+start_idx) for idx, word in enumerate(vocab)]) word2idx['SOS'] = 0 word2idx['EOS'] = 1 word2idx["<UNK>"] = 2 word2idx["<PAD>"] = 3 ...
def get_K(jfdb): """ Infer K from jellyfish db. """ j = jfdb.rsplit('_', 1)[0].rsplit('-', 1)[-1] assert j[0] == 'K' return int(j[1:])
def _is_backfill(event): """Checks if the event corresponds to a backfill request. Args: event: the event generated by pub/sub trigger Returns: True if message contains backfill attribute False otherwise """ return event.get('attributes') is not None and event.get('attributes').get( 'backf...
def ParseSnip(content): """Return the snippet based on the content.""" found = content.find('<!--more-->') if found >= 0: return content[:found]
def intersperse(lst, item): """ from lst = [0.75, 1.2, 1.3, 0.8, 1.4, 1.2] to lst = [0.75, 1, 1.2, 1, 1.3, 1, 0.8, 1, 1.4, 1, 1.2, 1] """ result = [item] * (len(lst) * 2 - 1) result[0::2] = lst return result
def _format_duration(duration): """Formats a duration.""" duration = int(1000 * duration) duration, ms = divmod(duration, 1000) duration, s = divmod(duration, 60) h, m = divmod(duration, 60) return "{:d}:{:02d}:{:02d}.{:03d}".format(h, m, s, ms)
def str2endpoint(val): """ Convert string to (host, port) tuple Format: [host:]port default host is 'localhost' """ splited = val.split(":") if len(splited) > 2: raise RuntimeError("Invalid argument") if len(splited) == 2: return (splited[0], int(splited[1])) return ("lo...
def sanitize(msg): """ Sanitizes the given string to prevent :py:func:`format_color` from substituting content. For example, when the string ``'Email: {user}@{org}'`` is passed to :py:func:`format_color` the ``@{org}`` will be incorrectly recognized as a colorization annotation and it will fail...
def function_exists(object_to_check, fn_name): """Check if function exists in the object Args: object_to_check: object to be searched for the existence of the function fn_name (str): name of the function Returns: bool: if function is present in the provided object """ if ha...
def compute_readout(params): """ Computes readout time from epi params (see `eddy documentation <http://fsl.fmrib.ox.ac.uk/fsl/fslwiki/EDDY/Faq#How_do_I_know_what_to_put_into_my_--acqp_file.3F>`_). .. warning:: ``params['echospacing']`` should be in *sec* units. """ epi_factor = 1.0 acc_f...
def odd_even_sort(input_list: list) -> list: """this algorithm uses the same idea of bubblesort, but by first dividing in two phase (odd and even). Originally developed for use on parallel processors with local interconnections. :param collection: mutable ordered sequence of elements :return: sa...
def tokenizer_pos(pos_tuplets): """ Tokenizer that tokenizes a list of part of speech tuplets into array of tokens for each word, and an array for each tag :param pos_tuplets: List of pos tuplets :return: tokens, list of word tokens; tokens_tags, list of pos tags """ tokens = [] token...
def convert_temp(num, initial, final): """Converts temperature from one unit set to another Parameters ---------- num : float, optional Number to convert. I not specified, will return the appropriate conversion factor. initial : str Units that num is curr...
def _getBit(x, i): """Returns true iff the i'th bit of x is set to 1.""" return (x >> i) & 1 != 0
def hostglob_matches(glob: str, value: str) -> bool: """ Does a host glob match a given value? """ rc = False if ('*' in value) and not ('*' in glob): # Swap. tmp = value value = glob glob = tmp if glob == "*": # special wildcard rc=True elif glob.e...
def set2rel(s): """ Convert a set containing individuals (strings or numbers) into a set of unary tuples. Any tuples of strings already in the set are passed through unchanged. For example: - set(['a', 'b']) => set([('a',), ('b',)]) - set([3, 27]) => set([('3',), ('27',)]) :type s:...
def dist(s1, s2): """Determine hamming distance""" hamm_diff = 0; len_diff = 0 if len(s1) != len(s2): len_diff = abs(len(s1) - len(s2)) for char1, char2 in zip(s1, s2): if char1 != char2: hamm_diff += 1 return hamm_diff + len_diff
def make_album(artist, title): """Build a dictionary describing a music album.""" return {'artist_name': artist, 'album_title': title}
def yesno(boolean, yes, no): """ternary in python: boolean? yes:no""" return (no, yes)[boolean]
def abs_smooth_dv(x, x_deriv, delta_x): """ Compute the absolute value in a smooth differentiable manner. The valley is rounded off using a quadratic function. Parameters ---------- x : float Quantity value x_deriv : float Derivative value delta_x : float Half wid...
def theta_beta_Hyper(theta, gamma): """ Computes the beta values for given theta in the hypersonic limit :param theta: (np.array), deflection angle (wedge angle) :param gamma: (float), adiabatic coefficient :return: """ return theta * (gamma + 1) /2
def location(observatory): """Return the observatory location as a dictionary""" if observatory == 'Gemini-North': latitude = 297.35709 # 19:49:25.7016 longitude = -155.46906 # -155:28:08.616 elevation = 4213 # meters elif observatory == 'Gemini-South': ...
def to_mixed_case(s): """ convert upper snake case string to mixed case, e.g. MIXED_CASE becomes MixedCase """ out = '' last_c = '' for c in s: if c == '_': pass elif last_c in ('', '_'): out += c.upper() else: out += c.lower() ...
def get_path(network): """ Select the right path given the chosen network. :type network: String :param network: Name of the desired network, e.g.: 'vgg16','xception'. :return: the path to the Experiments folder given the chosen network. """ # Just verify wich network was passed to the func...
def clean_scores(scores): """Filters the scores list to obtain all numerical values.""" candidate_scores = list() for score in scores: if isinstance(score, int) or isinstance(score, float): candidate_scores.append(score) return candidate_scores
def check_value_type(value): """ Args: value: the value for current key in the dictionary. Returns: returns a boolean value whether the value passed in is primitive. >>> check_value_type('Perfect') False >>> check_value_type(10) True >>> check_value_type(3.1415) True ...
def get_repadding(crops, d_shape): """ Returns ------- tuple padding values to restore 3D np array after it was cropped. Parameters ---------- crops : list 3 tuples in a list [(nz1,nz2), (ny1,ny2), (nx1,nx2)] d_shape : tuple or...
def snp_to_text(snp): """Convert SNP objects into strings.""" return f"{snp['orientation']}@{snp['pos']}:{snp['ref']}>{snp['alt']}"
def is_valid_tour(nodes, num_nodes): """Sanity check: tour visits all nodes given. """ return sorted(nodes) == [i for i in range(num_nodes)]
def round_two_significant_digits(num): """ :param num: :return: """ return float('%s' % float('%.1g' % num))
def ra_as_hours(ra_degrees): """ Input: float of Right Ascension in degrees. Returns: string of RA as hours, in hex, to the nearest 0.001 RA seconds. from photrix August 2018. """ if (ra_degrees < 0) | (ra_degrees > 360): return None n_ra_milliseconds = round((ra_degrees * 3600 * 100...
def index_merge(lsts): """ Merging algorithm that merges lists if they are not disjoint. Returns a list of disjoint lists. :param lsts: list of lists :type: list :return: list of disjoint lists :rtype: list """ newsets, sets = [set(lst) for lst in lsts], [] while len(sets) != len...
def get_duplicates(iterable): """Find and return any duplicates in the iterable.""" duplicates = {} for i in iterable: duplicates.setdefault(i, 0) duplicates[i] += 1 return [d for d in duplicates if duplicates[d] > 1]
def filter_apiv2_hook(endpoints): """This excludes API endpoints for AirOne API(v1). React views refer to only AirOne API(v2). So it's not necessary to generate API(v1)'s OpenAPI schema. """ result = [] for (path, path_regex, method, callback) in endpoints: if "/api/v2/" in path: ...
def lookup_gas_datasources(lookup_dict, gas_data, source_name, source_id): """ Check if the passed data exists in the lookup dict Args: lookup_dict (dict): Dictionary to search for exisiting Datasources gas_data (list): Gas data to process source_name (str): Name of cour...
def search(x, thing): """Search for x in thing. True iff found. Utility used only for tests in this file.""" if isinstance(thing, dict): for y in thing.values(): if search(x, y): return True elif isinstance(thing, list): for y in thing: if searc...
def prepend(the_list, the_str): """Add string to the front of each item in a list Args: list (list): List of values str (string): string to prepend """ the_str += "{0}" the_list = [the_str.format(i) for i in the_list] return the_list
def calc_padding(length, block_size): """ Calculate how much padding is needed to bring `length` to a multiple of `block_size`. :param int length: The length of the data that needs padding. :param int block_size: The block size. """ if length % block_size: return block_size - (lengt...
def code(msg: str): """Format to markdown code block""" return f'```{msg}```'
def _asymptotic_decay(x: float, t: int, max_t: int) -> float: """ Asymptotic decay function. Can be used for both the learning_rate or the neighborhood_radius. :param x: float: Initial x parameter :param t: int: Current iteration :param max_t: int: Maximum number of iterations :return: float: C...
def AffectedPatches(action_history): """Get the patches affected by a set of actions. Args: action_history: An iterable of CLActions. Returns: A set of GerritPatchTuple objects for the affected patches. """ return set(a.patch for a in action_history)
def flat_map_attr(x: list, attr: str = 'note') -> list: """ Helper function for the DBLP note parsing :param x: :param attr: :return: """ ret = [] for i in x: if isinstance(i[attr], list): for j in i[attr]: if isinstance(j, str): re...
def set_current(channel: int, value: float): """ Sets current on channel to the value. """ return f"ISET{channel}:{value}"
def issorted(l): """ Return True if the argument list is sorted """ for i, el in enumerate(l[1:]): if el >= l[i - 1]: return False return True
def determine_override_key( dict1_in, dict2_in, file_join_key_in, priority_key_criteria_in ): """given the info about the barcode, then assign the boolean to which value to override""" if ( file_join_key_in in dict1_in and dict1_in[file_join_key_in][0] == priority_key_criteria_in ): ...
def format_last_online(last_online): """ Return the upper limit in seconds that a profile may have been online. If last_online is an int, return that int. Otherwise if last_online is a str, convert the string into an int. Returns ---------- int """ if isinstance(last_online, str): ...
def parse_coco_categories(categories): """Parses the COCO categories list. The returned ``classes`` contains all class IDs from ``[0, max_id]``, inclusive. Args: categories: a dict of the form:: [ ... { "id": 2, ...
def is_sequence(obj): """ Grabbed from Python Cookbook / matplotlib.cbook. Returns true/false for Parameters ---------- obj : iterable """ try: len(obj) return True except TypeError: return False
def exercise_0(inputs): # DO NOT CHANGE THIS LINE """ This functions receives the input in the parameter 'inputs'. Change the code, so that the output is sqaure of the given input. """ output = inputs return output # DO NOT CHANGE THIS LINE
def separate_x_y(item, x_keys, y_keys): """Separate dataset into a tuple (X, Y) Args: dict ([type]): Each entry in tf dataset x_keys ([type]): List of key values y_keys ([type]): List of ky values Returns: tuple of each entry """ X = {} Y = {} for k, v in it...
def ip_port_hostname_from_svname(svname): """This parses the haproxy svname that smartstack creates, which is in the form ip:port_hostname. :param svname: A string in the format ip:port_hostname :returns ip_port_hostname: A tuple of ip, port, hostname. """ ip, port_hostname = svname.split(':', 1) ...
def charge_per_call( seconds, minimum, per_minute, charge_interval, connection=0): """Returns the charge for a call. Args: seconds: length of call minimum (seconds): calls are effectively at least this long per_minute: charge for a call of one minute charge_interval (sec...
def from_params_to_id(val): """ Function for creating string from test params. :param val: tuple Params of tests. :return: String presentation of params. """ return "params: {0}".format(str(val))
def _triple_to_three_strings(*one_triple): """This helper function is used to transform nodes into strings. Nodes are not uniquely generated.""" return str(one_triple[0]), str(one_triple[1]), str(one_triple[2])
def _reduce_datetimes(row): """Receives a row, converts datetimes to strings.""" row = list(row) for i in range(len(row)): if hasattr(row[i], 'isoformat'): row[i] = row[i].isoformat() return tuple(row)
def blocktrans_side2cen6(side_size): """ Convert from side rep to center rep In center rep, the 6 numbers are center coordinates, then size in 3 dims In side rep, the 6 numbers are lower x, y, z, then higher x, y, z """ lx,ly,lz = float(side_size[0]), float(side_size[1]), float(side_size[2]) hx,hy,h...
def get_sta_shift(sta, sta_shift): """ sta_shift must be a dictionary containing the station name to be shifted and the time shift in seconds e.g. {'STA':0.5}. """ if sta in sta_shift.keys(): return sta_shift[sta] else: return 0
def get_x_indicator_variable_index(i, j, k, l, m, n): """ Map the i,j,k,l indices to the sequential indicator variable index as generated by linear_objective_function_coefficients(). This is basically the (4-dimensional) 'array equation' (as per row-major arrays in C for example). Note that for...
def _table_format(value): """Format value for table.""" if isinstance(value, float): return f'{value:.2f}' else: return str(value)
def tform_to_format(tform): """Convert `TFORM` string in FITS binary table to format string in Python `struct` module. Args: tfrom (str): `TFORM` string in FITS binary table. Returns: str: A format string used in Python `struct` module. """ if tform == 'L': return 'b' # 1 byte, ...
def get_min_max(ints): """ Return a tuple(min, max) out of list of unsorted integers. Args: ints(list): list of integers containing one or more integers """ if(len(ints) == 0): # print('min_value : {} max_value : {}'.format(ints[0], ints[0])) return (0, 0) if(len(ints) =...
def vals_are_positive(vlist): """determine whether every value in vlist is positive""" for val in vlist: if val <= 0: return 0 return 1
def _get_difference(current, previous): """Return the percentage delta between the arguments.""" if current == previous: return 0 try: return (abs(current - previous) / previous) * 100.0 except ZeroDivisionError: # It means previous and only previous is 0. return 100.0
def assign_dates_to_tasks(date_list, n_tasks): """ For batch jobs, will want to split dates as evenly as possible over some number of tasks. """ output_lists = [[] for _ in range(min(n_tasks, len(date_list)))] j = 0 while j < len(date_list): for i in range(n_tasks): outp...
def loss_inversely_correlated_box_class_count_scaled(X, y): """ Return -1 * (concept_direction * prediction / box_class_count) where prediction = X[0] box_class_count = X[1] concept_direction = y """ eps = 1e-08 prediction, box_class_count, *_ = X concept_dir...
def parse_memory_line(line): """Parses the memory lines of an atom, returns the bytes of the observation 2c00f4a6 """ return [int(line[i:i + 2], 16) for i in range(0, len(line.strip()), 2)]
def findpop(value, lst): """ Return whether `value` is in `lst` and remove all its occurrences """ if value in lst: while True: # remove all instances `value` from lst try: lst.pop(lst.index(value)) except ValueError: break return True # and return yes we found the value ...
def row_contains_data(fieldnames, row): """Returns True if the value of atleast on of the fields is truthy""" for field in fieldnames: if row.get(field): return True return False
def _imag_2d_func(x, y, func): """Return imag part of a 2d function.""" return func(x, y).imag
def get(args, attr, default=None): """ Gets a command-line argument if it exists, otherwise returns a default value. Args: args: The command-line arguments. attr (str): The name of the command-line argument. default (obj): The default value to return if the argument is not found. De...
def get_attributes(obj, names): """Return attributes dictionary with keys from `names`. Object is queried for each attribute name, if it doesn't have this attribute, default value None will be returned. >>> class Class: ... pass >>> obj = Class() >>> obj.attr = True >>> obj.value =...
def default_none(ctx, _, value): """ click currently can not use None with tuple type it will return an empty tuple if the default=None details: https://github.com/pallets/click/issues/789 """ if not value: return None else: return value
def odd_even_transposition(arr: list) -> list: """ >>> odd_even_transposition([5, 4, 3, 2, 1]) [1, 2, 3, 4, 5] >>> odd_even_transposition([13, 11, 18, 0, -1]) [-1, 0, 11, 13, 18] >>> odd_even_transposition([-.1, 1.1, .1, -2.9]) [-2.9, -0.1, 0.1, 1.1] """ arr_size = len(arr) for...
def fix_35_activity_links(data): """Remove specific activity link bugs in ecoinvent 3.5 release""" remove_me = { # Was a link to RER, but in 3.5 there is only GLO # so can safely delete '25edb027-d7c0-4756-a051-cab82e4f6248', } link_iterator = (exc for ds in ...
def is_list_like(x): """Helper which returns `True` if input is `list`-like.""" return isinstance(x, (tuple, list))
def run_part_2(instructions, change_index): """ Run program recursively trying changes at successive nop/jmp instructions until program completes successfully """ acc = 0 cursor = 0 jmp_nop_index = 0 visited = set() while cursor < len(instructions): op, arg = instructions[cur...
def format_params(line, sep=':'): """Format keys in a dictionary and adds quotes to the keys. For example, {min: 0, max: 10} will result in ('min': 0, 'max': 10) Args: line (str): A string. sep (str, optional): Separator. Defaults to ':'. Returns: [str]: A string with keys quo...
def get_configs_from_labels(prefixes, labels): """Transforms a raw "labels" dict of (str, str) pairs into a list of dicts, each containing the configuration keys for a single trigger. """ trigger_configs = [] for trigger_prefix in prefixes: trigger_config = {} for key, value in label...
def product_except_self(nums): """ Given an array nums of n integers where n > 1, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i]. :param nums: list[int] :return: list[int] """ p = 1 n = len(nums) output = [] for i in ...
def get_second_level_domain(link): """ Given a URL, return the second level domain. """ return '.'.join(link.split('.')[-2:])
def display_word(word): """ Creates dashed display ex: _ _ _ _ _ """ return '{}'.format(len(word) * '_ ')
def hex_to_rgb(hexa): """Convert hex color to RGB color. :param hexa: Hex color :type hexa: str :return: RGB color :rtype: tuple """ return tuple(int(hexa[i:i+2], 16) for i in (0, 2, 4))
def cast_bool(value) -> bool: """ Tries to cast value to bool. Raises ValueError if value is ambiguous. Raises TypeError for unsupported types. :param value: value to cast :return: bool """ if isinstance(value, bool): return value if isinstance(value, str): if value.l...
def clean_data(row): """ Convert has_policy to boolean. """ if row["has_policy"].strip() == "Yes": row["has_policy"] = True return row
def is_list_of_valid_elem(value, elem_validator): """ Is the given value a list whose each element is checked by elem_check to be True? :param value: The value being checked :type value: Any :param elem_validator: The element checker :type elem_validator: Any -> bool :return: True if the given v...
def insertion_sort(arr): """Performs an Insertion Sort on the array arr.""" for i in range(1, len(arr)): key = arr[i] j = i-1 # 2 5 while key < arr[j] and j >= 0: # swap(key, j, arr) # 6 5 arr[j+1] = arr[j] ...
def strip_dot_git(url): """Strip trailing .git""" return url[: -len(".git")] if url.endswith(".git") else url
def normalize_ns(namespaces: str) -> str: """ Normalizes url names by collapsing multiple `:` characters. :param namespaces: The namespace string to normalize :return: The normalized version of the url path name """ return ':'.join([nmsp for nmsp in namespaces.split(':') if nmsp])
def twoSum(nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ res = [] seen = {} for i in range(len(nums)): print("curr_val (" + str(i) + "): " + str(nums[i])) remaining = target - nums[i] print ("remaining: " + str(remaining)) ...