content
stringlengths
42
6.51k
def snorm_to_byte(x): """float x in [-1, 1] to an integer [0, 255]""" return min(int((x + 1) * 128), 255)
def vector_add(v, w): """adds corresponding vectors""" return [v_i + w_i for v_i, w_i in zip(v, w)]
def all_arcs(constraints): """ For each constraint ((X, Y), const) adds: ((X, Y), const) ((Y, X), const) """ arcs = set() for neighbors, constraint in constraints: if len(neighbors) == 2: x, y = neighbors map(arcs.add, ((x, y), (y, x))) return ar...
def kml_cb(mapping): """ Create text for a colorbar png file overlay """ kml_text = """ <ScreenOverlay> <name>{name:s}</name> <Icon> <href>{cb_file:s}</href> </Icon> <overlayXY x="{xfrac:.4f}" xunits="fraction" y="{yfrac:.4f}" yunits="fraction"/> <screenXY x="{xfrac:.4f}" xunits="fraction...
def get_binary_rep(n, num_digits): """Assumes n and numDigits are non-negative ints Returns a str of length numDigits that is a binary representation of n""" result = '' while n > 0: result = str(n%2) + result n = n//2 if len(result) > num_digits: raise ValueError('not enough d...
def filter_headers(headers, fields): """ Keep only the headers listed in fields that also have a truthy value. """ filtered = {} for field in fields: value = headers.get(field) if value: filtered[field] = value return filtered
def ticket_to_order_ratio(total_tickets, total_orders): """Returns the ratio of tickets to orders. Args: total_tickets (int): Total chats, emails, or tickets in the period. total_orders (int): Total orders in the period. Returns: Ratio of tickets to orders """ return (tota...
def build_note(text, level=1, limit=180, strip=True, keyword='NOTE'): """ Format a note for gedcom output """ note = [] key = int(level) tag = keyword data = text if strip: data = data.strip() while data != '': index = limit if len(data) < limit: i...
def validate_args(args): """ Checks if the first argument in the list is a number. Args: args (list) - Command line arguments Returns: 0 if the first argument is a number 1 if the first argument is not a number 2 if the list is empty """ # Attempt to convert th...
def infer_align_format(line): """Guess the format of an alignment file based on first line. Parameters ---------- line : str First line of alignment. Returns ------- str Alignment file format (map, b6o or sam). Raises ------ ValueError Format cannot be ...
def sorting_two(nums): """ Sorts nums in descending order and retrieve first two values. """ if len(nums) < 2: raise ValueError('Must have at least two values') return tuple(sorted(nums, reverse=True)[:2])
def validate_files(input_files): """ The valid files will have name: <class_name>_<split>.txt. We want to remove all the other files from the input. """ output_files = [] for item in input_files: if len(item.split('/')[-1].split('_')) == 2: output_files.append(item) retur...
def settings2meta(settings, section_name="Skill Settings"): """ generates basic settingsmeta """ fields = [] for k, v in settings.items(): if k.startswith("_"): continue label = k.replace("-", " ").replace("_", " ").title() if isinstance(v, bool): fields.appe...
def punnettParse(s : str) -> list: """Take a str and turn it into a list of strings punnett can accept""" if len(s) % 2: raise ValueError('Even number of alleles required') return ["".join(sorted(s[i:i+2])) for i in range(0,len(s),2)]
def is_same_array(first, second): """ Check if two arrays of strings are equals Args: first (array[str]): Array of strings second (array[str]): Array of string Returns: int: True if both are equals """ diff_selected_columns = list(set(first) - set(second)) return...
def calc_s0s1s2_from_fourPolar(i000, i045, i090, i135): """ Return s0, s1, and s2 from four-directional polarization images. Args: i000: ndarray i045: ndarray i090: ndarray i135: ndarray Returns: ndarray """ s0 = (i000 + i045 + i090 + i135) / 2. s1 = i000 - i0...
def bubble_sort(li): """ [list of int] => [list of int] Bubble sort: starts at the beginning of the data set. It compares the first two elements, and if the first is greater than the second, it swaps them. It continues doing this for each pair of adjacent elements to the end of the data set. It ...
def max_run(_b, _x): """Determine the length of the maximum run of b's in vector x. Parameters ---------- b: int Integer for counting. x: array Vector of integers. Returns ------- max: int Length of maximum run of b's. """ # Initialize counter _max ...
def add_integer(a, b=98): """add two integer Args: a: int b: int """ if type(a) != int and type(a) != float: raise TypeError("a must be an integer") if type(b) != int and type(b) != float: raise TypeError("b must be an integer") return (int(a) + int(b))
def filtrePH(valeur, coup, val1, val2): """Applique un filtre passe-haut sur valeur en fonction de coup.""" if valeur < coup: return val1 else: return val2
def parseRawEventCall(raw_output, cutoff=0.5): """ Parses the raw results of a call to the `label_search` IBM Watson API, implementing a cutoff in the process. Used to parse the results for the `fetchConceptsForEvent()` front-facing method. Returns a dict that can be assigned to an ObjectModel. Minor semantic dif...
def do_call(FUN, args=[], kwargs = {}): """ # Goal Run code like R do.call # Parameters FUN: a function you'd like to run args: vector element args kwargs: dictionary args # Example ArgsList = dict() ArgsList['alpha'] = 0.01 ArgsList['beta'] = 1 ArgsList['b...
def reverse_sort_list(vec, sorted_index): """ Perform the reverse of sort described in sort_by_sorted_index Args: vec (list): list with len(list) = len(sorted_index) sorted_index (list of ints): desired order for vec """ new_vec = [0]*len(sorted_index) for i in range(len(sorted_index)): new_vec[sorted_ind...
def normalize_grch_name(assembly_name): """ Convert `GRCh` names to `hg` ones, GRCh38 = hg38, GRCh37 = hg19, and GRCh36 = hg18 """ assembly_version = int(assembly_name.lower().replace("grch", "")) if assembly_version < 38: hg_assembly_version = assembly_version - 18 else: hg_asse...
def CreateSafeUserEmailForTaskName(user_email): """Tasks have naming rules that exclude '@' and '.'. Task names must match: ^[a-zA-Z0-9_-]{1,500}$ Args: user_email: String user email of the task owner. Returns: String with unacceptable chars swapped. """ return user_email.replace('@', '-AT-').rep...
def rgb(*args): """ args: r, g, b as decimals return: r, g, b values converted into hexidecimals """ hex_list = [] for elt in args: if elt < 0: elt = "00" elif elt > 255: elt = "FF" elif elt < 10: elt = "0" + (hex(elt).split("0x"))[1] else: elt = (hex(elt).split("0x")...
def get_manufacturing_process_factor(manufacturing_id: int) -> float: """Retrive teh the manufacturing process correction factor (piMFG). :param manufacturing_id: the manufacturing process identifier. :return: _pi_mfg; the manufacturing process correction factor. :rtype: float """ return 0.55 i...
def text_cleaning(text): """Cleans a piece of text by removing escaped characters. Args: text (str): string with text Returns: str: cleaned piece of text """ # Remove escaped characters escapes = ''.join([chr(char) for char in range(1, 32)]) text = text.translate(str.maketr...
def echo_types_converter(types): """Convert job types""" if not types: return {'stdout': None, 'stderr': None} if not isinstance(types, dict): types = {types: None} if 'all' in types: return {'stdout': types['all'], 'stderr': types['all']} return types
def sort_list(l, key=None, reverse=False): """Returns a list.""" return sorted(l, key=key, reverse=reverse)
def _get_block_sizes(resnet_size): """Retrieve the size of each block_layer in the ResNet model. The number of block layers used for the Resnet model varies according to the size of the model. This helper grabs the layer set we want, throwing an error if a non-standard size has been selected. Args: resnet...
def transcription(dna_seq): """DNA --> RNA transcription. Replaces Thyamine with Uracil""" return dna_seq.replace("T", "U")
def get_quad_tag_parts(reftag:str): """ Return a 4-tuple given a tag """ # Split tag into parts tag_parts = reftag.split("/") if len(tag_parts) < 3 or len(tag_parts) > 4: return None, None, None, None tag_prefix = tag_parts[0] tag_context_name = tag_parts[1] tag_value_name...
def _find_used(activity, predicate): """Finds a particular used resource in an activity that matches a predicate.""" for resource in activity['used']: if predicate(resource): return resource return None
def image_group_object_factory(image_id, group_id): """Cook up a fake imagegroup json object from given ids.""" groupimage = { 'image_id': image_id, 'group_id': group_id } return groupimage
def _preprocess_padding(padding): """Convert keras' padding to tensorflow's padding. # Arguments padding: string, `"same"` or `"valid"`. # Returns a string, `"SAME"` or `"VALID"`. # Raises ValueError: if `padding` is invalid. """ if padding == 'same': padding =...
def betabinom_variance(a, b, n): """Variance of a beta-binomial discrete random variable :param a: the alpha parameter, number of prior successes, a > 0 :param b: the beta parameter, number of prior failures, b > 0 :param n: the number of total trials :return: the mean of the distribution(s) ""...
def rec_map(callable, dict_seq_nest): """Recursive map that goes into dics, lists, and tuples. This function tries to preserve named tuples and custom dics. It won't work with non-materialized iterators. """ if isinstance(dict_seq_nest, list): return type(dict_seq_nest)(rec_map(callable, x)...
def clean_whitespace(text): """ Remove any extra whitespace and line breaks as needed. """ import re # Replace linebreaks with spaces text = text.replace('\n', ' ').replace('\r', ' ').replace('\t', ' ') # Remove any leeding or trailing whitespace text = text.strip() # Remove consecut...
def emails_parse(emails_dict): """ Parse the output of ``SESConnection.list_verified_emails()`` and get a list of emails. """ result = emails_dict['ListVerifiedEmailAddressesResponse']['ListVerifiedEmailAddressesResult'] emails = [email for email in result['VerifiedEmailAddresses']] return ...
def digest_line(line, name): """ Interprets a line of input to a point-tuple. """ x, _, y = line.partition(",") x = int(x.strip()) y = int(y.strip()) return (x, y, name)
def debugsquare(x): """Return x squared but also print a debug value of x.""" print("DEBUG: the value of x is", x, "in the function debugsquare") return x * x
def rotate_matrix__90_clk_inplace(matrix): """In-place rotation. Changes the input matrix. Args: A square 2-dim matrix. Returns: Rotated matrix (in-place) """ n = len(matrix) if n <= 1: return matrix for i in range(n//2): for j in range(i, n - i - 1): ...
def get_checksum_value(source): """ Returns checksum_value, which is the parsed checksum value (after '*') from the source string. """ if (source.find('*') == -1): return None start = source.index('*')+1 checksum_value = source[start:] return checksum_value
def invert_index(idx): """Returns a new index with the same values, but structured differently in that in the output top-level keys switch place with embedded keys. For example, "k1 -> k2 -> value" will be turned into "k2 -> k1 -> value". The values themselves do not change.""" result = {} for f...
def is_number(s): """ Check if a string is a number """ try: float(s) return True except ValueError: return False
def map_label(label, alias): """ Update label from its alias value in config.yaml. ``` alias.get(label, label) ``` If the `label` has an alias, use it else use the label as-is. This requires labels to be created this way: ```yaml alias: aliased_label_1: real_label a...
def get_extra_empty_samples(classification_n, empty_classification_n, classifications): """ Arguments: classification_n: Total number of classifications we have. empty_classification_n: Total number of empty classifications we have. classifications: List of strings mapping our class indi...
def getPrefix(netmask): """ Get the CIDR prefix representing the netmask. :param netmask: Netmask to convert to CIDR :type netmask: :returns: CIDR prefix representing the netmask :rtype: int """ return sum([bin(int(x)).count('1') for x in netmask.split('.')])
def set_to_list(setstring, delimiter="|", affix="|"): """Turn a set string into a list.""" if setstring == affix: return [] setstring = setstring.strip(affix) return setstring.split(delimiter)
def create_html_link(url, text): """Wrap a text into an html anchor element with a specified url.""" line = f"<a href='{url}'>{text}</a>" return line
def linear20(value): """Convert dB value to linear units (voltage-like).""" return 10 ** (value / 20)
def get_file_path_from_manifest(manifest: str) -> str: """ Get the file path from OTA manifest. This function is used when the manifest is failed to parse and want to remove temporary OTA file. It gets the file path information directly from the manifest. @param manifest: OTA manifest @return: stri...
def clean_sample_data(samples): """Clean unnecessary information from sample data, reducing size for message passing. """ out = [] for data in (x[0] for x in samples): data["dirs"] = {"work": data["dirs"]["work"], "galaxy": data["dirs"]["galaxy"], "fastq": data["dirs"].ge...
def alphanumericp(c): """Returns true if character is an alphabetic character or a numeric character; otherwise, returns false. """ return type(c) is str and c.isalpha() or c.isnumeric()
def read_file(fname): """ Read file at `fname` as text, return `contents` Parameters ---------- fname : str Filename. Returns ------- contents : str Contents read from `fname`. """ with open(fname, 'rt') as fobj: contents = fobj.read() return contents
def convert_height(height_str): """ Converting height from feet to centimeters """ foot, inches = height_str.split('-') height_cm = 30.48 * float(foot) + 2.54* float(inches) return height_cm
def _allocate_clients(selected_clients, n): """Allocate selected clients at each round to all processes as evenly as possible Args: selected_clients (List[int]): Selected clients ID n (int): Num of processes Returns: List[List[int]]: Allocated clients ID for each process. """...
def fulltag_from_detail(image_detail: dict) -> str: """ Return a fulltag string from the detail record :param image_detail: :return: """ return ( image_detail["registry"] + "/" + image_detail["repo"] + ":" + image_detail["tag"] )
def list_median(values): """ Assignment 3 updated """ sorted_values = sorted(values) length = len(sorted_values) if length % 2 == 0: return round((sorted_values[length//2-1] + sorted_values[length//2]) / 2, 1) return sorted_values[(length-1)//2]
def _cast(value, schema_type): """Convert value to a string based on JSON Schema type. See http://tools.ietf.org/html/draft-zyp-json-schema-03 for more details on JSON Schema. Args: value: any, the value to convert schema_type: string, the type that value should be interpreted as Returns: A str...
def brightness_from_percentage(percent): """Convert percentage to absolute value 0..255.""" return round((percent * 255.0) / 100.0)
def fib_recursiva_com_cache(number): """Fibonacci recursiva com cache.""" if number < 2: return number return fib_recursiva_com_cache(number - 1) + fib_recursiva_com_cache( number - 2 )
def keep_in_baremetal(name): """Rules for symbols in the "baremetal" configuration.""" if name in [ 'MBEDTLS_DEPRECATED_WARNING', 'MBEDTLS_ENTROPY_NV_SEED', 'MBEDTLS_FS_IO', 'MBEDTLS_HAVEGE_C', 'MBEDTLS_HAVE_TIME', 'MBEDTLS_HAVE_TIME_DATE',...
def is_prime(n, primes): """Quick primality test using a given list of primes Args: n (int): Number to test primes (int list): list of primes """ for x in primes: if n % x == 0: return False else: return True
def GetPerfDashboardRevisionsWithProperties( got_webrtc_revision, got_v8_revision, version, git_revision, main_revision, blink_revision, point_id=None): """Fills in the same revisions fields that process_log_utils does.""" versions = {} versions['rev'] = main_revision versions['webkit_rev'] = blink_rev...
def parse_content_type(ct): """Given an HTTP content-type header, parses out the content-type and the charset. Does not currently perform any validation on the content of the header.""" parts = ct.split(";") content_type = parts[0] try: charset = parts[1].strip().lstrip('charset=') ...
def categorize_attendance(attendances): """ :type attendances: iterable of librus_tricks.classes.SynergiaAttendance :rtype: dict[librus_tricks.classes.SynergiaAttendanceType.short_name, list of librus_tricks.classes.SynergiaAttendance] """ attendance_dict = dict() for att in attendances: ...
def breguet_propellant_winged_powered(R_cruise, v_cruise, lift_drag, I_sp_ab): """Recovery propellant factor P for winged vehicle with air-breathing propulsion. See Breguet range equation http://web.mit.edu/16.unified/www/FALL/thermodynamics/notes/node98.html Arguments: R_cruise (scalar): cruise r...
def overlap(a, b, min_length=3): """ Return length of longest suffix of 'a' matching a prefix of 'b' that is at least 'min_length' characters long. If no such overlap exists, return 0. """ start = 0 # start all the way at the left while True: start = a.find(b[:min_length], ...
def _crc_update(cur, crc, table): """helper for crc calculation :param cur :param crc :param table """ l_crc = (0x000000ff & cur) tmp = crc ^ l_crc crc = (crc >> 8) ^ table[(tmp & 0xff)] return crc
def droid_mod_to_mod_list(droid_mods): """ Converts droid mod string to PC mod string. """ # Honestly not the best implementation, but the core is there final_mods = "" if "a" in droid_mods: final_mods += "at" if "x" in droid_mods: final_mods += "rx" if "p" in droid_mod...
def _divides(a1, a2): """ divide 1-w (i.e. a1+a2*w -> (1-w)^k * (x+y*w)) """ if (a1 == 0) and (a2 == 0): return a1, a2, 0 j = 0 while (a1 + a2) % 3 == 0: tmpa1 = a1 a1 = ((a1 + a1) - a2) / 3 a2 = (tmpa1 + a2) / 3 j += 1 return a1, a2, j
def unique_allocation(students_pref, student_index, elected_topics): """ Finds the number of possible allocations possible from the current student's position till the last student :param students_pref: eg [[s1 pref],[s2 pref],...] :param student_index: Current student's index for whom we should elect ...
def get_responders(players, suggester): """ get the responders (in the correct order) for the given suggester """ si = players.index(suggester) return players[si+1:] + players[:si]
def populate_nested_dictionary(dictionary, key_list, types=[]): """ For each key k_i in key_list, make sure that dictionary[k_0][k_1][k_2]...[k_i] exists, creating objects of the appropriate type in each sub-dictionary as needed. If types is specified, then dictionary[key_list[i]] should point to a...
def concentration(n, volume): """ """ return float(n) / 6.0221415e23 / (volume * 1e-27)
def get_object_class(configvalue): """ Formats the objectclass line from the config into a list """ objclass = configvalue.split('|') return objclass
def _get_num_elements(objects): """" number of elements in `objects` """ s = set() for t in objects: for i in t: s.add(i) nvars = len(s) b = list(sorted(s)) b.sort() if b != list(range(nvars)): raise ValueError('elements should be labelled in 0,...,nvars-...
def range_count(start, stop, count): """Generate a list. Use the given start stop and count with linear spacing e.g. range_count(1, 3, 5) = [1., 1.5, 2., 2.5, 3.] """ step = (stop - start) / float(count - 1) return [start + i * step for i in range(count)]
def SplitBlobName(layer_name, blob_name, blob_idx, split_idx): """ Used for caffe parser. """ return "_".join([layer_name, blob_name, str(blob_idx), "split", str(split_idx)])
def getNameOnly(filename): """get file name without extension from a path""" nameonly = filename.split('.')[0] return nameonly
def no_faves_menu(on=0): """Remove a Opcao "Favoritos" do Menu Iniciar DESCRIPTION Esta restricao remove a opcao "Favoritos" do menu iniciar. COMPATIBILITY Todos. MODIFIED VALUES NoFavoritesMenu : dword : 00000000 = Desabilitado; 00000001 = Remove opcao. ...
def is_case_pv_graded(products): """Returns True if pv_grading is True for atleast one of the products on the application""" gradings = {product.get("good", {}).get("is_pv_graded") for product in products} return "yes" in gradings
def add_new_column(header, rows, column_name, column_generator): """ Add new column with generator """ updated_rows = [] for row in rows: mutable_row = list(row) mutable_row.append(column_generator(row)) updated_rows.append(mutable_row) mutable_header = list(header) ...
def calc_n_param_from_bins(value_min, value_max, n_bins): """Return the correct number of bins for initialising the gaussian smoothers.""" assert n_bins > 0 assert isinstance(n_bins, int) bin_width = (value_max - value_min) / n_bins if n_bins == 1: n_param = 2 elif n_bins == 2: ...
def helper_for_blocking_services_via_tcp(service): """ Helper for blocking a service via tcp """ args = [] args.append("-iptables-reset-ip") args.append(service) return args
def _reference_expect_copies(chrom, ploidy, is_sample_female, is_reference_male): """Determine the number copies of a chromosome expected and in reference. For sex chromosomes, these values may not be the same ploidy as the autosomes. The "reference" number is the chromosome's ploidy in the CNVkit refe...
def format_flag_query(flags: dict) -> str: """ Takes a dictionary of flags and parses it into a space separated string: "<key>:<value> <key>:<value> ..." to be injected as a query parameter. Args: flags: dict Returns: str, space separated with "<key>:<value" e.g. ...
def parse_wigos_id(wigos_id: str) -> dict: """ Returns the WIGOS Identifier (wigos_id) in string representation as the individual components in a dictionary. The WIGOS Identifier takes the following form: <WIGOS identifier series>-<issuer>-<issue number>-<local identifier> See https://comm...
def create_data_model(costs_matrix, start_index, end_index): """Stores the data for the problem.""" data = {'distance_matrix': costs_matrix, 'num_vehicles': 1, 'starts': [start_index], 'ends': [end_index]} return data
def chance_of_missing(num_of_keys: int, num_of_draws: int, total_choices: int): """Given total number of choices, the number of keys among the choices, and total number of draws, what are the chances of not being to draw a single key in all the draws. """ r = 1 for _ in range(num_of_draws): ...
def strip_blanks(lines): """Strip lines and remove blank lines.""" return [line.strip() for line in lines if line.strip() != '']
def get_value(json_data, property): """Get the values from json_data.""" return json_data.get(property, [''])[0]
def GetJulianEphemerisDay(julian_day, delta_seconds = 66.0): """delta_seconds is the value referred to by astronomers as Delta-T, defined as the difference between Dynamical Time (TD) and Universal Time (UT). In 2007, it's around 65 seconds. A list of values for Delta-T can be found here: ftp://maia.usno.na...
def within_bounds( x: float, y: float, min_x: float, min_y: float, max_x: float, max_y: float ): """ Are x and y within the bounds. >>> within_bounds(1, 1, 0, 0, 2, 2) True """ return (min_x <= x <= max_x) and (min_y <= y <= max_y)
def removeprefix(in_str: str, prefix: str) -> str: """remove string prefix""" if in_str.startswith(prefix): return in_str[len(prefix):] return in_str[:]
def _new_board(board_size): """Return a emprty tic-tac-toe board we can use for simulating a game. Args: board_size (int): The size of one side of the board, a board_size * board_size board is created Returns: board_size x board_size tuple of ints """ return tuple(tuple(0 for _ in ...
def negative_dice_parse(dice: str) -> str: """ :param dice: Formatted string, where each line is blank or matches t: [(t, )*t] t = (0|D|2T|FT|2F|F|T) (note: T stands for Threat here) :return: Formatted string matching above, except tokens are r...
def is_array(obj): """Return True if object implements necessary attributes to be considered similar to a numpy array. Attributes needed are "shape", "dtype", "__getitem__" and "__array__". :param obj: Array-like object (numpy array, h5py dataset...) :return: boolean """ # add more req...