content
stringlengths
42
6.51k
def alignmentTo2(alignment): """Converts an alignment to two-level with one sub-label.""" return [ (startTime, endTime, label, [(startTime, endTime, 0, None)]) for startTime, endTime, label, subAlignment in alignment ]
def is_var(name, config_dict): """Checks if the given configuration defines a variable Args: config_dict (any): A configuration Returns: bool: True if 'config_dict' defines a variable """ return isinstance(config_dict, int) or isinstance(config_dict, float) or isinstance(config_d...
def _flatten(d: dict) -> list: """Transform dict of sets in flat list :param d: dict of sets :return: list of tuples """ return [(key, v) for key, values in d.items() for v in values]
def prepend_all(stack, list): """ Prepend all of the items in the given stack onto the head of the given list. (Naturally tail-recursive.) For example: prepend_all([3, 2, 1], [4, 5]) -> [1, 2, 3, 4, 5] """ if stack == (): return list else: head, tail = stack ...
def build_slot_value(interpreted_value): """ Build a slot object with given interpretedValue. """ return { "shape": "Scalar", "value": { "originalValue": interpreted_value, "interpretedValue": interpreted_value, "resolvedValues": [interpreted_value] ...
def to_char(integer): """ Convert integer into charactere >>> ord(to_char(1)) 1 >>> ord(to_char(0x80)) 128 """ if integer >= 0x80: return eval(u"'\\x%02X'"%integer) else: return chr(integer)
def fizz_buzz_decode(i, prediction): """decodes a prediction {0, 1, 2, 3} into the corresponding output""" return [str(i), "fizz", "buzz", "fizzbuzz"][prediction]
def is_allequal(List): """ Test if all elements of a list are the same. return True if all elements are equal return False if elements are different """ return all([x == List[0] for x in List])
def find_skips_in_seq(numbers): """Find non-sequential gaps in a sequence of numbers :type numbers: Iterable of ints :param numbers: Iterable to check for gaps :returns: List of tuples with the gaps in the format [(start_of_gap, end_of_gap, ...)]. If the list is empty then there are no...
def normalize_text(text): """Normalize a text by converting it to lower case and removing excess white space.""" return " ".join(text.casefold().split())
def get_new_hw(h, w, max_size, shorter_edge_size): """Get the new img size with the same ratio.""" scale = shorter_edge_size * 1.0 / min(h, w) if h < w: newh, neww = shorter_edge_size, scale * w else: newh, neww = scale * h, shorter_edge_size if max(newh, neww) > max_size: scale = max_size * 1.0 ...
def type_of_user(datum, city): """ Takes as input a dictionary containing info about a single trip (datum) and its origin city (city) and returns the type of system user that made the trip. Remember that Washington has different category names compared to Chicago and NYC. """ user...
def get_new_id(json_data: dict) -> int: """Generate a new ID based on existing {json_data}. Args: json_data (dict): The JSON data with keys as the ID. Returns: int: An ID a new resource can be assigned to. """ keys = list(json_data.keys()) if not keys: return 1 last...
def verse(bottle): """ Sing a verse """ current_bottle = '1 bottle' if bottle == 1 else f'{bottle} bottles' next_bottle = 'No more bottles' if bottle == 1 else f'{bottle - 1} bottle' if bottle == 2 else f'{bottle - 1} bottles' return '\n'.join([ f'{current_bottle} of beer on the wall,', ...
def assert_model_predictions_deviations( y_pred: float, y_pred_perturb: float, threshold: float = 0.01 ): """Check that model predictions does not deviate more than a given threshold.""" if abs(y_pred - y_pred_perturb) > threshold: return True else: return False
def get_release(state, release_name): """ Get Release from all deployed releases """ if state is not None: for release in state: if release['name'] == release_name: return release return None
def collabel_2_index(label): """Convert a column label into a column index (based at 0), e.g., 'A'-> 1, 'B' -> 2, ..., 'AA' -> 27, etc. Returns -1 if the given labe is not composed only of upper case letters A-Z. """ # The following code is adopted from # https://stackoverflow.com/questions...
def left_next_day(departure): """Return True if departed next day. False, otherwise.""" planned = departure[0] actual = departure[1] if not actual: return False return actual.day > planned.day
def merge_duplicates(nodes): """Given a list of nodes with the same-length label, merge any duplicates (by combining their children)""" found_pair = None for lidx, lhs in enumerate(nodes): for ridx, rhs in enumerate(nodes[lidx + 1:], lidx + 1): if lhs.label == rhs.label: ...
def handle_path_win(path): """find the proper path if using windows based OS""" if path.endswith("\\"): return "{0}simc.exe".format(path) return "{0}\\simc.exe".format(path)
def eos_to_linux_intf(eos_intf_name): """ @Summary: Map EOS's interface name to Linux's interface name @param eos_intf_name: Interface name in EOS @return: Return the interface name in Linux """ return eos_intf_name.replace('Ethernet', 'et').replace('/', '_')
def _fastq_slicers(idxs_arg): """Convert a string input of slicing indexes to a list of slice objects. Arg: idx_arg: A string defining regions to be sliced out from a sequence. It uses the following syntax rules: - The first index value is 1; - Regions are se...
def break_words(sentence): """This function will break up words for us.""" return sentence.split(' ')
def allocate_receiver_properties(receivers, param_values, demand): """ Generate receiver locations as points within the site area. Sampling points can either be generated on a grid (grid=1) or more efficiently between the transmitter and the edge of the site (grid=0) area. Parameters ----...
def get_byte_as_int(encoded: bytearray, idx: int) -> tuple: """ Returns a byte value as int and next to be read index :param encoded: bytearray :param idx: index to lookup :return: tuple of byte read and next index """ return encoded[idx], idx + 1
def line_parser(buf): """ Parses the given `buf` as str representation of list of values (e.g. 'ovs-vsctl list-br' command or 'docker ps' command). :param buf: str type value containing values list. :return: list of parsed values. """ values = [] for line in buf.split('\n'): if...
def check_derivation(derivation, premises, conclusion): """Checks if a derivation is ok. If it is, returns an empty list, otherwise returns [step, error] Does not check if the conclusion and premises are ok, for that there is another function""" for step in sorted(derivation): try: # ...
def is_missing_conversation_id(config): """" :param config: JSON object :return: True if the config miss the conversation ID """ return "conversation_id" not in config
def levels_content(number_of_levels): """Returns the contents of each pyramid level, given an N number of levels.""" levels = [] for level in range(1, number_of_levels + 1): level_content = '1' for number in range(2, level + 1): level_content += f" {number}" for numbe...
def safir_problem_definition_protobuf(str_parameterised_problem_definition, dict_safir_params): """ :param str_parameterised_problem_definition: :param kwargs: :return: """ dict_safir_param_ = dict() for k, v in dict_safir_params.items(): if isinstance(v, int) or isinstance(v, float...
def get_blank_wf_data( dd ): """Get workflow data inside flowCode by default""" dd['data'] = {} dd['viewName'] = '' return dd
def gcd(a, b): # (1) """ Returns the greatest commond divisor of a and b. Input: a -- an integer b -- an integer Output: an integer, the gcd of a and b Examples: >>> gcd(97,100) 1 >>> gcd(97 * 10**15, 19**20 * 97**2) ...
def make_row_address(ri, excel_style): """Make row address for print.""" if excel_style: return f'{ri+1}:{ri+1}' else: return f'R{ri+1}'
def comparable_dictionaries(d1, d2): """ :param d1: dictionary :param d2: dictionary :return: True if d1 and d2 have the same keys and False otherwise util function to compare two dictionaries for matching keys (including nested keys), ignoring values """ for key in d1: if key n...
def get_comparison_columns(table_1, table_2, include_columns, exclude_columns): """ Given two tables and inclusion / exclusion rules, return a list of columns that will be used for comparison. Inclusion/exclusion rules apply to both tables, the resulting sub-tables must have matching columns. ...
def array(value): """Always return a list """ if type(value) in (list, tuple): return value else: return [value]
def inflate_cost(raw_cost, current_cpi, cpi_time_variant): """ Calculate the inflated cost associated with raw_cost, considering the current CPI and the CPI corresponding to the date considered (cpi_time_variant). Returns: The inflated cost """ return raw_cost * current_cpi / cpi_time_...
def is_string(maybe_string): """ Check if the given item is a String :param maybe_string: String :return: Boolean """ return isinstance(maybe_string, str)
def periodic_commit(start, length, split): """Return the hourly commit within interval according to split().""" return start + split() * length
def converter_in(converters_desc, converter): """ Is the converter in the desc :param converters_desc: :param converter: :return: """ for converter_desc in converters_desc: if converter in converter_desc: return True # end if # end for return False
def joiner(items): """properly conjuct items""" num_items = len(items) if num_items == 0: return '' elif num_items == 1: return items[0] elif num_items == 2: return ' and '.join(items) else: items[-1] = 'and ' + items[-1] return ', '.join(items)
def epochTime(seconds): """Convert the time expressed by 'seconds' since the epoch to string""" import time return time.ctime(seconds)
def find_paths(cities_left, location_distances, total_distance, path): """Find possible paths between cities_left, with location_distances.""" if len(cities_left) == 1: return [(total_distance, path)] paths = [] source_cities = [path[-1]] if path else cities_left for city in source_cities: ...
def dump_byte_array(aaa): """ Stringify a byte array as hex. """ out = '' for bbb in aaa: pair = "%02x" % bbb out += pair return out
def build_suffix_tree(text): """ Build a suffix tree of the string text and return a list with all of the labels of its edges (the corresponding substrings of the text) in any order. """ result = [] # Implement this function yourself return result
def list_str_prepend(pre, list_str): """ Helper function that preprends an item to a stringified comma separated list of items. """ return pre + ("" if list_str == "" else ", " + list_str)
def unqiue_with_order(lst) -> list: """Returns only the unique values while keeping order""" ulst = [] uvals = set() for v in lst: if v in uvals: continue uvals.add(v) ulst.append(v) return ulst
def shrink(line, bound=50, rep='[...]'): """Shrinks a string, adding an ellipsis to the middle""" l = len(line) if l < bound: return line if bound <= len(rep): return rep k = bound - len(rep) return line[0:k / 2] + rep + line[-k / 2:]
def average_above_zero(tab): """ brief : computes the average of the positive values in an array Args : tab : a list of numeric value, expect at list one positive value return: the computed average as a float value raise : ValueError if no positive value is found Valu...
def find_tokens(all_smiles): """ Find all different tokens from a set of data to get the grammar :param all_smiles: list of list of tokens :type all_smiles: list of list of tokens :return: different tokens in all_smiles """ val = ["\n"] for smile in all_smiles: for a in smile: ...
def square_area(side): """Returns the area of a square""" return float(side**2)
def drop_unspecified_subcategories(db): """Drop subcategories if they are in the following: * ``unspecified`` * ``(unspecified)`` * ``''`` (empty string) * ``None`` """ UNSPECIFIED = {'unspecified', '(unspecified)', '', None} for ds in db: if ds.get('categories')...
def unif(x, p0=0.5, r=0.1): """Define indicative function of interval in [0, 1] given center and radius. Parameters ---------- x : float in [0, 1] function variable p0 : float in [0, 1] (optional) center r : float (optional) radius Returns ------- 0 or 1 : v...
def parse_bits( field ): """Return high, low (inclusive).""" text = field.get( 'bits' ) parts = text.split( ':' ) if len( parts ) == 1: return parts * 2 elif len( parts ) == 2: return parts else: assert False, text
def search_parameter_generator(count=100, language='en', entity_bool=False): """Genrates search parameters for Twitter API search """ SEARCH_PARAMS = { 'count': count, 'lang': language, 'include_entities': entity_bool } return SEARCH_PARAMS
def combinations_nb(n): """Return number of (i, j) combinations with 0 <= i < j < n""" return (n * (n-1)) // 2
def stringify_options(config): """Convert config dict to params for gsevol, like: opt=val;opt2=val2 """ opts = [] for opt, value in config.items(): opts.append("%s=%s" % (opt, value)) return ";".join(opts)
def vnu(cards): """Value and whether or not there is a usable ace.""" s = 0 aces = 0 for card in cards: if card[0] == 'A': aces += 1 else: s += int(card) acevals = [11 for ace in range(aces)] while (s + sum(acevals) > 21) and (11 in acevals): i = a...
def isNumber( ch ): """ Is the given character a number? """ return (ch >= '0' and ch <= '9')
def find_name_version_debian(project): """Find the name and the version of a Debian project. Args: project (str): project name with version (e.g. dpkg-1.18.25) Returns: name, version (tuple): name and version (e.g. dpkg,1.18.25) """ name = project[:project[:project.find('.')].rfin...
def is_zero(x): # tolerance """error tolerant zero test """ return -1e-6 < x and x < 1e-6 # replace with x == 0 si we are handling Fraction elements
def coordinates(line): """ Produces coordinates tuples line: CSV string from RDD """ contents = line.split(",") lng, lat = map(float,contents[3:5]) return lng, lat
def get_scale_factor(scale): """ Args: scale: ori scale Returns: floor scale """ if scale <= 1: return 1 elif scale <= 2: return 2 elif scale <= 4: return 4 else : return 8
def get_seed(voxel): """ Get a seed point for the center of a brain volume. Parameters ---------- voxel : tuple: The seed coordinates in x y z. Returns ------- tuple A tuple containing the (x, y, z)-coordinates of the seed. """ numpy_seed = (int(voxel[0...
def titles(posts): """Get a set of post titles from a list of posts.""" return set(p["title"] for p in posts)
def get_coords(geojson): """.""" if geojson.get('features') is not None: return geojson.get('features')[0].get('geometry').get('coordinates') elif geojson.get('geometry') is not None: return geojson.get('geometry').get('coordinates') else: return geojson.get('coordinates')
def _generate_download_google_link(link): """ ----- Brief ----- Function that returns a direct download link of a file stored inside a Google Drive Repository. ----------- Description ----------- Generally a link from a Google Drive file is only for viewing purposes. If the...
def sort(_list): """ counting sort algorithm :param _list: list of values to sort :return: sorted values """ try: max_value = 0 for i in range(len(_list)): if _list[i] > max_value: max_value = _list[i] buckets = [0] * (max_value + 1) ...
def add_str(arg1, arg2): """concatenate arg1 & arg2""" return str(arg1) + str(arg2)
def select_migrations(current, target, migration_ids): """ Select direction and migrations to run, given current and target migrations, from a list of migration ids """ if target > current: return 'forward', [ id_ for id_ in migration_ids if current < id_ <= targe...
def unir_cadena(lista_adn): """ (list of str) -> str Funcion que une todas las cadenas ingresadas >>> unir_cadena(['CGTA', 'ATTA']) 'CGTAATTA' >>> unir_cadena(['GC', 'GCATTT']) 'GCGCATTT' :param lista_adn: Lista de ADN ingresadas :return: Union de las cadenas """ cadena = "...
def is_person(possible_person:dict): """Helper for getting party ID""" return not possible_person.get('value',{}).get('entityRepresentation',{}).get('value',{}).get('personOtherIdentification') is None
def compare_word(word_a: str, word_b: str) -> int: """Compare word property of `word_a` to `word_b` (unambiguous) Arguments: word_a {ScoredKeyword} -- keyword word_b {ScoredKeyword} -- keyword Returns: int -- `word_a lt word_b`: -1, `word_a eq word_b`: 0, ...
def get_execution_date(tixi, module_name, xpath): """Function to get and write the execution date of a CEASIOMpy module. Function 'get_execution_date' ... Args: tixi (handles): TIXI Handle of the CPACS file module_name (str): Name of the module to test xpath (str): xPath where star...
def join_byteblocks(block, reverse=False) -> int: """ join_byteblocks used to combine low bit data and high bit data Parameters ---------- block : list Low Digit Block -> int High Digit Block -> int Returns ------- parsed : int low | high << 8 ... Example: ...
def build_token_dict(vocab): """ build bi-directional mapping between index and token""" token_to_idx, idx_to_token = {}, {} next_idx = 1 vocab_sorted = sorted(list(vocab)) # make sure it's the same order everytime for token in vocab_sorted: token_to_idx[token] = next_idx idx_to_toke...
def is_neq_prefix(text_1, text_2): """Return True if text_1 is a non-equal prefix of text_2""" return text_1 != text_2 and text_2.startswith(text_1)
def filter_none_values(data): """Returns a new dictionary excluding items where value was None""" return {k: v for k, v in data.items() if v is not None}
def is_valid_speed(sp): """ Returns: True if sp is an int in range 0..10; False otherwise. Parameter sp: the value to check Precondition: NONE (sp can be any value) """ return (type(sp) == int and 0 <= sp and sp <= 10)
def extend_params(params, more_params): """Extends dictionary with new values. Args: params: A dictionary more_params: A dictionary Returns: A dictionary which combines keys from both dictionaries. Raises: ValueError: if dicts have the same key. """ for yak in more_params: if yak in p...
def ticklabel_format(value): """ Pick formatter for ytick labels. If possible, just print out the value with the same precision as the branch value. If that doesn't fit, switch to scientific format. """ bvs = str(value) if len(bvs) < 7: fp = len(bvs) - (bvs.index(".") + 1) if "." in ...
def double_layer_cover_reflection_coefficient(transmission_coef_1, reflection_coef_1, reflection_coef_2) -> float: """ The reflection coefficient Equation 8.15 :param float transmission_coef_1: the transmission coefficients of the first layer :param float reflection_coef_1: the reflection coefficien...
def nearby_valid_date(desired_date, dictionary): """ Sometimes we get a date (year, month, day) that does not exactly exist in another dictionary. We want to find a nearby date that does exist in that dictionary, but is part of the same month. """ for valid_date in dictionary: if (valid...
def toBytes(string, length): """Converts a string into shift-jis encoding and padding it with zeroes to the specified length""" encoded = string.encode("shift-jis") return encoded + (b"\x00" * (length - len(encoded)))
def pad_rect(rect, move): """Returns padded rectangles given specified padding""" if rect['dx'] > 2: rect['x'] += move[0] rect['dx'] -= 1*move[0] if rect['dy'] > 2: rect['y'] += move[1] rect['dy'] -= 1*move[1] return rect
def square_area(side): """Returns the area of a square""" # You have to code here # REMEMBER: Tests first!!! area = pow(2, side) return area
def simplify_person_name( name ): """ Simpify a name to a last name only. Titles such as Ph. D. will be removed first. Arguments: name -- The name to shorten """ if name is not None: new_name = name.replace("Ph.D.", "").replace("Ph. D.", "").replace("M.A.", "").replace...
def seekable(fileobj): """Backwards compat function to determine if a fileobj is seekable :param fileobj: The file-like object to determine if seekable :returns: True, if seekable. False, otherwise. """ # If the fileobj has a seekable attr, try calling the seekable() # method on it. if has...
def get_single(x, name): """Make sure only a single element is used """ if isinstance(x, list): if len(x) == 1: return x[0] else: raise ValueError("Only a single {} can be used with --singularity".format(name)) else: return x
def get_coord(site, L): """Get the 3-vector of coordinates from the site index.""" # XXX: 3D hardcoded, can do N-D x = site // (L[1]) y = site % (L[1]) return [x, y]
def mapsets(f, datasets): """Apply a function to all the datasets.""" result = dict(datasets) for which, data in list(result.items()): result[which] = f(data) return result
def calc_probability(col_dict): """ This function calculates probability of each item in the dictionary For example, {'item1':10,'item2':30} gives prob = {'item1': 0.25, 'item2': 0.75} """ s = sum(col_dict.values()) for key, val in col_dict.items(): col_dict[key] = val / s return co...
def image_layers(state): """Get all image layer names in the state Parameters ---------- state : dict Neuroglancer state as a JSON dict Returns ------- names : list List of layer names """ return [l["name"] for l in state["layers"] if l["type"] == "image"]
def valid_face(x,y,w,h): """Checks if an rectangle contains a face. Assumes image is of size 450x800 """ # Face too small if (w < 50 or h < 50): return False # Face too large if (w > 200 or h > 200): return False if (y > 200 or y < 50): return False if (x > 250 or x < 100): retu...
def edges_equal(edges1, edges2, need_data=True): """Check if edges are equal. Equality here means equal as Python objects. Edge data must match if included. The order of the edges is not relevant. Parameters ---------- edges1, edges2 : iterables of with u, v nodes as edge tuples (u...
def get_all_post_ids(creation_year_map): """ union of all post_ids from each year's post_ids """ all_post_ids = set() for year, post_ids in creation_year_map.items(): all_post_ids.update(post_ids) return all_post_ids
def transfer_function_Rec709_to_linear(v): """ The Rec.709 transfer function. Parameters ---------- v : float The normalized value to pass through the function. Returns ------- float A converted value. """ a = 1.099 b = 0.018 d = 4.5 g = (1.0 / 0.45...
def checkRecordC(s): """ :type s: str :rtype: bool """ import re return re.match(".*LLL.*|.*A.*A.*",s) is None
def _shortName(s): """ Given a path like "|a|b|c", return the last item, "c". """ try: idx = s.rindex('|') return s[idx+1:] except ValueError: return s
def _do_poll(snmp_params): """Determine whether doing a poll is valid. Args: snmp_params: Dict of SMNP parameters Returns: poll: True if a poll should be done """ # Initialize key variables poll = False if bool(snmp_params) is True: if isinstance(snmp_params, dict...