content
stringlengths
42
6.51k
def _extract_sicd_tx_rcv_pol(str_in): """ Extract the tx and rcv components from the sicd style tx/rcv polarization string. Parameters ---------- str_in : str Returns ------- str, str """ if str_in is None: return 'UNKNOWN', 'UNKNOWN' if not isinstance(str_in, str...
def multi_to_single(y, combinations): """Convert multilabel indices to singlelabel strings.""" single = [] for y_i in y: y_i_str = ", ".join([str(i) for i in y_i]) single.append(combinations.index(y_i_str)) return single
def lcg(x, length=16): """Linear congruential generator""" if x == 0: return bytes(length) out = bytearray(length) for i in range(length): x = (214013 * x + 2531011) & 0x7fffffff out[i] = (x >> 16) & 0xff return bytes(out)
def compute_fuel(mass: int): """Read input module value and compute the fuel Parameters ---------- mass : [int] The mass of each module Returns ------- [int] Fuel for each module based on mass fuel = round(mass/3) - 2 """ return round(mass // 3) - 2
def maneuverToDir(str: str) -> int: """ maps dubins curve action to an interger {-1, 0, 1} Paramters --------- str: str dubins curve action Returns ------- int L -> 1, R -> -1, S -> 0 """ if str == 'L': return 1 if str == 'R': return -1 r...
def _to(f, x, nearest): """ :param f: rounding function, e.g. ceiling, floor, round :param x: number to round :param nearest: number to round to :return: x rounded to `nearest` """ return nearest * f(float(x) / nearest)
def receptive_field_pool(kernel, n0=1, shift_n=0, n_lyrs=1): """ Compute receptive field for pooling layers Parameters ---------- kernel kernel size n0 receptive field from previous layer shift_n number of shifting pixels in shift convolution architecture n_lyrs ...
def r(o, t): """ Transform back from the Boltzmann variable into `r`. Parameters ---------- o : float or numpy.ndarray Value(s) of the Boltzmann variable. If an array, it must have a shape broadcastable with `t`. t : float or numpy.ndarray Time(s). If an array, it must h...
def rain(walls): """ Given a list of non-negative integers representing walls of width 1, calculate how much water will be retained after it rains. walls is a list of non-negative integers. Return: Integer indicating total amount of rainwater retained. """ previous_wall = 0 spaces = [] ...
def prepare_sentence(str_words, word_to_id, lower=False): """ Prepare a sentence for evaluation. """ def f(x): return x.lower() if lower else x words = [word_to_id[f(w) if f(w) in word_to_id else '<UNK>'] for w in str_words] return { 'str_words': str_words, 'words': ...
def _parse_tensor_name(tname): """Adapt from TensorFlow source code """ components = tname.split(":") if len(components) == 2: try: output_index = int(components[1]) except ValueError: raise ValueError("invalid output index: {}".format(tname)) return (components[0], output_index) elif ...
def is_type_upgrade(origin_v, other_v): """Check whether type upgraded.""" tmp = origin_v + other_v return not isinstance(tmp, type(origin_v))
def remove_unreferenced_ids(referencedIDs, identifiedElements): """ Removes the unreferenced ID attributes. Returns the number of ID attributes removed """ keepTags = ['font'] num = 0 for id in identifiedElements: node = identifiedElements[id] if id not in referencedIDs and ...
def int_split(expression_str): """ split the expression into list of rules and logical symbols/words only be used with simple rule, no parenthesis :param: expression_str: a string of expression ex. 1 & 2 & 3 :return: list of rules and logical symbols/words ...
def secondlast_char(word): """ Return the second last letter example: zerrouki; 'k' is the second last. @param word: given word @type word: unicode @return: the second last letter @rtype: unicode char """ return word[-2:-1]
def getAssemblyUniverseCell(cellNum, surfaceNum, universe, comment): """Create a cell which will encompass all aspects of an assembly.""" cellCard = "{} 0 -{} fill={} imp:n=1 {}".format(cellNum, surfaceNum, universe, comment) assert (len(cellCard) - len(comment)) < 80 return cellCard
def to_dec_string(num): """Convert to decimal after being retrieved from DB""" return "%.2f" % (float(num) / 100)
def tab_header(line): """ dict mapping column title to column number """ return dict([(col_name, col_number) for col_number, col_name in enumerate(line.strip().split('\t'))])
def get_counting_line(line_orientation, frame_width, frame_height, line_position): """ To return the coords of the counting line by the line position and the frame width and height. :param line_orientation: the string of the orientation of the line.need to be top, bottom, left, right. example- if right - th...
def deal_hands(deck, start): """ Deal hands from the deck starting at index i """ return ( [deck[start], deck[start + 2]], [deck[start + 1], deck[start + 3]], )
def convert_codonlist_to_tuplelist(seq_codons, codon_to_codon_extended): """Convert a list of triplets into a list of tuples, using a swaptable. The swaptable is a dict of triplet: triplets, and determines the allowed swaps. """ codon_extended = [None] * len(seq_codons) for i, codon in enumerat...
def get_entangler_map(map_type, num_qubits): """Utility method to get an entangler map among qubits Args: map_type (str): 'full' entangles each qubit with all the subsequent ones 'linear' entangles each qubit with the next num_qubits (int): Number of qubits for which the ...
def mstoMin(ms) -> str: """Convert milliseconds to 0:00 format""" import time if ms >= 3600000: return time.strftime("%H:%M:%S", time.gmtime(ms / 1000)) else: return time.strftime("%M:%S", time.gmtime(ms / 1000))
def json_defaults(item_to_convert): """ convenience method used during json.dumps for non-json serializable items.""" return "%s" % item_to_convert
def yesno_as_boolean(yesno_string): """converts text containing yes or no to a bool""" valid = {"yes": True, "y": True, "ye": True, "no": False, "n": False} return valid[yesno_string.lower()]
def replace_comma(u_text): """ Replace the English comma in the text, because the English comma has special meaning in the FLYBIRDS framework """ return u_text.replace(',', ' ')
def inside_gamut(r, g, b): """ Test whether a requested colour is within the gamut achievable with the primaries of the current colour system. This amounts simply to testing whether all the primary weights are non-negative. */ """ return (r >= 0) and (g >= 0) and (b >= 0)
def _validate_set(val): """Check to see that a set is a set type""" if not isinstance(val, set): raise ValueError("Passed value {} is not a set".format(val)) if not all([isinstance(char, str) for char in val]): raise ValueError("Passed overrides of non-string to overrides") return val
def set_bit(v, index, x): """Set the index:th bit of v to 1 if x is truthy, else to 0, and return the new value.""" mask = 1 << index # Compute mask, an integer with just bit 'index' set. v &= ~mask # Clear the bit indicated by the mask (if x is False) if x: v |= mask # If x was True, set the...
def solution1(A, k): # O(N^2) """ Write a function to left rotate a list a by k number of times. eg. [1, 2, 3] if k = 1, then result = [2, 3, 1] if k = 2, then result = [3, 1, 2] >>> solution1([1, 2, 3, 4, 5], 4) [5, 1, 2, 3, 4] >>...
def get_label_length(label): """Get length of cell label.""" label_length = 5 while label_length < len(label) and label[label_length].isdigit(): label_length += 1 return label_length
def first_odd_or_even(numbers): """Returns 0 if there is the same number of even numbers and odd numbers in the input list of ints, or there are only odd or only even numbers. Returns the first odd number in the input list if the list has more even numbers. Returns the first even number ...
def trapezoid_area(height, top, bottom): """ Computes the area of a trapezoid with the given height and top/bottom lengths. """ return ( # triangle based on longer - shorter of the top/bottom 0.5 * abs(top - bottom) * height # plus parallelogram based on shorter edge + ...
def interpolate_json_query(sql): """ pony.orm processes `$` as a format variable. This function interpolates it replacing with `$$`. See https://github.com/ponyorm/pony/issues/322#issuecomment-351307146 :param sql: :return: an escaped string """ return sql.replace("$", "$$")
def area_poly(points): """ This function computes the area of the polygon formed by the intersection points after they are sorted. """ area = 0.5 * abs(points[0][0] * points[-1][1] - points[0][1] * points[-1][0]) for i in range(len(points) - 1): area += 0.5 * abs(points[i][0] * points[i...
def is_reference_type(text: str) -> bool: """ Does the given type represent a reference type? """ return text[0] == "&"
def fileNameCleaner(name): """cleans up the name for the file and preserves the file extension :param name: The name of the file that needs to be renamed :type name: str :returns: A str that will be the new name of the file :rtype: str """ resolutions = ['proper', '480p', '720p', '1080p', '4...
def format_srt_time(sec_time): """Convert a time in seconds (google's transcript) to srt time format.""" sec, micro = str(sec_time).split('.') m, s = divmod(int(sec), 60) h, m = divmod(m, 60) return "{:02}:{:02}:{:02},{}".format(h, m, s, micro)
def _format_path_row(start_point, end_point=None): """ Format path-row for display in a dataset id. :type start_point: ptype.Point or None :type end_point: ptype.Point or None :rtype: (str, str) >>> _format_path_row(ptype.Point(78, 132)) ('078', '132') >>> _format_path_row(ptype.Point(...
def make_tuple(value, convert_none=False): """Shortcut utility for converting a value to a tuple.""" if isinstance(value, list): return tuple(value) if not isinstance(value, tuple) and (convert_none or value is not None): return (value,) return value
def get_prefix(headword, length): """ Return the prefix for the given headword, of length length. Note that the procedure implemented here is the result of reverse engineering, since no official specification has been published by Kobo so far. YMMV. :param headword: the headword string ...
def parse_job(children): """ parse status information out of the Job element """ job_status = {'name': False, 'state': "", 'status': "", 'succeeded': ""} for mpijob_name, mpijob in children['Job.batch/v1'].items(): job_status['name'] = mp...
def while_check(code): """Prevents player from using indefinite while loops by breaking loop after pre-defined amount of iterations. :param code: Source code string block. :type code: str :returns: The modified user source code string block. """ tab = False pass1 = False tmpArr = code....
def merge_settings(fetch_setting, class_setting): """Merge settings for ``fetch``, method params have priority.""" if fetch_setting is None: return class_setting else: return fetch_setting
def normalize_interface(if_name): """Return the normalized interface name """ def _get_number(if_name): digits = '' for char in if_name: if char.isdigit() or char == '/': digits += char return digits if if_name.lower().startswith('et'): if_typ...
def _build_rules_helper(search): """Helper function for build_rules(). A branch node like: ["and", [node1, node2]] will be transformed, recursively, into: { "condition": "AND", "rules": [_build_rules_helper(node1), _build_rules_helper(node2)] } A leaf...
def get_mobilenetv2_filename(key): """Rename tensor name to the corresponding Keras layer weight name. # Arguments key: tensor name in TF (determined by tf.variable_scope) """ filename = str(key) filename = filename.replace('/', '_') filename = filename.replace('MobilenetV2_', '') fi...
def fix_span(dic, p): """ changing the span of words from sentence level to step level :rtype: dict """ return {'name': dic['name'], 'span': [i + p for i in dic['span']]}
def binary_search(data, target, low, high): """return True if target is found""" if low > high: return False mid = (low + high) // 2 print(mid) if target == data[mid]: return True elif target < data[mid]: return binary_search(data, target, low, mid-1) else: re...
def make_ordinal(n): """ Convert an integer into its ordinal representation:: make_ordinal(0) => '0th' make_ordinal(3) => '3rd' make_ordinal(122) => '122nd' make_ordinal(213) => '213th' """ n = int(n) suffix = ['th', 'st', 'nd', 'rd', 'th'][min(n % 10, 4)] if...
def count_sentences(s, sentence_delimiters=set([".", "!", "?"])): """Counts the number of sentences in the given string.""" cs = " ".join([p.strip() for p in s.split("\n")]) count = 0 for c in cs: if c in sentence_delimiters: count += 1 return count
def group(number): """show money in laks and crores (indian way of presenting money)""" s = '%d' % number groups = [] groups.append(s[-3:]) s = s[:-3] while s and s[-1].isdigit(): groups.append(s[-2:]) s = s[:-2] return s + ','.join(reversed(groups))
def str_empty_in(*args) -> bool: """ Function that checks whether an object is an empty string. Returns: [bool]: Return bool """ for _ in args: if "" in args: return True return False
def p2(max): """Problem 2 Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... By considering the terms in the Fibonacci sequence whose values do not exceed four million, find...
def is_timestamp(item: str) -> bool: """ Returns True if the item matches the timestamp format """ return len(item) == 7 and item[-1] == "Z" and item[:-1].isdigit()
def foo(x): """ Simple function to explain usage of test file. """ # Returns input + 1 return x + 1
def scale(scalar, vector): """ Scale vector by scalar :param scalar: numerical value :param vector: list of numerical values :return: """ return [vector[i] * scalar for i in range(len(vector))]
def strings_share_characters(str1: str, str2: str) -> bool: """Determine if two strings share any characters.""" for i in str2: if i in str1: return True return False
def magic_square(array): """ :param array:A 2D array :return: True or False whether the array is a magic squre :rtype: bool """ if array is None or not isinstance(array, list): return False if len(array) == 0: return False # summing rows # loop through the array sum...
def converter_parameter_to_float(value): """ Converts the given value to string. Parameters ---------- value : `str` The value to convert to string. Returns ------- value : `None` or `float` Returns `None` if conversion failed. """ try: value = f...
def schedule(epoch, learning_rate): """This function schedules a variable learning rate based on the epoch number :param epoch: The current training epoch :type epoch: float :return: A value for the learning rate :rtype: float """ if epoch >= 50: return 0.0001 else: return 0.001
def get_mwa_eor_spec(nu_obs=150.0, nu_emit=1420.40575, bw=8.0, tint=1000.0, area_eff=21.5, n_stations=50, bmax=100.0): """ Parameters ---------- nu_obs : float or array-like, optional observed frequency [MHz] nu_emit : float or array-like, optional rest frequency...
def info_of_opfn_by_name(name): """ Returns a nice human-readable name and tooltip for a given gate-function abbreviation. Parameters ---------- name : str An appreviation for a gate-function name. Allowed values are: - "inf" : entanglement infidelity - "agi" : ave...
def _merge_lists(lists, option): """ Merges multiple lists into one list, with the default being the values of the first list. It either replaces values with NULL if NULL is in that position in another list or replaces NULL with values if values are in that position in another list. """ if t...
def word_probabilities(counts, total_spams, total_non_spams, k=0.5): """Turn the word_counts into a list of triplets: w, p(w|spam) and p(w|~spam)""" return [(w, (spam + k)/(total_spams + 2 * k), (non_spam + k)/(total_non_spams + 2 * k)) for w, (spam, non_spam) in counts.item...
def compare_bib_dict(item1, item2): """ compare bibtex item1 and item 2 in dictionary form """ # unique id check col_list = ["doi", "pmid", "pmcid", "title", "local-url"] for c in col_list: if (item1.get(c, "1") != '') and (item1.get(c, "1") == item2.get(c, "2")): return 1.0 s...
def gcd_2(n, m): """finds the gcd of n and m""" if(n < m):##swaps n and m n ^= m m ^= n n ^= m while(m!=0): k = n%m n = m m = k return n
def light_boost_level_factor(LightLevel): """ # -------------------------------------- # Calculate the Light boost level based on the provided Light Level # taken from a light sensor, or possibly derived from time of day etc. # Colours can be multiplied by the boost level to increase the bright...
def generate_registers_riscv_plic0_pending(inta, inth, intl, addr): """Generate xml string for riscv_plic0 pending register for specific interrupt ids""" temp = inth + " to " + intl return """\ <register> <name>pending_""" + inta + """</name> <description>...
def _snake_to_pascal_case(model_name: str) -> str: """Convert model name from snake case to Pascal case. Args: model_name (str): Model name in snake case. Returns: str: Model name in Pascal case. """ return "".join([split.capitalize() for split in model_name.split("_")])
def powfun(a, b): """Method to raise a to power b using pow() function.""" return pow(a, b)
def events_clashes(events_definition, clashes_definition): """ Parameters ---------- events_definition : list of dicts of the form {'title': Event title, 'duration': <integer in minutes>, 'tags': <list of strings>, 'person': <string>, ...
def perform_list_union(lst): """ Performs the union of a list of sets Parameters ------------ lst List of sets Returns ------------ un_set United set """ ret = set() for s in lst: ret = ret.union(s) return ret
def lerp(a, b, p): """Linear interpolation between a and b with p .. math:: a * (1.0 - p) + b * p Args: a, b: interpolated values p: [0..1] float describing the weight of a to b """ assert 0 <= p and p <= 1 return a * (1.0 - p) + b * p
def build_response(session_attributes, speechlet_response): """ Standard response """ return { 'version': '1.0', 'sessionAttributes': session_attributes, 'response': speechlet_response }
def is_chinese_char(cp): """Checks whether CP is the codepoint of a CJK character.""" # This defines a "chinese character" as anything in the CJK Unicode block: # https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block) # # Note that the CJK Unicode block is NOT all Japanese and Korean...
def isIterable(input): """ This function check a input is iterable, for example sequences and collections. :param input: unknown type object """ try: _ = iter(input) return True except TypeError: return False
def smoothInterp(t,dt,tform): """Smooth interpolation in time, following Dehnen (2000)""" if t < tform: smooth= 0. elif t > (tform+dt): smooth= 1. else: xi= 2.*(t-tform)/dt-1. smooth= (3./16.*xi**5.-5./8*xi**3.+15./16.*xi+.5) return smooth
def f_sma(close_prices, window): """Calculates standard moving average SMA). This function takes historical data, and a moving window to calculate SMA. As the moving average takes previous closing prices into account, its length will be len(candles) - window Args: close_prices (list of float):...
def check_field_constraints(passport): """ This function checks the following constraints: byr (Birth Year) - four digits; at least 1920 and at most 2002. iyr (Issue Year) - four digits; at least 2010 and at most 2020. eyr (Expiration Year) - four digits; at least 2020 and at most 2030. hgt (Hei...
def clean_data_dict(data_dict): """Add some key/value pairs to the data dict, if they are missing. Args: data_dict - dictionary containing data for LFADS Returns: data_dict with some keys filled in, if they are absent. """ keys = ['train_truth', 'train_ext_input', 'valid_data', 'valid_truth...
def compute_lr(step, factor=3e-3, warmup=50, eps=1e-7): """ Calculates learning rate with warm up. """ if step < warmup: return (1 + factor) ** step else: # after reaching maximum number of steps # the lr is decreased by factor as well return max(((1 + factor) ** warm...
def __subtract_list(list_a: list , list_b: list): """ Private Function - removes elements from a list via subtaction Parameters: list_a (list): The original list list_b (list): A list of values to remove from list_a Returns: list: returns a substracted list of elements """ ret...
def site_id(request): """Site id of the site to test.""" return request.param if hasattr(request, 'param') else None
def cross_product(x1, y1, z1, x2, y2, z2): """Cross product of two vectors, v1 x v2. Parameters ---------- x1 : float or array-like X component of vector 1 y1 : float or array-like Y component of vector 1 z1 : float or array-like Z component of vector 1 x2 : float or...
def sort_dict_keys(dict_thing:dict) -> list: """ sort dictionary keys """ return_value = [key for key in dict_thing] return sorted(return_value)
def create_player_matchmaking_list(players_and_scores): """Create a list of player and return it.""" players_matchmaking = [] players_and_scores_to_empty = dict(players_and_scores) players_list = list(players_and_scores) while players_and_scores_to_empty != {}: temp_player_list = [] ...
def compare_config(cfg_1, cfg_2): """Compare two config dictionaries. Useful for checking when resuming from previous session. Parameters ---------- cfg_1 : dict cfg_2 : dict Returns ------- Returns True when the two configs match (with some exclusions), False otherwise. ""...
def _dateCheck(date_1, date_2): """ Will return True if date_1 is before or equal to date_2. Date params are lists with 3 elements, year, month, day. """ if date_1[0] < date_2[0]: return True if date_1[0] > date_2[0]: return False if date_1[1] < date_2[1]: return True...
def from_733(u: bytes) -> int: """Convert from ISO 9660 7.3.3 format to uint32_t Return the little-endian part always, to handle non-specs-compliant images """ return u[0] | (u[1] << 8) | (u[2] << 16) | (u[3] << 24)
def get_hero_name(hero_page): """Method that parses hero name from its responses page. Pages for heroes are in the form of `Hero name/Responses`. We need only the `Hero name` part for heroes. :param hero_page: hero's responses page as string. :return: Hero name as parsed """ return hero_page.sp...
def get_model_constants(model_settings): """ Read constants from model settings file Returns ------- constants : dict dictionary of constants to add to locals for use by expressions in model spec """ return model_settings.get('CONSTANTS', {})
def make_patterns(dirs): """Returns a list of git match patterns for the given directories.""" return ['%s/**' % d for d in dirs]
def centroid_to_row(centroid_resource): """Returns a csv row to store main centroid info in csv files. """ return [centroid_resource['object']['centroid_name']]
def create_content_string(name, attrs): """Utility method to take a tag name and a dictionary of attributes and create a tag from it.""" string = '<'+name for att in attrs.items(): nameAtt = att[0] value = att[1] if not (name is None or value is None): string =strin...
def prepare_data(items, rcn): """Append the project code ('RCN') to each "row" (dict) of data (list)""" return [dict(project_rcn=rcn, **item) for item in items]
def bezier_tangent(p0:float, p1:float, p2:float, p3:float, t:float): """ Calculate the tangent of the point with parameter t on the cubic bezier curve. Note that the parameter t must >=0 and <=1 . :param p0: position of the first control point :param p1: position of the second control point :p...
def convert_value(val): """Convert values in operation conditions dictionaries.""" return { 'min_value': float(val['min']) if val['min'] is not None else None, 'max_value': float(val['max']) if val['max'] is not None else None, 'values': [float(x) for x in val['values']], 'units'...
def utctz_to_altz(utctz): """we convert utctz to the timezone in seconds, it is the format time.altzone returns. Git stores it as UTC timezone which has the opposite sign as well, which explains the -1 * ( that was made explicit here ) :param utctz: git utc timezone string, i.e. +0200""" return -1 * int(float(utc...
def transpose_board(board): """Transpose the board --> change row to column""" return [list(col) for col in zip(*board)]