content
stringlengths
42
6.51k
def find_argument(inp): """ Find the start of the Arguments list. """ line = next(inp) count = 1 while 'Arguments' not in line: line = next(inp) # We assume we're going to find this within two lines of the original # location of the input # - stop looking if we ...
def binomial_convulation(Pi, theta): """Pi is a list of N+1 probabilities; {pi_0, pi_1,...pi_N}(N trials)""" n=len(Pi) N=n-1 Pi_=[(1-theta)*Pi[0]] for k in range(1, N+1): Pi_+=[theta*Pi[k-1]+(1-theta)*Pi[k], ] Pi_+=[theta*Pi[N]] return Pi_
def factorial(n: int) -> int: """Calculates the factorial of n Args: n (int): n > 0 Returns: int: factorial of n """ print(n) if n == 1: return 1 return n * factorial((n - 1))
def rows_to_load_sets(rows): """ Given rows queried from database generate "load_sets" Return Dictionary keyed by url Where the value is a list of tuples containing: (load_id, time, load_set) load_id: the unique id for this page load time: when it was captured load_set: the set of view elements...
def update_real_2d(real_2d, new_price): """@params: real_2d: List[int] new_price: int """ # left shift the real_2d for 1 day # debug print("===========") print("updating real_2d:", real_2d, " with %s" % new_price) print("updated real_2d will be: ", real_2d[1:] + [new_price])...
def filter_dict_with_list(dictionary, key_list): """ Filter dictionary to keep keys from given list Args: dictionary (dict): dictionary to filter key_list (list): keys to keep in filtered dictionary Returns: dictionary (dict): the filtered dictionary with key...
def _CV2_IMG_POS(idx, height, width, text="", pos=0): """Applies only for FONT_HERSHEY_SIMPLEX (~20px wide chars)""" margin = 0.01 charwidth, charheight = 20, 23 x = width y = height if idx in (0, 2): x *= margin if idx in (1, 3): x = x * (1 - margin) - len(text) * charwidth ...
def _get_real_user(user, anon_user=None): """ Given a "user" that could be: * a real user object * a function that returns a real user object * a LocalProxy to a real user object (like Flask-Login's ``current_user``) This function returns the real user object, regardless of which we have. ...
def pick_datatype(counts): """ If the underlying records are ONLY of type `integer`, `number`, or `date-time`, then return that datatype. If the underlying records are of type `integer` and `number` only, return `number`. Otherwise return `string`. """ to_return = 'string' if len(...
def set_bit(num: int, index: int, value: bool) -> int: """ Set the index-th bit of num to 1 if value is truthy, else to 0, and return the new value. From https://stackoverflow.com/a/12174051/1076564 . """ mask = 1 << index # Compute mask, an integer with just bit 'index' set. num &= ~mask ...
def MilitaryConvert(MilInput): """ converts the given military time from the satellite to hh:mm """ Mil = str(MilInput) size = len(Mil) minutes = Mil[-2:] #get the minutes hours = Mil[:size - 2] #get the hours time = hours + ':' + minutes if len(time) == 4 : #if its a single hour,...
def other_identifiers_to_metax(identifiers_list): """ Convert other identifiers to comply with Metax schema. Arguments: identifiers_list {list} -- List of other identifiers from frontend. Returns: list -- List of other identifiers that comply to Metax schema. """ other_identif...
def safe_str_cmp(str1: str, str2: str) -> bool: """ Compare two strings in constant time, return True if equal, False if not """ if type(str1) != str or type(str2) != str: return False return len(str1) == len(str2) and all([str1[i] == str2[i] for i in range(len(str1))])
def NumberOfSets(points): """ Returns the total number of landmark sets in the given collection of pointsets. """ count = 0 for pointset in points: if pointset[0] is not None and pointset[1] is not None: count += 1 return count
def string_to_binary(data_string): """ Returns Binary Representation of string """ return ''.join((bin(ord(c))[2:]).zfill(8) for c in data_string)
def combined_fidelity(f1: float, f2: float) -> float: """Calculate effective fidelity over two combined links.""" f12 = f1 * f2 + (1 - f1) * (1 - f2) / 3 return f12
def gen_histo(twoexp): """ Return a histogram of future games for the next round. """ lsize = (twoexp + 1) // 2 if lsize == 2: lsize = 3 retv = [] for _ in range(0, lsize): retv.append([0, 0]) return retv
def prepare_k_cross_eval_data(evals, model): """ prepare eval dict """ eval=evals[0] accuracy = 0 mae = 0 mse = 0 rmse = 0 for ev in evals: accuracy += ev['accuracy'] mae += ev['mae'] mse += ev['mse'] rmse += ev['rmse'] eval['ac...
def get_complement(sequence): """Get the complement of `sequence`. Returns a string with the complementary sequence of `sequence`. If `sequence` is empty, an empty string is returned. """ #force uppercase sequence=sequence.upper() if sequence: #use translate method to change each b...
def convertBinListToInt(bin_list): """ Convert a binary list ([1, 0, 1, 0]) to an integer :param bin_list: Binary list :return: Integer representation of the binary list (integer) """ dec = int("".join(map(str, bin_list)),2) return dec
def solution(A): """ :param A: :return: """ continuous_block_size = 0 candidate = 0 for element in A: print() print("process element "+str(element)) # when counter become zero it means new item starts and new item can be candidate if continuous_block_size == ...
def compute_wave_height(crest_height, trough_depth): """Computes wave height from given crest height and trough depth.""" assert crest_height > trough_depth return crest_height - trough_depth
def func(source, delimiter): """ :params: source,delimiter :ptypes: String,String :returns: a,b :rtype: String, String """ result = source.split(delimiter, 1) out = dict() out["a"] = result[0] if len(result) > 1: out["b"] = result[1] else: out["b"] = "" r...
def round_sig_fig(x, sf): """ Rounds a number to the specified number of significant figures. Parameters ---------- x : float number to round sf : float number of significant figures Returns ------- y : float rounded number """ format_str = "%." + s...
def three_one(three): """ Converts three-letter amino acid codes to one-letter. Arguments: three (str): Three letter amino acid code; AMBER and CHARMM nomenclature for alternative protonation states is supported, but lost by conversion. Returns: str: Corresponding one-lette...
def distance2(x1, y1, x2, y2): """calc distance between (x1,y1) and (x2, y2) without sqrt of result - faster for length comparisons""" l = (x2 - x1) * (x2 - x1 ) + (y2 - y1) * (y2 - y1) return l
def reformat_large_tick_values(tick_val, pos): """ Turns large tick values (in the billions, millions and thousands) such as 4500 into 4.5K and also appropriately turns 4000 into 4K (no zero after the decimal). """ if tick_val >= 1000000000: val = round(tick_val/1000000000, 1) new_...
def bar1s(ep, ed): """ Compute element force in spring element (spring1e). :param float ep: spring stiffness or analog quantity :param list ed: element displacements [d0, d1] :return float es: element force """ k = ep return k*(ed[1]-ed[0])
def unchunk(string): """ Remove spaces in string. """ return string.replace(" ", "")
def pretty_print_large_number(number): """Given a large number, it returns a string of the sort: '10.5 Thousand' or '12.3 Billion'. """ s = str(number).ljust(12) if number > 0 and number < 1e3: pass elif number >= 1e3 and number < 1e6: s = s + " (%3.1f Thousand)" % (number * 1.0 / 1e3)...
def _length_penalty(sequence_lengths): """https://arxiv.org/abs/1609.08144""" # return (5 + sequence_lengths) ** 0.9 / (5 + 1) ** 0.9 # return torch.sqrt(sequence_lengths) return sequence_lengths
def retrieve_parameter(line): """Return the parameter value from one line in a .csv file.""" return line.split(',', 1)[1]
def package_name(module_name): """Which name needs to be passed to pip to install a Python module Normally, the PIP package has the same same, but there are a few exceptions""" package_name = module_name if module_name == "wx": package_name = "wxPython" if module_name == "PIL": package_name = "Image...
def frange(start, stop, step): """frange(start, stop, step) -> list of floats""" l = [] if start <= stop and step > 0: x = start while x <= stop: l.append(x) x += step return l elif start >= stop and step < 0: x = start while x >= stop: ...
def uniqify(seq): """ An order preserving uniqifier that takes a sequence and gives out the uniqified sequence. Works even on object lists. CREDIT: Dave Kirby """ noDupes = [] [noDupes.append(i) for i in seq if not noDupes.count(i)] return noDupes
def arithmetic_right_shift(a: int, b: int) -> str: """ Ambil dalam 2 bilangan bulat. 'angka' adalah bilangan bulat yang secara aritmatika benar bergeser 'shift_amount' kali. Yaitu (nomor >> shift_amount) Kembalikan representasi biner yang bergeser. >>> arithmetic_right_shift(0, 1) '0b00'...
def candy(ratings): """ Candy distribution :param ratings: list of ratings :type ratings: list[int] :return: minimum number of candies to give :rtype: int """ candies = [1] * len(ratings) for i in range(len(ratings) - 1): if ratings[i + 1] > ratings[i]: candies[i...
def shift_position(pos, x_shift, y_shift) -> dict: """ Moves nodes' position by (x_shift, y_shift) """ return {n: (x + x_shift, y + y_shift) for n, (x, y) in pos.items()}
def _conditional_probability(col_a_counts_map, col_b_counts_map, both_counts_map): """ For values that a might take, maps to p(a=v|b=v). = the number f times both columns a and b have a value divided by the number of times column b has that value. returns: value->prob for given maps. NB: n...
def check_for_period(message): """Check that there is no period in the end of the subject line.""" splitted = message.splitlines() check = not splitted[0].endswith(".") return check
def display_percent(chunk_size, chunk_percent, last_percent, progress): """ Used to monitor progress of a process. Example usage: Progress = 0 chunk_percent = 10.0 chunk_size = int(math.ceil(all_files*(chunk_percent/100))) for x in all_files: Progress += ...
def _check_flag(elems, value): """ Checks that a value is a member of a set of flags. Note that we use a top-level function and `partial`. The trouble with lambdas or local defs is that they can't be pickled because they're inaccessible to the unpickler. If you don't intend to pickle your encoders...
def rn_abs(a): """ change signs of a if a < 0 :param a: RN object :return: |a| """ return a if a > 0 else -a
def list_zfill(l, width): """ Pad a list with empty strings on the left, to fill the list to the specified width. No-op when len(l) >= width. >>> list_zfill(['a', 'b'], 5) ['', '', '', 'a', 'b'] >>> list_zfill(['a', 'b', 'c'], 1) ['a', 'b', 'c'] >>> list_zfill(['a', 'b', 'c'], 3) [...
def get_local_file_path(language, page): """ :param language: string :param page: string :return: String: path without '/' at the beginning """ return "{lang}/{page}".format(lang=language, page=page)
def isBoolean(value): """Returns True if \"True\" or \"False\"""" return value == "True" or value == "False"
def genetekaMarriageUrl(record): """Generate URL to geneteka for a marriage record.""" return ( 'http://www.geneteka.genealodzy.pl/index.php?' 'op=gt&lang=pol&bdm=S&w={}&rid={}&' 'search_lastname={}&search_name={}&' 'search_lastname2={}&search_name2={}&' 'from_date={}&to_date={}&' 'exac=1&pa...
def _normalised(name): """Normalise string to make name lookup more robust.""" return name.strip().lower().replace(' ', '').replace('_', '')
def time_overlap(time_span, agent_time): """Check if agent_time overlaps with time_span""" if agent_time[0] <= time_span[1] and agent_time[1] >= time_span[0]: return True else: return False
def get_frequency_dict(sequence): """ Returns a dictionary where the keys are elements of the sequence and the values are integer counts, for the number of times that an element is repeated in the sequence. sequence: string or list return: dictionary """ # freqs: dictiona...
def parse_request(event): """ Parses the input api gateway event and returns the product id Expects the input event to contain the pathPatameters dict with the productId key/value pair :param event: api gateway event :return: a dict containing the productId key/value """ if 'pathParamete...
def raised_to(x): """ Raise the input to the power of itself """ if x == 0: return 0 else: return x**x
def bytes_to_int(n: bytes) -> int: """ turn bytes into an integer :param n: the bytes :return: the integer """ r = 0 for p in n: r *= 256 r += p return r
def _contains(a, b, c, d): """ Whether inclusive interval [a,b] contains interval [c,d] """ if not ((a <= b) and (c <= d)): raise ValueError("Left endpoint must be given before right endpoint: [{}, {}] does not contain [{}, {}]".format(a,b,c,d)) return (a <= c) and (b >= d)
def show_table_like(table_name): """Rerurns the command Arguments: db_name {string} -- [description] Returns: string -- [description] """ return "SHOW TABLES LIKE '" + table_name+ "'"
def common_suffix(l): """ Return common suffix of the stings >>> common_suffix(['dabc', '1abc']) 'abc' """ commons = [] for i in range(min(len(s) for s in l)): common = l[0][-i-1] for c in l[1:]: if c[-i-1] != common: return ''.join(reverse...
def assert_cell(cell): """ Ensure it fits into the ipython notebook cell structure: { 'cell_type': 'whatever', 'source': ['whatever'] } Otherwise raises AssertionError. Parameters ---------- cell: dict iPython notebook cell representation. Retur...
def basename_handler(value, current_file, **kwargs): """ Return a list of tuples with (dirindexes, md5, basename) """ data = [] for index, file in enumerate(current_file): basename = (value[index],) data.append(file + basename) return {'current_file': data}
def capitalize(msg: str) -> str: """ Capitalize the first character for a string. Args: msg: The string to capitalize Returns: The capitalized string """ return msg[0].upper() + msg[1:]
def local_url(url, code=None): """Replace occurences of `{locale_code} in URL with provided code.""" code = code or "en-US" return url.format(locale_code=code)
def intersector(x, y): """ Intersection between two memory values x = m' and y = m. """ parity_x = x % 2 parity_y = y % 2 if parity_x == 1: if parity_y == 1: return min(x, y) else: return y if parity_x == 0: if parity_y == 0: retur...
def replace_replacements(file_replacement, replacements, to_be_replaced): """Apply replacements to file identifier""" replaced = to_be_replaced common_keys = [key for key in file_replacement if key in replacements] for key in common_keys: old_value = file_replacement[key] new_value = rep...
def pretty_print_time(sec): """Get duration as a human-readable string. Examples: - 10.044 => '10.04 s' - 0.13244 => '132.4 ms' - 0.0000013244 => '1.324 us' Args: sec (float): duration in fractional seconds scale Returns: str: human-readable string representat...
def getExposure(header={}): """ :param header: :return: """ expTime = max(float(header.get('EXPOSURE', 0)), float(header.get('EXPTIME', 0)), ) return expTime
def euler(f, x0, y0, xn, n): """ Forward Euler's Method for a single linear equation. Parameters ---------- f : function linear equation. x0 : float initial x value. y0 : float initial f(x) value. xn : float x-value at which to estimate f. n : integer...
def check_int(s): """Convert to integer.""" try: return int(s) except ValueError: raise ValueError(f'Could not convert {s} to integer.')
def total_incl_gst(amount, gst_rate): """Calculate total including GST. Calculates total including GST and returns the GST inclusive amount and the gst_component amount. Args: amount (float): GST exlusive amount gst_rate (float): GST rate to apply. Returns: ...
def choices_from_list(source, prepend_blank=True): """ Convert a list to a format that's compatible with WTForm's choices. It also optionally prepends a "Please select one..." value. Example: # Convert this data structure: TIMEZONES = ( 'Africa/Abidjan', 'Africa/Accra', ...
def minutesToHours(minutes): """ (number) -> float convert input minutes to hours; return hours >>> minutesToHours(60) 1.0 >>> minutesToHours(90) 1.5 >>>minutesToHours(0) 0.0 """ hours = minutes / 60 hours = round(hours, 2) return hours
def _strip_suffixes(string, suffixes=None): """Remove suffixes so we can create links.""" suffixes = ['.ipynb', '.md'] if suffixes is None else suffixes for suff in suffixes: string = string.replace(suff, '') return string
def chef_download_url(name, version, registry='https://supermarket.chef.io/cookbooks'): """ Return an Chef cookbook download url given a name, version, and base registry URL. For example: >>> c = chef_download_url('seven_zip', '1.0.4') >>> assert c == u'https://supermarket.chef.io/cookbooks/seven_z...
def has_comment(line): """Determines if a string contains a fortran comment.""" return '!' in line
def bit_length(int_type): """Return the number of bits necessary to represent an integer in binary, excluding the sign and leading zeros""" length = 0 while int_type: int_type >>= 1 length += 1 return length
def image(index): """Return the image name for the given index.""" return f'im-{index}.png'
def set_difference(lst1, lst2): """returns the elements and indicies of elements in lst1 that are not in lst2""" elements = [] indicies = [] for indx, item in enumerate(lst1): if item not in lst2: elements.append(item) indicies.append(indx) return elements, indicies
def parse_claim(claim): """ Parse a line of input Example claim: #1 @ 861,330: 20x10 """ tokens = claim.split(" ") claim_id = int(tokens[0][1:]) (offset_x, offset_y) = tokens[2].split(',') offset_x = int(offset_x) offset_y = int(offset_y[:-1]) (width, height) = tokens[3].sp...
def name2id(name, maxval=2 ** 16): """ Map a name into an index. """ value = 0 for c in name: value += ord(c) return value % maxval
def convert_spanstring(span_string): """ converts a span of tokens (str, e.g. 'word_88..word_91') into a list of token IDs (e.g. ['word_88', 'word_89', 'word_90', 'word_91'] Note: Please don't use this function directly, use spanstring2tokens() instead, which checks for non-existing tokens! Ex...
def _update_with_csrf_disabled(d=None): """Update the input dict with CSRF disabled.""" if d is None: d = {} d.setdefault('meta', {}) d['meta'].update({'csrf': False}) return d
def listify_plottable_item(item): """ plottable is a list of strings: 'FBti0020401\t78\t-1.0\tR' split on tab and return gene, coordinate, count and orientation """ gene, coordinate, count, orientation = item.split("\t") return gene, coordinate, count, orientation
def is_ascii(some_string): """Check if a string only contains ascii characters""" try: some_string.encode('ascii') except UnicodeEncodeError: return False else: return True
def frange(start, end=None, increment=None): """ Adapted from http://code.activestate.com/recipes/66472 """ if end == None: end = start + 0.0 start = 0.0 if increment == None: increment = 1.0 L = [] while 1: next = start + len(L) * increment if increment > 0 and next >= end: brea...
def filter_employees(row): """ Check if employee represented by row is AT LEAST 30 years old and makes MORE THAN 3500. :param row: A List in the format: [{Surname}, {FirstName}, {Age}, {Salary}] :return: True if the row satisfies the condition. """ return row[-2] >= 300 and row[-...
def merge_dict(d1, d2): """Merge two dictionaries The second dictionary `d2` overwrites values in `d1` if they have common keys. This is equivilent to return {**d1, **2} in python3. Using this function improves python2--3 compatibility. """ out = d1.copy() out.update(d2) ...
def camel(s): """Camel case the given string""" return s[0].upper() + s[1:]
def f7(seq): """ Source: https://stackoverflow.com/a/480227/1493011 """ seen = set() return [x for x in seq if not (x in seen or seen.add(x))]
def leaders_in_array(numbers, size): """ Write a program to print all the LEADERS in the array. An element is leader if it is greater than all the elements to its right side. The rightmost element is always a leader. """ if size == 1: return numbers leaders = [] for i in range(...
def radix(data): """A sorting method called Radix.""" try: idx = -1 longest = 0 for x in data: if not isinstance(x, int): raise TypeError if len(str(x)) > longest: longest = len(str(x)) while idx != -longest - 1: ...
def sort_sublists(data): """ Ensure that any lists within the provided (possibly nested) structure are sorted. This is done because PyYAML will sort the keys in a mapping but preserves the order of lists. While it would be possible to ensure everything is sorted upstream, i.e. when it is added to e...
def split_kwargs(kwargs): """ :param dict kwargs: Split keys with commas and the corresponding values accordingly (values of comma-keys must be tuples of the same length than the splitted key). Example: >>> split_kwargs({'a,b': (1, 2), 'c': 3}) {'a': 1, 'b': 2, 'c': 3} :return dict: ...
def escape(buff): """Because otherwise Firefox is a sad panda.""" return buff.replace(',', '%2c').replace('-', '%2D')
def GetUniqueSessionID(process_obj): """ Create a unique session identifier. params: process_obj: lldb.SBProcess object refering to connected process. returns: int - a unique number identified by processid and stopid. """ session_key_str = "" if hasattr(process_obj, "...
def get_cursor(callbacks, limit=50): """ Returns the next page cursor """ return callbacks[-1].get('id') if callbacks and len(callbacks) >= limit else None
def upper(text): """ Creates a copy of ``text`` with all the cased characters converted to uppercase. Note that ``isupper(upper(s))`` might be False if ``s`` contains uncased characters or if the Unicode category of the resulting character(s) is not "Lu" (Letter, uppercase). The uppercas...
def is_manager(user): """ A simple little function to find out if the current user is a project tracker manager. """ # this code uses Django groups, we want to use roles in Project Tracker Employee: # manager = False # if user: # if user.groups.filter(name="manager").count() > 0 | us...
def HexStringToBytes ( hexStr ): """ Convert a string of hex bytes to an array of bytes. The Hex String values may or may not be space separated """ bytes = [] # Remove spaces hexStr = ''.join( hexStr.rstrip().split(" ") ) for i in range(0, len(hexStr), 2): bytes.append( int...
def extract(mod, models): """ Returns models with mod removed. """ if mod == {}: # No mod to delete, return models as it is. return models return [model for model in models if model != mod]
def is_special_char(astring): """ (str) -> Boolean returns True if astring contains a special character:!, @, #, $, %, ^, & else return False. >>> is_special_char('CIS122') False >>> is_special_char('CIS-122') False >>> is_special_char('CIS122!') True """ specia...
def ImCrossTermID(atom_names): """ # From a list of 4 atom names, corresponding two a pair # of angles between atoms# 3,2,1 and 3,2,4, # and replaces the list of atoms with a canonical tuple # which eliminates order ambiguity. # If you swap the first and last atom (#1 and #4), then # the -pa...
def is_palindrome(string): """ (str) -> bool Return True if and only if string is a palindrome. Precondition: string is all in lowercase. >>>> is_palindrome('ABCDEFG') '' >>>> is_palindrome('madamimadam') True >>>> is_palindrome('Racecar') '' >>>> is_palindrome('racecar...