content
stringlengths
42
6.51k
def _normalize_coverage(coverages): """ Exclude any coverage requirements that have `facebook` in the path as these are internal. """ return [ (percent, dep) for percent, dep in coverages if "facebook" not in dep ] if coverages else None
def generate_transaction_subsets(transaction, k): """ Get subsets of transactions of length k >>> generate_transaction_subsets(['A', 'B', 'C', 'D', 'E'], 4) [('A', 'B', 'C', 'D'), ('A', 'B', 'C', 'E'), ('A', 'B', 'D', 'E'), ('A', 'C', 'D', 'E'), ('B', 'C', 'D', 'E')] :param transaction: list :...
def extract_index_as_string(name): """Return the library or sample name index as a string Arguments: name: the name of a sample or library Returns: The index, consisting of the trailing numbers from the name. It is returned as a string to preserve leading zeroes, e.g. '1' for 'LD_C...
def makeHeader(seqs): """ Make a header for the BAM file """ header = { 'HD': {'VN': '1.0'}, 'SQ': [] } for seqName in seqs: # {'LN': 1575, 'SN': 'chr1'}, header['SQ'].append({'LN': len(seqs[seqName]), 'SN': seqName}) return header
def get_note_freq(p): """ Return the frequency corresponding to a particular note number Parameters ---------- p: int Note number, in halfsteps. 0 is a concert a """ return 440*2**(p/12)
def byte_mask(n): """ Returns a mask that covers just the nth byte (zero-indexed), starting from the least-significant digits. """ return (1 << (8 * n)) * 0xff
def read_key_bool(op, key): """Reads a key from dict, ensuring valid bool if present.""" if key in op: assert isinstance(op[key], bool), 'must be bool: %s' % key return op[key] return None
def build_cosr(request_status, cosd, vnfr_ids, csr_ids, service_instance_id): """ This method builds the whole NSR from the payload (stripped nsr and vnfrs) returned by the Infrastructure Adaptor (IA). """ cosr = {} # cosr mandatory fields cosr["descriptor_version"] = "cosr-schema-01" c...
def _gcd(num1: int, num2: int) -> int: """Get the GCD of the given two numbers""" while num1 % num2 != 0: old_num1 = num1 old_num2 = num2 num1 = old_num2 num2 = old_num1 % old_num2 return num2
def split_on_whitespace(text): """ Runs basic whitespace cleaning and splitting on a peice of text. e.g, 'a b c' -> ['a', 'b', 'c'] """ text = text.strip() if not text: return [] return text.split()
def gen_gradient(args, resource, inflow, radius, loc, common=True): """ Returns a line of text to add to an environment file, initializing a gradient resource with the specified name (string), inflow(int), radius(int), and location (tuple of ints) """ return "".join(["GRADIENT_RESOURCE ", str(re...
def count_pins(n_ring): """Count the pins in the assembly. Parameters ---------- n_ring : int Number of pin rings in assembly, where ring=1 is center pin Returns ------- int Number of pins in the assembly. Notes ----- The number of pin rings is equal to the num...
def add_markdown_quotes(text): """ Add Markdown quotes around a piece of text """ if not text: return '' split_desc = text.split('\n') for index, line in enumerate(split_desc): split_desc[index] = '> ' + line return '\n'.join(split_desc)
def truncate(data, sizes): """ @param data - A list of a list of values @param sizes - A list of max sizes Shrink each value in data to it's corresponding max size Show truncation by replacing the last 2 characters with `..` """ truncated = [] for row in data: truncated_row = []...
def shift_window_inside_image(start, end, image_axis_size, input_axis_size): """ If the window goes outside the bound of the image, then shifts it to fit inside the image. """ if start < 0: start = 0 end = start + input_axis_size elif end > image_axis_size: end = image_axis_s...
def is_should_pass_and_warn(sort_module: str) -> bool: """Test helper. """ if sort_module == "counting": print("Just pass for counting") return True return False
def decode_escaped_bytes(s: str, encoding="utf-8") -> str: """Convert escaped bytes in the \\xhh format to unicode characters.""" return ( s.encode("latin1") # To bytes, required by 'unicode-escape' .decode("unicode-escape") # Perform the actual octal-escaping decode .encode("lati...
def two_sequences_in_parallel(sequence1, sequence2): """ Demonstrates iterating (looping) through TWO sequences in PARALLEL. This particular example assumes that the two sequences are of equal length and returns the number of items in sequence2 that are bigger than their corresponding item in sequ...
def lookup_pipeline_parser_name(aset_name, pipe_name, parser_name): """Find the flattened name of a pipeline parser running under an analysis set. """ return f'{pipe_name}-~-{parser_name}-~-{aset_name}'
def dict_to_qs(dct): """ Takes a dictionary and uses it to create a query string. """ itms = ["%s=%s" % (key, val) for key, val in list(dct.items()) if val is not None] return "&".join(itms)
def is_immediate(addr): """ Evaluates whether or not an addressing is immediate """ if 0x0600 < addr < 0x0800: return True else: return False
def selector(result, roman_string, one, four, five, nine): """Selects the appropriate roman character for the number given.""" if 0 < result <= 3: for r in range(result): roman_string = roman_string + one elif result == 4: roman_string = roman_string + four elif 9 > re...
def levenshtein(a,b): """Calculates the Levenshtein distance between a and b. (Clever compact Pythonic implementation from hetland.org)""" n, m = len(a), len(b) if n > m: a,b = b,a; n,m = m,n current = range(n+1) for i in range(1,m+1): previous,current = current,[i]+[0]*n ...
def check_input(year, month, work_hours_max): """ Return True when all conditions are met Parameters: year (int): current year month (int): order of current month """ if (0 < month <= 12) and (1990 <= year <= 2100) and (0 < work_hours_max <= 24): return True else: return Fals...
def chain(_cb, *args, **kwargs): """ The proper way to check properties of duck-typed objects is to ask them if they quack, not to see if they fit in a duck-sized container. Ref: https://realpython.com/python-kwargs-and-args/ https://stackoverflow.com/questions/624926/how-do-i-detect-whether-a-python-variabl...
def _move_left(p, index): """exchange blank position with the tile on the left""" _p = list(p) _p[index], _p[index - 1] = _p[index - 1], _p[index] return tuple(_p)
def validate_cache_seconds(string): """A number of seconds to cache a Resource in RAM.""" string = (string or '').strip() if string: return float(string) return 1.0
def to_str(to_convert: list) -> list: """ Convert a string (or real value) to any alias, band or index. You can pass the name or the value of the bands. .. code-block:: python >>> to_str(["NDVI", "GREEN", RED, "VH_DSPK", "SLOPE", DEM, "CLOUDS", CLOUDS]) ['NDVI', 'GREEN', 'RED', 'VH_DS...
def time_diff_in_ms(start, end): """ Returns the time difference end-start in ms. """ return (end-start)*1000
def _calculate_color(num, color_mode: str): """ Calculate color for input byte, represented as 0<=int<=255 (or special float code) """ color_max = 255 if type(num) == float: if num == 0.: return 255, 250, 255 elif num == 1.: return 5, 0, 5 if color_mode...
def convert_bytes(num): """ Convert num to idiomatic byte unit. :param num: the input number. :type num:int :return: str >>> convert_bytes(200) '200.0 bytes' >>> convert_bytes(6000) '5.9 KB' >>> convert_bytes(80000) '78.1 KB' """ for x in ['bytes', 'KB', 'MB', 'GB', ...
def find_voxel(x,y,z,g): """returns (i,j,k) of voxel containing point x,y,z if the point is within the grid, otherwise return the corresponding grid boundary. """ # g is grid boundaries i = max(0,int((x-g['xlo'])//g['dx'])) j = max(0,int((y-g['ylo'])//g['dy'])) k = max(0,int((z-g...
def _dict_raise_on_duplicates(ordered_pairs): """ Reject duplicate keys. (used by json load) src: https://stackoverflow.com/questions/14902299/json-loads-allows-duplicate-keys-in-a-dictionary-overwriting-the-first-value """ d = {} for k, v in ordered_pairs: if k in d: raise...
def josephus_problem_recur(n: int, k: int) -> int: """1-indexed, k-skips, Josephus problem, recursively.""" if n == 1: return 1 return (josephus_problem_recur(n - 1, k) + k - 1) % n + 1
def snapshot_state_counts_deterministic(shots): """Snapshot Statevector test circuits reference counts.""" targets = [] # Snapshot |000> targets.append({'0x0': shots}) # Snapshot |111> targets.append({'0x7': shots}) return targets
def _apply_scorer(estimator, X, y, scorer, sample_weight): """Applies the scorer to the estimator, given the data and sample_weight. If ``sample_weight`` is None ``sample_weight`` WILL NOT be passed to ``scorer``; otherwise, it will be passed. In the event that ``sample_weight`` is provided and used b...
def symbol(data): """ Get the feature symbol. """ return data["marker_symbol"]
def hasattrs(object, *names): """ Takes in an object and a variable length amount of named attributes, and checks to see if the object has each property. If any of the attributes are missing, this returns false. :param object: an object that may or may not contain the listed attributes :param n...
def get_camera_info_from_image_topic(topic): """ Returns the camera info topic given an image topic from that camera """ topic_split = topic.split('/') info_topic = topic_split[:-1] info_topic.append('camera_info') info_topic = '/'.join(info_topic) return info_topic
def crop_box_left_top(current_size, target_size): """ Returns box coordinates (x1, y1, x2, y2) to crop image to target size from left-top. """ cur_w, cur_h = current_size trg_w, trg_h = target_size assert trg_w <= cur_w assert trg_h <= cur_h x1 = 0 x2 = trg_w y1 = 0 y2 = ...
def load_from_dict(config_dict): """Check if the argument is dictionary or not. If successful it calls the parsing decorator, followed by validation decorator. This validates the keys used in the config_dict, before returning to its caller. Args: config_dict: a dict containing client configurat...
def xyToA1(x, y): """Convert (x, y) coordinates (like 0,0 or 1,4) to user-friendly coordinates (like A1 or B5).""" return chr(x + 65) + str(y + 1)
def filter_args(valid_args, kwargs): """Filters arguments from a dictionary Args: valid_args: list/tuple of valid arguments kwargs: dictionary containing program config arguments Returns Dictionary with only valid_args keys if they exists """ return dict((k, kwargs[k]) for k in va...
def jpg_coeff_to_binstr(decimal_number): """ Assigns jpeg coefficients a binary str using a 1's-complement-like encoding """ if decimal_number == 0: return '' # the only place this will come up is if the DC coeff is # exactly zero. The decoder will catch this and insert a 0 elif decimal_n...
def parse_attribute_map(filenames): """ Expects a file with each line being composed of the oid for the attribute exactly one space, a user friendly name of the attribute and then the type specification of the name. :param filenames: List of filenames on mapfiles. :return: A 2-tuple, one dictio...
def more_than_half_number(nums): """ :param nums:list :return: mode """ count = 0 most = nums[0] for n in nums: if n == most: count += 1 else: count -= 1 if count < 0: most = n count = 1 return most
def line_eq(x): """ Line equation for photometric rejects """ xs = (1.5, 3) ys = (7.5,10.) m = (ys[1] - ys[0]) / (xs[1] - xs[0]) c = ys[0] - m * xs[0] return m*x + c
def sum_multiples(n): """ return number >>> sum_multiples(10) 23 >>> sum_multiples(100) 2318 >>> sum_multiples(1000) 233168 """ multiple = [num for num in range(n) if num % 3 == 0 or num % 5 == 0] return sum(multiple)
def clean_url(url_str): """ Cleans a given URL. :param url_str: String formatted URL. :return: Cleaned string formatted URL. """ url_str = url_str.lower() url_str = url_str.strip() return url_str
def get_player_pos(level, player_char='*'): """Returns a (x, y) tuple of player char on the level""" for y, row in enumerate(level): for x, char in enumerate(row): if char == player_char: return x, y
def _gr_xmin_ ( graph ) : """Get minimal x for the points >>> graph = ... >>> xmin = graph.xmin () """ xmn = None np = len(graph) for ip in range( np ) : x , y = graph[ip] if None == xmn or x <= xmn : xmn = x return xmn
def _build_info_response(ndocs, language, done): """ Construct the expected response when we get the project's info after requesting a build. """ response = { 'json': { 'project_id': 'projid', 'document_count': ndocs, 'language': language, 'las...
def getValidValues(values, threshold = 1e10): """ Get the valid values in a list. Valid means the absolute value is lower than some threshold. For numpy arrays, consider values[np.abs(values) < threshold] Parameters ---------- values : list of floats threshold : float, optional. The ab...
def sum_dicts(dicts): """Sums the dictionaries entrywise. Parameters ---------- dicts : list A list of dictionaries with numeric entries. Returns ------- dict A dict with the sum. """ # Sum repeated entries. sum_dict = {} for val_dict in dicts: for i...
def remove_nonascii(string_nonASCII): """ Removes the non ascii chars from passed string """ if not string_nonASCII: return "" string_encode = string_nonASCII.encode("ascii", "ignore") string_decode = string_encode.decode() return string_decode
def abs_of_steel(n): """ Function to illustrate the use of duck typing for make an abs function that works on iterables and scalars. :param n: List or scalar :return: The absolute value of the iterable or scalar. """ try: # Assume that abs will work, and try to run it. return ab...
def e(n): """ :param n: (float) :return: scientific notation of n (str) """ a = "%E" % n return a.split("E")[0].rstrip("0").rstrip(".") + "E" + a.split("E")[1]
def _field_path_to_elasticsearch_field_name(field_path): """Take a field_path tuple - for example: ("va", "info", "AC"), and converts it to an elasicsearch field name. """ # drop the 'v', 'va' root from elastic search field names return "_".join(field_path[1:] if field_path and field_path[0] in ("v...
def split_minutes(minutes): """ Format 00:00:00 style lengths """ hours, minutes = divmod(minutes, 60) return int(hours), int(minutes)
def make_splits(seq, train_ratio: float): """split valid and test set from the remaining data.""" tr_idx = int(train_ratio * len(seq)) vl_idx = int((1 - train_ratio) * len(seq) / 2) return seq[:tr_idx], seq[tr_idx : tr_idx + vl_idx], seq[tr_idx + vl_idx :]
def ndependents(dependencies, dependents): """ Number of total data elements that depend on key For each key we return the number of data that can only be run after this key is run. The root nodes have value 1 while deep child nodes will have larger values. Examples -------- >>> dsk = {'...
def strict_equal(a, b): """Checks the equality of the types of the values as well as the values, and handle errors.""" # pylint: disable=unidiomatic-typecheck # Try/catch needed because some comparisons may fail (e.g. datetimes with different tzinfo) try: return type(a) == type(b) and a == b except Except...
def red(string: str) -> str: """Wraps the given string in terminal color code red""" return "\033[91m" + string + "\033[0m"
def index_subs(ind, substitution): """ A simple subs function that works both on tuples and strings """ if ind is None: return ind else: return tuple([substitution.get(c, c) for c in ind])
def is_valid_hgt(height): """Checks for valid Height.""" if 'cm' in height: measurement = int(height.split('cm')[0]) if 150 <= measurement <= 193: return True else: return False elif 'in' in height: measurement = int(height.split('in')[0]) if 5...
def _hue2rgb(v1, v2, vH): """Private helper function (Do not call directly) :param vH: rotation around the chromatic circle (between 0..1) """ while vH < 0: vH += 1 while vH > 1: vH -= 1 if 6 * vH < 1: return v1 + (v2 - v1) * 6 * vH if 2 * vH < 1: return v2 if 3 * vH < 2: return v1 +...
def part2(depths): """ Use the sum of 3-value windows to determine if the depth has increased or not If there are not at least 3 values left, stop """ depth_increases = 0 previous_depth_sum = depths[0] + depths[1] + depths[2] for i in range(len(depths)): if i+2 >= len(depths): ...
def get_num_pred(confusion_table, actual_class, pred_class): """ Helper function to get the number of instances that are actual_class but predicted as pred_class from confusion table. :param confusion_table: :param actual_class: :param pred_class: """ if actual_class not in confusion_tab...
def is_leap_year(year: int) -> bool: """Returns whether the given year is a leap year""" if year % 100 == 0: return year % 400 == 0 else: return year % 4 == 0
def remove_hex(text): """ Example: "\xe3\x80\x90Hello \xe3\x80\x91 World!" """ res = [] i = 0 while i < len(text): if text[i] == "\\" and i+1 < len(text) and text[i+1] == "x": i += 3 res.append(" ") else: res.append(text[i]) i += 1...
def get_reverse_nibbles(bytes_array): """ Reverse nibbles in arbitrary-length bytes array """ return bytes.fromhex(bytes_array.hex()[::-1])
def get_fault(my_result: float, real_result: float) -> float: """ Get real fault :param my_result: result from my methods :param real_result: result from NumPy :return: real fault """ return abs(real_result - my_result)
def _convert_from_F(temp: float) -> float: """ Convert F temp to C param temp: temp in F to convert return: float """ return round((temp - 32) * 5/9, 1)
def distance(model_result_summary_dict: dict, observations_dict: dict) -> float: """Simple distance function just returns the absolute difference between the model result and the observations. Note that these inputs are dictionaries.""" # 'model_summary' was the key in the dict that is returned by summa...
def find_vnic_by_ip(ip_addr, vnics): """ Given an ip address and a list of vnics, find the vnic that is assigned that ip. Parameters ---------- ip_addr : str The ip address. vnics : dict The list of virtual network interface cards. Returns ------- The matchi...
def getFibonacciIterative(n: int) -> int: """ Calculate the fibonacci number at position n iteratively """ a = 0 b = 1 for i in range(n): a, b = b, a + b return a
def apply_policy(observation): """ A policy under which one will stick if the sum of cards is >= 20 and hit otherwise. """ score, dealer_score, usable_ace = observation return 0 if score >= 20 else 1
def binop(x, y, op): """ Returns op(x,y), where either x or y can be None, to indicate 'missing data'. The op() argument is a binary callable, e.g. op=min or op=(lambda x,y:x+y). """ if (x is None) and (y is None): return None x = x if (x is not None) else 0 y = y if (y is not None...
def sanitizeTex(texstring): """ Cleans up overly eager LaTeX renderings from pandas. Parameters ---------- texstring : string The string of LaTeX code to be cleaned up Returns ------- sanitized : string Cleaned up LaTeX string. """ newstring = ( texstring....
def zo_to_pm(zo): """ Goes from plus-minus to zero-one """ return (-1)**zo
def is_base_complement(c1, c2): """Returns true if c1 is a watson-crick complement of c2 args: c1 -- char c2 -- char returns: bool -- True if is complement, false otherwise """ if c1 == "A": return c2 == "U" elif c1 == "U": return c2 == "G" or c2 == "A" ...
def _get_mass_value_and_error(raw): """Entries look like "1.8e6(1.5,2.2)" """ val, err = raw.split('(') err_lo, err_hi = err.split(',') err_hi = err_hi.strip(')') exp = "e" + val.split('e')[-1] err_lo += exp err_hi += exp return val, err_lo, err_hi
def big_t_bt(s: int) -> int: """T_BT from KPT21""" if (s & (s - 1) == 0) and s != 0: """If s=2^i for some i""" return s else: return 0
def check_port(port): """ Check that the host port is valid Keyword arguments: port -- an integer """ if not isinstance(port, int): return False if port not in range(1024, 65535): return False return True
def parse_forum_response(resp): """ Prepare forum json object from forum response :param resp: forum response :return: required forum json object """ name = resp.get('name', '') hostname = resp.get('hostname', '') tags_list = [tag['name'] for tag in resp['tags']] tags_value = ', '....
def from_json(json_data, key): """Extract values from JSON data. :arg dict json_data: The JSON data :arg str key: Key to get data for. :Returns: The value of `key` from `json_data`, or None if `json_data` does not contain `key`. """ if key in json_data: return json_data[key] ...
def _to_sf_location(lx: str) -> str: """Append SF specific info to location string to improve GeoLocation lookup""" return lx + ", San Francisco, CA"
def optimal_summands(n: int): """ Gets the maximum number of distinct prizes. >>> optimal_summands(6) [1, 2, 3] >>> optimal_summands(8) [1, 2, 5] >>> optimal_summands(2) [2] """ if n <= 2: return [n] opt_sum = 0 summands = [] for num in range(1, n): ...
def _RemoveXclangFlags( flags ): """Drops -Xclang flags. These are typically used to pass in options to clang cc1 which are not used in the front-end, so they are not needed for code completion.""" sanitized_flags = [] saw_xclang = False for flag in flags: if flag == '-Xclang': saw_xclang = True...
def first(collection): """Start iterating over collection, and return the first element.""" return next(iter(collection))
def parse_hex(text: str) -> int: """ Parse hex string in either 0xnn or nnh formats. https://stackoverflow.com/a/604244/3347 """ text = text.rstrip('h') if not text.startswith('0x'): text = '0x' + text return int(text, 0)
def is_s(c): """Tests production [3] S Optimized for speed as this function is called a lot by the parser.""" return c is not None and c in "\x20\x09\x0A\x0D"
def opengl_to_bullet_frame(vec): """ Converts a rotation or a translation from the opengl ref frame to the bullet ref frame (Y-UP vs Z-UP) Parameters: vec - A vector xyz, list of 3 elements """ return [vec[0], vec[2], -vec[1]]
def num_matches(list1, list2): """returns the number of elements that the 2 lists have in common""" list1.sort() list2.sort() matches = i = j = 0 lenLst1 = len(list1) lenLst2 = len(list2) while i < lenLst1 and j < lenLst2: if list1[i] < list2[j]: i+=1 elif lis...
def maybe_a(a, b, func): """ Compute func(a, b) when a could be None. Args: a (any; maybe None) b (any) func (callable) Returns: func(a, b) or b if a is None """ if a is not None: return func(a, b) return b
def compute_spike_rate(spikes): """Estimate spike rate from a vector of spike times, in seconds. Parameters ---------- spikes : 1d array Spike times, in seconds. Returns ------- float Average firing rate. Examples -------- Compute spike rate of 6 spikes >>...
def quadrant(coorX, coorY, maxX, maxY, quadrant=0): """ Moves a point to a quadrant :param coorX: point in x coordinate :param coorY: point in y coordinate :param maxX: max value in x axis :param maxY: max value in y axis :param quadrant: Cartesian quadrant, if 0 or False it leaves coorX an...
def catalan(n): """ Returns n'th catalan number Parameters ---------- n : int represent the position of catalan number starting from zero """ if(n<0): raise NotImplementedError( "Enter a valid natural number" ) if(n==0 or n==1): return 1 ...
def ConvertVolumeSizeString(volume_size_gb): """Converts the volume size defined in the schema to an int.""" volume_sizes = { "500 GB (128 GB PD SSD x 4)": 500, "1000 GB (256 GB PD SSD x 4)": 1000, } return volume_sizes[volume_size_gb]
def create_products_impressions(queryset): """Create impressions for Google Analytics""" impressions = [] if queryset is None: return [] for index, product in enumerate(queryset): impressions.append(dict(id=product.reference, \ name=product.name, price=product.get_price()...