content
stringlengths
42
6.51k
def coords2idx(c, shape): """ (2,3) --> 2 * cols + 3 """ assert len(c) == 2 cols = shape[1] return c[0] * cols + c[1]
def b64max(char_length): """ Maximum number of raw bits that can be stored in a b64 of length x """ # Four byte increments only, discard extra length return (char_length // 4) * (3 * 8)
def series_generator(osversion): """ Generate series/branch name from OS version. :param osversion: OS version. :type osversion: str """ splits = osversion.split(".") return "BB{0}_{1}_{2}".format(*splits[0:3])
def get_list_depth(list_) -> int: """ Get the number of nesting of list """ if isinstance(list_, list) and len(list_) >= 1: return 1 + max(get_list_depth(item) for item in list_) else: return 0
def capitalize_string(input_string): """Converts the first character of a string to its uppercase equivalent (if it's a letter), and returns the result. Args: input_string: str. String to process (to capitalize). Returns: str. Capitalizes the string. """ # This guards against e...
def multiply_factors(factors): """ Return the product of the factors. """ prod = 1 for ordinal, exponent in factors: prod *= ordinal ** exponent return prod
def pointInRect(x, y, left, top, width, height): """Returns ``True`` if the ``(x, y)`` point is within the box described by ``(left, top, width, height)``.""" return left < x < left + width and top < y < top + height
def bh2u(x: bytes) -> str: """ str with hex representation of a bytes-like object >>> x = bytes((1, 2, 10)) >>> bh2u(x) '01020A' """ return x.hex()
def index(items): """Create an index/codebook that maps items to integers.""" return dict((v, k) for k, v in enumerate(sorted(items)))
def hex_int(val): """Convert an integer into a decimal-encoded hex integer as bytes, which the EMV spec seems awfully keen on. >>> hex_int(123456) [0x12, 0x34, 0x56] >>> hex_int(65432) [0x06, 0x54, 0x32] """ s = str(val) if len(s) % 2 != 0: s = "0" + s return [int(s[i : ...
def convert_functions_in_dict_to_values(dict_to_convert): """ When passed a dictionary that contains functions as some of its values, it converts them to their responses """ return {key: value() if hasattr(value, '__call__') else value for key, value in dict_to_convert.items()}
def maxSubArray(nums): """ :type nums: List[int] :rtype: int """ if len(nums) == 1: return nums[0] total_max_sum = float("-inf") for i in range(len(nums)-1): max_sum = nums[i] temp_max_sum = max_sum for j in range(i+1, len(nums)): temp_max_sum...
def char_stats( char, charOccurrenceMap, totalCharCount ): """ Explicity define, presence and absence of expected characters. In this case, I want to produce numbers for characters in set ["A","C","T","G","N","P"]. I want to know when characters are not present and to be able to print them to ...
def maximizing_xor(l, r): """Hackerrank Problem: https://www.hackerrank.com/challenges/maximizing-xor/problem Given two integers, l and r, find the maximal value of a xor b, written a @ b, where a and b satisfy the following condition: l <= a <= b <= r Solve: We XOR the l and r bound and ...
def f_filter_null(nif_ref, year_ref, pfeatures, qvalue): """Null filter data.""" return nif_ref, year_ref, pfeatures, qvalue
def unique_strategies(strategies): """ Extract unique strategies from array of strategies. Parameters ---------- strategies : Strategy list Strategies to be processed. Returns ------- Strategy set : Unique strategies. """ # Using set (we must define hash to use...
def verilator_name_to_standard_modular_name(verilator_name): """Converts a name exposed in Verilator to its standard name. In short, this function decodes special character encodings used by Verilator to get C++ friendly names, and it drops the top-level module name. Verilator encodes raw signal n...
def rev(sis): """Utility function""" return (sis[1], sis[0])
def ingest_configs(datacube_env_name): """ Provides dictionary product_name => config file name """ if datacube_env_name == "s3aio_env": return { 'ls5_nbar_albers': 'ls5_nbar_albers_s3test.yaml', 'ls5_pq_albers': 'ls5_pq_albers_s3test.yaml', } return { 'l...
def check_arg(name, value, exp_type, exp_range=()): """ Checks a value against an expected type and range. Used for data preprocessign and projections. Keyword Arguments: - name: name of the argument, for error messages - value: value - exp_type: the type that the value should have - ex...
def _compute_change(current_subs, new_subs): """ Determines the list of submodules that have been removed. Also needs to determine if any submodules need to have recursive init disabled current_subs - List of selective submodule init entries for the current combo new_subs - List of selec...
def a_baz(dependencies, _possible_dependencies): """ Use an undeclared dependency. """ return dependencies['bar']
def truncate_at_eos(mt, preds, true, eos_token=u'</S>'): """ Cut sequences based on location of the eos token Params: mt: 2d sequence of mt tokens preds: 2d sequence of predicted true: 2d sequence of ground truth tokens eos_token: the symbol used as the EOS token Returns: ...
def get_both_marks(course_record, course_code): """(str, str) -> str Return a string of coursemark and exammark if the course record matches with the course code. >>>get_both_marks('MAT,90,94', 'MAT') '90 94' >>>get_both_marks('MAT,90,94', 'ENG') '' """ if course_code in course...
def encode_direct(list_a: list): """Problem 13: Run-length encoding of a list (direct solution). Parameters ---------- list_a : list The input list Returns ------- list of list An length-encoded list Raises ------ TypeError If the given argument is not ...
def roman_numeral_from_string(numeral): """ Converts a roman numeral string into an integer :param string: Roman numeral as a string :returns int: integer value of string or None if failed to convert """ the_answer = 0 fail = False numerals = {'I': 1, 'V': 5, 'X': 10, 'L':50, 'C':100, 'D...
def cmp(a, b): """Comparison function for Python 3 https://stackoverflow.com/a/22490617/10840 """ return (a > b) - (a < b)
def hex_array(data): """ Convert six.binary_type or bytearray into array of hexes to be printed. """ # convert data into bytearray explicitly return ' '.join('0x%02x' % byte for byte in bytearray(data))
def is_valid_output_minimize(ext): """ Checks if output file format is compatible with Obminimize """ formats = ["pdb", "mol2"] return ext in formats
def tamper(payload, **kwargs): """ Appends special crafted string Notes: * Useful for bypassing Imperva SecureSphere WAF * Reference: http://seclists.org/fulldisclosure/2011/May/163 >>> tamper('1 AND 1=1') "1 AND 1=1 and '0having'='0having'" """ return payload + " and '0ha...
def selection_sort_dec1(array): """ it looks for smallest value for each pass, after completing the pass, it places it in the proper position it has O(n2) time complexity smaller numbers are sorted first """ for i in range(len(array)-1,-1,-1): small = i for j in range(0,i): if array[small] > array[j]: ...
def interface_has_mirror_config(mirror_table, interface_name): """Check if port is already configured with mirror config """ for _,v in mirror_table.items(): if 'src_port' in v and v['src_port'] == interface_name: return True if 'dst_port' in v and v['dst_port'] == interface_name: ...
def package_prop_by_tab(package, tabs, template=False): """Return a dictionary of tabs and their property query set for a package""" out = {} for tab in tabs: if template: props = package.properties.filter(tab=tab[0]) if len(props) > 0: out[tab[0]] = package.p...
def graph_knowledge_load(word, wtype, ident, relations): """Given the original data to 'identify' - (see ident_parent_object) and a resolved cache object from an API of knowledge for flat content. Convert the data into a tree graph ready for contex api walking. Return a result dict, in the same...
def my_sum(my_list): """Calculates the sum of a given list. Keyword arguments: my_list (list) -- Given list. Returns: Float -- Sum of given list. """ my_total = 0 for i in my_list: my_total += i return my_total
def hex2str(s): """given an ascii string of single-byte hex literals, interpret as ascii""" return bytes.fromhex(s).decode('ascii')
def fibo_sum(number: int): """ Recursively calculates the fibonacci sequence's sum up to a given number. :param number: An integer that represents the last fibonacci number. :return: The sum of the sequence. """ if number < 2: return number return fibo_sum(number - 1) + fibo_sum(n...
def linramp(valstart, valend, dur): """ Generates a linear ramp of values. **Parameters** valstart: *float* The value at the start of the ramp. valend: *float* The value at the end of the ramp. dur: *int* The number of steps in the ramp. **Returns** List of...
def lfilter(predicate, iterable): """ >>> lfilter(lambda x: x % 2, range(10)) [1, 3, 5, 7, 9] """ return list(filter(predicate, iterable))
def dict_from_hash(hashstring): """ From a hashstring (like one created from hash_from_dict), creates and returns a dictionary mapping variables to their assignments. Ex: hashstring="A=0,B=1" => {"A": 0, "B": 1} """ if hashstring is None: return None if len(hashstring) == 0: return {} re...
def concatenate_string(*args): """ Author : Niket Shinde Description : Marge multiple strings to to_dict :param args: string sequences :return: Marged string """ # string = "" # for temp_str in args: # string += temp_str return ''.join([x for x in args])
def fitsToJpegExtension(filename): """fitsToJpegExtension. Args: filename: """ newName = filename[:filename.find('.fits')] + '.jpeg' return (newName)
def utf8_decode(b: bytes) -> str: """Decodes a byte sequence with utf-8 and returns its string. If decoding fails, it will be replaced with U+FFFD. Args: b: A byte sequence to decode with utf-8. Returns: A utf-8 decoded string. """ return b.decode("utf-8", "replace")
def clear_state(dict_in): """Clear the state information for a given dictionary. Parameters ---------- dict_in : obj Input dictionary to be cleared. """ if not isinstance(dict_in,dict): return dict_in for k,v in dict_in.items(): if isinstance(v,dict): d...
def terminal(board): """ Returns True if game is over, False otherwise. """ boardelements = [] for row in board: for element in row: boardelements.append(element) myset = set(boardelements) if len(myset) > 1: # for checking rows for (i, row) in enumerat...
def parse_range(range_str): """ Parse the chrom, start and end from the range string Args: range_str (str): In format chrom:start-end Returns: chrom (str), start (int), end (int) """ chrom, start_end = range_str.split(":") start, end = start_end.split("-") return str(chrom), ...
def fprint(txt): """ Print some text in a debug file """ f = open('/tmp/cgs_debug.txt', 'a') f.write(str(txt)+"\n") f.close() return True
def convert_domain(dom): """Return equivalent integer domain if C{dom} contais strings. @type dom: C{list} of C{str} @rtype: C{'boolean'} or C{(min_int, max_int)} """ # not a string variable ? if not isinstance(dom, list): return dom return (0, len(dom) - 1)
def _is_p_power(a, p): """ Determine whether ``a`` is a ``p`` th power. INPUT: - ``a`` -- an integer - ``p`` -- a prime number OUTPUT: - True if ``a`` is a ``p`` th power; else False. EXAMPLES:: sage: sage.combinat.binary_recurrence_sequences._is_p_power(2**7,7) ...
def short_kill_m(well, neighbor): """If the well is xantophore and neighbor is melanophore, kill the xantophore""" # Note that original paper assumes that the chromaphores kill each other at the same rate (sm == sx == s) if (well == 'X') & (neighbor == 'M'): return 'S' else: return well
def _transpose(in_data, keys, field): """Turn a list of dicts into dict of lists Parameters ---------- in_data : list A list of dicts which contain at least one dict. All of the inner dicts must have at least the keys in `keys` keys : list The list of keys to extrac...
def Sundaram(n: int) -> list: """ Sieve of Sundaram. """ k = (n-2) // 2 prime = [True]*(k+1) for i in range(1, k+1): j = i while i + j + 2*i*j <= k: prime[i + j + 2*i*j] = False j += 1 prime_numbers = [2] for i in range(1, k+1): ...
def listify(obj) -> list: """Converts obj to a list intelligently. Examples -------- Normal usage:: listify('str') # ['str'] listify((1, 2)) # [1, 2] listify(len) # [<built-in function len>] """ if isinstance(obj, str): return [obj] try: retur...
def trailing_indent(str): """Count the lead indent of a string""" if not isinstance(str, list): str = str.splitlines(True) for line in reversed(str): if line.strip(): return len(line) - len(line.lstrip()) return 0
def write_nonequilibrium_trajectory(nonequilibrium_trajectory, trajectory_filename) -> float: """ Write the results of a nonequilibrium switching trajectory to a file. The trajectory is written to an mdtraj hdf5 file. Parameters ---------- nonequilibrium_trajectory : md.Trajectory The t...
def fibonacci(x): """Function docstring The fibonacci() function will take in a value x and give the numbers in the fibonacci sequence up to the x number. Args: x(int): parameter 1 Returns: fiblist: The list of fibonacci sequence numbers up to the input value """ as...
def sign_in_handler(sender, message, bot_id, app_id): """Return attendance google form""" if '!attendance' in message: return "https://docs.google.com/forms/u/0/d/e/1FAIpQLScYQDbMuOAH4EVpUlCAPxRhmPMJGXoYnR0Loo3fIrDzp6ZgTg/formResponse" return None
def is_tachy(patient): """Calculate if this patient has tachycardia or not based on the valu of heart rate If heart rate is larger than 100, it will return "tachycardic", otherwise, it will return "not tachycardic" :param patient: The data of a patient in JSON :returns: If heart rate is large...
def class_fsck_manual(log): """An error classifier. log the console log text Return None if not recognized, else the error type string. """ if 'UNEXPECTED INCONSISTENCY; RUN fsck MANUALLY' in log: return 'FSCK_manual' return None
def normalize_range_name(name, elems=None): """Make element name usable as argument to the RANGE attribute.""" if isinstance(name, tuple): return tuple(map(normalize_range_name, name)) if '/' in name: return '/'.join(map(normalize_range_name, name.split('/'))) name = name.lower() if ...
def is_float_str(string): """ Checks if a given str can be successfully converted to a float value. :param str string: String to be evaluated. :return: Returns true if the string is float convertible and false otherwise. :rtype: bool """ try: float(string) return True exc...
def percent(num, div, prec=2): """ Returns the percentage of num/div as float Args: num (int): numerator div (int): divisor prec (None, int): rounding precision Returns: p (float) p = 100 * num/div """ num = float(num) div = float(div) if div...
def to_list(thing): """convert something to a list if necessary :param thing: Maybe a list? :type thing: str or list :return: listified thing :rtype: list """ if not isinstance(thing, list): return [thing] return thing
def shift(lattice, start: int): """Shift lattice periodically so that it starts at index 'start'. Args: lattice (any iterable): a list of objects. start (int): index of first element in new lattice. Returns: new_lattice: shifted lattice. """ leng = len(lattice) start =...
def brick_sort(arr): """Performs an odd-even in-place sort, which is a variation of a bubble sort. https://www.geeksforgeeks.org/odd-even-sort-brick-sort/ :param arr: the array of values to sort :return: the sorted array """ # Initially array is unsorted is_sorted = False while not...
def widthwrap(dna: str, wrap_length: int = 10): """Returns a dna wrapped after each ``wrap_length`` number of base-pairs. """ return "\n".join( [ dna[i * wrap_length : (i + 1) * wrap_length] for i in range((len(dna) - 1) // wrap_length + 1) ] )
def normalize_page_number(page_number, page_range): """Handle a negative *page_number*. Return a positive page number contained in *page_range*. If the negative index is out of range, return the page number 1. """ try: return page_range[page_number] except IndexError: return pag...
def humanReadableSize(size): """ Get a human-readable file size string from bytes. :Parameters: size : `int` File size, in bytes :Returns: Human-readable file size :Rtype: `str` """ for unit in ["bytes", "kB", "MB", "GB"]: if abs(size) < 1024: ...
def dequote(str): """Will remove single or double quotes from the start and end of a string and return the result.""" quotechars = "'\"" while len(str) and str[0] in quotechars: str = str[1:] while len(str) and str[-1] in quotechars: str = str[0:-1] return str
def chart_quarters(quarter_queryset, phase_queryset): """ prepare data for charting. """ quarter_data = [] original_data = {"labels": [], "data": []} adjusted_data = {"labels": [], "data": []} if phase_queryset: for phase in phase_queryset: if phase.budget_phase.name == ...
def add_slash(m): """ Helper function that appends a / if one does not exist. Parameters: m: The string to append to. """ if m[-1] != "/": return m + "/" else: return m
def TypeNameHeuristic(t): # type: (str) -> str """ For 'use'. We don't parse the imported file, so we have a heuristic based on the name! e.g. re_t or BraceGroup """ return '%s_t' % t if t[0].islower() else t
def crossSet(list1, list2): """ return the cross-set of list1 and list2 """ return list(set(list1).intersection(list2))
def parse_float(arg): """Parses an argument to float number. Support converting string `none` and `null` to `None`. """ if arg is None: return None if isinstance(arg, str) and arg.lower() in ['none', 'null']: return None return float(arg)
def h_dateqiftoint(in_date): """4/1'2008 or 12/31'2009 format in - 20091231 int out""" sp1 = str(in_date).split("'") # [0] = 4/1, [1] = 2008 sp2 = sp1[0].split("/") # [0] = 4(month), [1] = 1(day) return int(sp1[1] + sp2[0].zfill(2) + sp2[1].zfill(2))
def _get_type_name(ot): """ Examples -------- >>> _get_type_name(int) 'int' >>> _get_type_name(Tuple) 'Tuple' >>> _get_type_name(Optional[Tuple]) 'typing.Union[typing.Tuple, NoneType]' """ if hasattr(ot, "_name") and ot._name: return ot._name elif hasattr(ot, "_...
def read_all(fname, mode=None): """ read all contents of a file """ args = [fname] if mode is not None: args.append(mode) with open(*args) as f: return f.read()
def string(vec, num_per_row=None, val_format='{0:>8.3f}'): """ Write a vector to a string. :param vec: vector to form string with :type vec: list, tuple, or nd.array :param num_per_row: number of vector elements to write to a row :type num_per_row: int :rtype: str """ ...
def color_to_bytes(color): """ Args: color (int) Returns: List[int] """ return [ ((color >> 16) & 0x000000ff) >> 1, ((color >> 8) & 0x000000ff) >> 1, (color & 0x000000ff) >> 1, ]
def common_prefix(strings) -> str: """ Find the longest string that is a prefix of all the strings. """ if not strings: return '' prefix = strings[0] for s in strings: if len(s) < len(prefix): prefix = prefix[:len(s)] if not prefix: return '' f...
def encode_parameters(asl: int, voice_focus: bool) -> bytes: """ Encode the parameters to control the headset. Most of the info from this function was taken from SonyHeadphonesClient. :param asl: Ambient Sound Level. -1 = disable. 0 or 1 are 'noise canceling', up to 19 is allowed. :param voice_focu...
def clean_string(string): """Removed unwanted characters from string.""" return string.replace(" ", "_").replace("'", "_").replace(".", "").replace(",", "_").encode('ascii', errors='ignore').decode()
def max_prod_finder(n, grid, start_i, start_j, next_i, next_j): """ find largest product in grid along axis defined by start + increment e.g. main diagonal would be start_i = 0, j = 0, next_i = 1, next_j = 1 can rewrite problem 8 as: max_prod_finder(13, [input_str], 0, 0, 0, 1) after convert...
def line(t): """ A straight line connecting (0,1) and (1,0.9) """ return 1.0 - 0.1*t
def makeDaisyWithEvents(events, with_recovery, network, b): """ Make a daisy using all those ! and ? events. Add recovery using the with_recovery flag. """ daisy = "active proctype daisy () {\n\tdo" if with_recovery: daisy = "bit " + b + "= 0;\n" + daisy for event in events: daisy += "\n\t:: " + event if wi...
def parameters_to_tensor_groups(parameter_groups, attribute): """ Function to reduce a parameter group from an optimizer to tensor_group with the same structure and just the requested parameter :param parameter_groups: The parameter group to extract from :param attribute: The attribute from the paramete...
def lmemoFib(n, memoize): """ Fibonacci numbers solved with memoization using list""" if n < 3: return n if memoize[n] >= 0: return memoize[n] else: memoize[n] = lmemoFib(n-1, memoize) + lmemoFib(n-2, memoize) return memoize[n]
def decode_tag(tag): """ Decode tag used in pmd file. """ sid = int(tag) ifmv = int((tag -sid)*10) num = int(((tag-sid)*10 -ifmv)*1e+14) return sid,ifmv,num
def merge_dicts(*dicts): """ Given any number of dicts, shallow copy and merge into a new dict, precedence goes to key value pairs in latter dicts. Source: https://stackoverflow.com/q/38987 """ result = {} for dictionary in dicts: result.update(dictionary) return result
def global_id_to_cartesian(id, grid_sizes): """Map global index to its Cartesian coordinates in a grid """ # Sanity check n01 = grid_sizes[0] * grid_sizes[1] if id < 0 or id >= n01 * grid_sizes[2]: return None # Compute successive euclidean divisions k, r = divmod(id, n01) j, ...
def one_off(ids): """Find id pair that differs by one letter and return common letters.""" for index, code in enumerate(ids[:-1]): for comparison in ids[index+1:]: diff = [] to_compare = zip(code, comparison) for pos, pair in enumerate(to_compare): if ...
def get_saturation(value, quadrant): """ This function returns the saturation value of the pixel of the image. :param value: RGB color value of the pixel. :param quadrant: Quadrant of the color wheel. :return: Returns saturation value of the pixel. """ if value > 223: return 255 ...
def fix_value(value): """ Missing values are repesened by "null" - we need to convert those to None. SHMU is also pretty priting CSV, so we need to strip leading and trailing white space from values. """ svalue = value.strip() if (svalue == "null"): return None ret...
def initial(array): """Return all but the last element of `array`. Args: array (list): List to process. Returns: list: Initial part of `array`. Example: >>> initial([1, 2, 3, 4]) [1, 2, 3] .. versionadded:: 1.0.0 """ return array[:-1]
def tool_dependency_is_orphan( type, name, version, tools ): """ Determine if the combination of the received type, name and version is defined in the <requirement> tag for at least one tool in the received list of tools. If not, the tool dependency defined by the combination is considered an orphan in it's...
def _select_shorter_captions(captions, top_n): """ :param captions: a list of lists of string, such as [['a','b'],['c','d','e']] :param top_n: an integer :return: a list with top_n shortest length of the lists of string, """ assert top_n <= 10 lengths = [[x, len(y)] for x, y in enumerate(cap...
def TO_UPPER(expression): """ Converts a string to uppercase, returning the result. https://docs.mongodb.com/manual/reference/operator/aggregation/toUpper/ for more details :param expression: The string or expression of string :return: Aggregation operator """ return {'$toUpper': express...
def add_context(context, new_input): """ Update the context strings for all speakers in a conversation. Args: context: A dictionary of context strings for all speakers new_input: A string to be appended to the context for all speakers. Returns: new_context: An updated dictionary of ...
def clean_refvar(refvar: str) -> str: """Cleans refvar string of characters that cause issues for filenames. Args: refvar: A string representing a refvar. Returns: A cleaned string. """ refvar = refvar.replace(" ", "_") refvar = refvar.replace("/", "_") return refvar
def right_strip_lines(lines): """Remove trailing spaces on each line""" return [line.rstrip() for line in lines]