content
stringlengths
42
6.51k
def binomialCoeff(n, k): """https://rosettacode.org/wiki/Evaluate_binomial_coefficients#Python""" result = 1 for i in range(1, k+1): result = result * (n-i+1) // i return result
def _IsBackslashEscapedQuote(string, quote_index): """Checks if the quote at the given index is backslash escaped.""" num_preceding_backslashes = 0 for char in reversed(string[:quote_index]): if char == '\\': num_preceding_backslashes += 1 else: break return num_preceding_backslashes % 2 == ...
def _uint_to_le(val, length): """Returns a byte array that represents an unsigned integer in little-endian format. Args: val: Unsigned integer to convert. length: Number of bytes. Returns: A byte array of ``length`` bytes that represents ``val`` in little-endian format. """ retur...
def vec_add_scalar (x, c): """[Lab 14] Adds the scalar value c to every element of x.""" return [x_i+c for x_i in x]
def errormessage(resultstring, expectedstring): """Does the formatting for the error message""" return "\n\nRESULT: %s.\nEXPECTED: %s." % (resultstring, expectedstring)
def handles_url( url ): """ Does this storage driver handle this kind of URL? """ return url.startswith("file://")
def get_user_host(user_host): """Return a tuple (user, host) from the user_host string.""" if "@" in user_host: return tuple(user_host.split("@")) return None, user_host
def twos_comp(bits): """compute the 2's complement of int value val Stolen from a stack overflow like everything else """ val = int(bits,2) bits = len(bits) if (val & (1 << (bits - 1))) != 0: # if sign bit is set e.g., 8bit: 128-255 val = val - (1 << bits) # compute negative valu...
def remove_crud(string): """Return string without useless information. Return string with trailing zeros after a decimal place, trailing decimal points, and leading and trailing spaces removed. """ if "." in string: string = string.rstrip('0') string = string.lstrip('0 ') string ...
def split(circumstances, n): """Split a configuration CIRCUMSTANCES into N subsets; return the list of subsets""" subsets = [] start = 0 for i in range(0, n): len_subset = int((len(circumstances) - start) / float(n - i) + 0.5) subset = circumstances[start:start + len_subset] ...
def is_valid_variable_name(name: str) -> bool: """ All single-letter, uppercase variable names are reserved. """ if len(name) == 1 and name.upper() == name: return False if not name.isidentifier(): return False return True
def id_to_file(id: str, image_dir) -> str: """image_id to file name""" id = str(id) file = '0' * (12 - len(id)) + id + '.jpg' return image_dir + '/' + file
def _compose_err_msg(msg, **kwargs): """Append key-value pairs to msg, for display. Parameters ---------- msg: string arbitrary message kwargs: dict arbitrary dictionary Returns ------- updated_msg: string msg, with "key: value" appended. Only string values are ...
def pfs(pitchspeed): """time until pitch full stop""" return abs(pitchspeed) / 66 + 1 / 60
def upper_case(string): """ Returns its argument in upper case. :param string: str :return: str """ return string.upper()
def choice(r,p_cumsum): """ select from cumulated probilities Args: r (double): uniform random number p_cumsum (numpy.ndarray): vector of cumulated probabilities, [x,y,z,...,1] where z > y > x > 0 Returns: i (int): selection index """ i = 0 while r > p_cumsum[i] an...
def aggregateFeaturesByTranscript(gtflines): """ aggregates a set of features by transcript_id if transcript_id does not exist it deletes the line sorts the features under a transcript by start site adds a start-end tuple to each transcript indicating where in the transcript each feature is (ref...
def compact(objects): """ Filter out any falsey objects in a sequence. """ return tuple(filter(bool, objects or []))
def _ArgSortReverse(a): """Returns the indices that would sort an array. Ties are given indices in reverse ordinal order.""" return list(reversed(sorted(range(len(a)), key=a.__getitem__, reverse=True)))
def best_stock(a: dict) -> str: """ You are given the current stock prices. You have to find out which stocks cost more. Input: The dictionary where the market identifier code is a key and the value is a stock price. Output: The market identifier code (ticker symbol) as a string. """ new_stock =...
def median(values): """ Finds the middle most value of values """ num = len(values) sorted_vals = sorted(values) midpoint = num // 2 if num % 2 == 1: return sorted_vals[midpoint] else: low = midpoint - 1 high = midpoint return (sorted_vals[low] + sorted_vals[high...
def block_search(dict_or_list, block_name, default=None): """Find block_name in dict_or_list where block_name in the form 'keya.keyb.keyc'""" current = dict_or_list if block_name is None or block_name == "" or block_name == ".": return current for part in block_name.split("."): if isinst...
def drop_unnecessary_metrics(submission_scores: dict, list_of_metrics: list): """Return submission_scores with every metric not in list_of_metrics removed.""" for data_name, data in submission_scores.items(): if data_name in ["param_count", "submission_name"]: continue filtered_score...
def read_addr(title): """Extracting address from a title.""" addr = None if (title is None): return addr sp = title.split(" in ") if (len(sp)>1): addr = sp[1].lower() return addr
def selection_sort(collection): """Implementation of the selection sort algorithm in Python :param collection: some mutable ordered collection with heterogeneous comparable items inside :return: the same collection ordered by ascending Examples: >>> selection_sort([0, 5, 3, 2, 2]) [0, ...
def split_course_key(key): """Split an OpenEdX course key by organization, course and course run codes. We first try splitting the key as a version 1 key (course-v1:org+course+run) and fallback the old version (org/course/run). """ if key.startswith("course-v1:"): organization, course, run ...
def fixslash(url, relative=True): """ Removes trailing slash. If relative is True ensures a leading slash is present otherwise ensures it is not. """ url = url.strip("/") if relative: url = "/" + url return url
def capitalize_first(line): """ capitalises the first letter of words (keeps other letters intact) """ return ' '.join([s[0].upper() + s[1:] for s in line.split(' ')])
def mode_to_int(mode): """Returns the integer representation in VPP of a given bondethernet mode, or -1 if 'mode' is not a valid string. See src/vnet/bonding/bond.api and schema.yaml for valid pairs.""" ret = {"round-robin": 1, "active-backup": 2, "xor": 3, "broadcast": 4, "lacp": 5} try: ...
def create_ports_list(values): """ Create the ports list for PPTN configuration :param values: TN Ports Configuration values :return: the complete ports list in good format :Example: result = create_ports_lists(values) """ ports_list = values.split(',') for port in ports_list: ...
def int_tuple(str_): """ Transform a string of integers into a tuple. Example: '1,2,3' becomes (1,2,3) """ strlist = str_.strip().split(',') # ['1','2','3'] return tuple([int(i) for i in strlist])
def bubble_sort(array): """ :param array: the array to be sorted. :return: sorted array. >>> import random >>> array = random.sample(range(-50, 50), 100) >>> bubble_sort(array) == sorted(array) True >>> import string >>> array = random.choices(string.ascii_letters + string.digits, k ...
def get_bbox_center(bbox): """Return the center of the bounding box :param bbox: the player bounding box [top_left x, top_left y, bottom_left x, bottom_left y] :return: the center x, y of the bounding box #>>> get_bbox_center([23,12,35,20]) #(29.0, 16.0) """ return ((bbox[2]-bbox[0])/2+bbox[...
def sign( x ): """ Returns 1 or -1 depending on the sign of x """ if( x >= 0 ): return 1 else: return -1
def get_output_jar_paths(version): """ Gets the list of output jars, which includes the primary jep-${version}.jar, the test jar, and the src jars. """ return [ 'build/java/jep-{0}-sources.jar'.format(version), 'build/java/jep-{0}.jar'.format(version), 'build/java/jep-{0}-tes...
def divide_snapshot_nodes(previous_nodes, next_nodes): """ For each snapshot divide the nodes into three groups: new- nodes that weren't in the previous snapshot, exist- nodes that are in both sequential snapshots, disappear- nodes that were in the previous snapshot but in the next they disappeared. ...
def urlencode(s): """urlencode(s) -> str URL-encodes a string. Example: >>> urlencode("test") '%74%65%73%74' """ return ''.join(['%%%02x' % ord(c) for c in s])
def remove_uuids(bib_entry): """ Removes the following fields: doi, eprint, archiveprefix, isbn @returns the filtered bib_entry """ for field in ['doi', 'eprint', 'archiveprefix', 'isbn', 'issn', 'arxivid', 'arxivId']: bib_entry.pop(field, None) return bib_entry
def jsonify_book_search_data(book_list): """return json list of database query for front-end""" json_book_list = [] for book in book_list: book_data = {'book_id': book.book_id, 'title': book.title, 'author': book.author, 'description': book.descriptio...
def find_max_simultaneous_events(events): """ Question 14.5: Given a list of intervals representing start and end times of events, find the maximum number of simultaneous events that we can schedule """ transitions = [] simultaneous = 0 max_simultaneous = 0 for event in events: ...
def share_ratio(x, y): """ Given floats :math:`x, y \\in \\mathbb{R}`, return the quantity .. math:: \\frac{x}{x+y}. Parameters ---------- x : `float` y : `float` Returns ------- `float` """ return (x)/(x+y)
def check_uniqueness_in_rows(board: list): """ Check buildings of unique height in each row. Return True if buildings in a row have unique length, False otherwise. >>> check_uniqueness_in_rows(['***21**', '412453*', '423145*',\ '*543215', '*35214*', '*41532*', '*2*1***']) True >>> chec...
def parse_config_list(s): """util to convert X = A,B,C config entry into ['A', 'B', 'C']""" return [x.strip() for x in s.split(',') if x.strip()]
def pstate2str(val): """ Print human readble configuration for Pstate Adapted from ZenStates.py """ if val & (1 << 63): fid = val & 0xff did = (val & 0x3f00) >> 8 vid = (val & 0x3fc000) >> 14 ratio = 25*fid/(12.5 * did) vcore = 1.55 - 0.00625 * vid ret...
def classificationError(p_m1): """ This is defined as E 1 - max_k{p_mk} """ p_m2 = 1 - p_m1 E = 1 - max(p_m1, p_m2) # You could do E=min(p_m1, p_m2) instead return E
def indentParagraph(text, indent): """ Indent some text by a number of spaces :param indent: (int or str) number of spaces to indent the text, or the text to use as the indentation >>> indentParagraph('foo\\nbar', indent=3) ' foo\\n bar' >>> indentParagra...
def transpose(imlist): """ Replacing the x-axis and y-axis of an image in the list of images """ return [ img.T for img in imlist]
def reverse_edge(edge): """Switches u and v in an edge tuple. """ reverse = list(edge) reverse[0] = edge[1] reverse[1] = edge[0] return tuple(reverse)
def lower(text): """<string> -- Convert string to lowercase.""" return text.lower()
def bubble_sort(items): """Sort given items by swapping adjacent items that are out of order, and repeating until all items are in sorted order. Running time: O(n^2) because as the input grows so does both of the loops Memory usage: O(1) because not creating any new space and everything is done in place...
def _invert_value(value, invert=False): """Invert specified value - 1 / value.""" if invert: value **= (-1) return value
def in_region(pos, regions): """Find whether a position is included in a region. Parameters ---------- pos : int DNA base position. regions : list of tuples List of (start, end) position integers. Returns ------- bool True if the position is within an of the reg...
def calc_absent(marks): """ Function which returns the count of absent students. """ absent_count = 0 for mark in marks: if mark == 0: absent_count += 1 return absent_count
def binary_search(elements, target): """.""" mid = len(elements) // 2 if len(elements) == 0: return False if elements[mid] == target: return True if target < elements[mid]: return binary_search(elements[:mid], target) else: return binary_search(elements[mid + 1:],...
def format_assumption(step): """Format a proof assumption.""" pred = step['detail']['predicate'] return 'assumption: {}'.format(pred)
def height_str_to_int(heights): """Change a string of heights in a list of heights while also error checking""" # Max height the reader should read. Anything above this is an error max_height = 100 heights_int = [] for height_str in heights: try: # Convert height value ...
def os_system(cmds, stdout_only=True): """ Executes system command and Get print output from command line :param cmds a list containing command and its arguments """ import subprocess p = subprocess.Popen(cmds, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = p.communicate() ...
def distance1(cell1, cell2): """Return Manhattan distance between cells.""" return abs(cell1[0] - cell2[0]) + abs(cell1[1] - cell2[1])
def darker(rgb,scl=1.5): """ Make the color (rgb-tuple) a tad darker. """ _rgb = tuple([ int((a/255.)**2 * 255) for a in rgb ]) _rgb = tuple([ (a/255.)**scl for a in rgb ]) return _rgb
def isSubsetSum(set, n, sum): """ Determine if set contains subset which has desired sum. :param set: list of values :param n: length of set :param sum: intended sum of values :return: True or False """ if sum == 0: return True if n == 0 and sum != 0: return False ...
def get_filename(filespec): """ Remove OpenVMS drive/folder from a file spec """ separator = ']' if ']' in filespec else ':' return filespec.strip().split(separator)[-1]
def strip_filter(text): """Trim whitespace.""" return text.strip() if text else text
def pick_words(group): """ pick fixed 10 words for experiment group or control group :param group: :return: a list of 10 fixed words """ fixed_words = ["advice", "field", "midnight", "information", "theft", "call", "reach", "abuse", "accept", "catch"] return fixed_words
def is_val_in_range(val, range): """Checks if val falls in range Arguments: val {float} -- value to check range {tuple} -- range of two values Returns: bool -- True if val in range """ return val > range[0] and val < range[1]
def hex_to_rgb(value): """taken from: http://stackoverflow.com/questions/214359/converting-hex-color-to-rgb-and-vice-versa""" value = value.lstrip('#') lv = len(value) return tuple(int(value[i:i + lv // 3], 16) for i in range(0, lv, lv // 3))
def get_class_req_num(required): """Assigned value for required number of classes to find. If not assigned set min_num to 0""" # required = attr_intr["Required"] try: required except NameError: min_num = 1 ## Set max_num to a high number so that any number of instances can ...
def depunct(s): """ Returns s but with everything that is not a letter removed Parameter: s the string to edit Precondition s is a string """ assert type(s) == str, repr(s) + ' is not a string' # get in the habit # Work on small data (BASE CASE) if s == '': return s ...
def sanitize_mapping_file(data, headers): """Clean the strings in the mapping file for use with javascript This function will remove all the ocurrences of characters like ' or ". Parameters ---------- data : list of lists of str the mapping file data headers : list of str the m...
def savings(w,rho): """Compute the basic savings Args: rho (float): discount parameter w (float): wage Returns: (float): basic savings """ return w/(2+rho)
def pool_output_length(input_length, pool_size, stride, pad, ignore_border): """ Compute the output length of a pooling operator along a single dimension. Parameters ---------- input_length : integer The length of the input in the pooling dimension pool_size : integer The le...
def calculate_slice_timings(repetition_time: float, volume_count: int): """ Returns the slice timings in a list. Slices must be interleaved in the + direction. Parameters ---------- repetition_time : float Repetition time of each scan in the functional image. volume_count : int ...
def remove_reflexive_bindings(scope): """Elimina bindings reflexivos de un scope""" # ie: {X = X, X = a, Y = Y} # retona {X = a} return set([eq for eq in scope if eq.var != eq.value])
def parse_direction(item): """Parse direction to tuple with rotation and number of steps.""" return item[0], int(item[1:])
def build_person(firstn, lastn, age=''): """Return a dict of info abt the person.""" person = {'first':firstn, 'last':lastn} if age: person['age'] = age return person
def find_judge(N, trust): """ Inputs: N -> int trust -> List[List[int]] Output: int """ # Your code here # base case if len(trust) < N - 1: return - 1 indegree = [0] * (N + 1) outdegree = [0] * (N + 1) for a, b in trust: outdegree[a] += 1 ...
def top_down_function(N,K,ts): """ Recursive algorithm. args: N :: int length of ts K :: int ts :: list of ints returns: True :: if a subset of ts sums to K False :: otherwise """ # Sum to zero always possible. if K == 0: return Tr...
def parse_arg(arg): """ Parses arguments for convenience. Argument can be a csv list ('a,b,c'), a string, a list, a tuple. Returns a list. """ # handle string input if type(arg) == str: arg = arg.strip() # parse csv as tickers and create children if ',' in...
def do_remove_first(s, remove): """ Removes only the first occurrence of the specified substring from a string. https://github.com/Shopify/liquid/blob/b2feeacbce8e4a718bde9bc9fa9d00e44ab32351/lib/liquid/standardfilters.rb#L218 """ return s.replace(str(remove), '', 1)
def get_learning_rate(args, current, best, counter, learning_rate): """If have not seen accuracy improvement in delay epochs, then divide learning rate by 10 """ if current > best: best = current counter = 0 elif counter > args.delay: learning_rate = learning_rate / args.lr_div c...
def decode_name(nbname): """Return the NetBIOS first-level decoded nbname.""" if len(nbname) != 32: return nbname l = [] for i in range(0, 32, 2): l.append(chr(((ord(nbname[i]) - 0x41) << 4) | ((ord(nbname[i + 1]) - 0x41) & 0xf))) return ''.join(l).split('\x00', ...
def str_to_tile_index(s, index_of_a = 0xe6, index_of_zero = 0xdb, special_cases = None): """ Convert a string to a series of tile indexes. Params: s: the string to convert index_of_a: begining of alphabetical tiles index_of_zero: begining of numerical tiles special_cases: what to if a character is not alpha...
def get_bytecount_from_pid(pid): """ The pid is the calculated value, which could be composed of several bytes when using page extensions. Return the number of bytes the pid utilizes. 3 for n. -1 for unknown """ bytes1 = [(0,127),(256,383),(512,639),(768,895)] bytes2 = [(128,191),(384,447),(640,7...
def ensure_list(indices): """ Return a list, even if indices is a single value :arg indices: A list of indices to act upon :rtype: list """ if type(indices) is not type(list()): # in case of a single value passed indices = [indices] return indices
def megagcd(a, b): """needs in diophantic function""" if b == 0: return a, 1, 0 d, x, y = megagcd(b, a % b) return d, y, x - y * (a // b)
def filter_match_kwargs(kwargs, children=False): """ Filters out kwargs for Match construction :param kwargs: :type kwargs: dict :param children: :type children: Flag to filter children matches :return: A filtered dict :rtype: dict """ kwargs = kwargs.copy() for key in ('pat...
def Saito_fcn_HS_S3(phi): """ Saito-type function: Third-order polynomial on phi (S3) The expression is already reported by Riest et al. Soft Matter (2015) although their actual use with solvent-permeable hard sphere is based on the linear fit with phi (see Saito_fcn_SPHS function). """ return phi*(1. +...
def is_blank(*string: str): """Checks if the string is blank""" return all(map(lambda x: (x is not None and len(x) > 0), string))
def right_replace(string, old, new, count=1): """ Right replaces ``count`` occurrences of ``old`` with ``new`` in ``string``. For example:: right_replace('one_two_two', 'two', 'three') -> 'one_two_three' """ if not string: return string return new.join(string.rsplit(old, count))
def numberToBytes(n): """ Returns the bytes representing the number, without most significant bytes if empty. Starts at the rightmost (least significant) byte and traverse to the left. """ if n == 0: return bytearray([0x00]) result = bytearray() while n > 0: resul...
def bytes_to_string(bytes): """ It generates a string with a proper format to represent bytes. Parameters ---------- bytes : int A quantity of bytes Returns ------- size_str : str The string representing the number of bytes with a proper format """ kilobytes = b...
def make_set(value): """ Takes a value and turns it into a set !!!! This is important because set(string) will parse a string to individual characters vs. adding the string as an element of the set i.e. x = 'setvalue' set(x) = {'t', 'a', 'e', 'v', 'u', 's', 'l'} make_set(x) ...
def video_id(video_id_or_url): """ Returns video id from given video id or url Parameters: ----------- video_id_or_url: str - either a video id or url Returns: -------- the video id """ if 'watch?v=' in video_id_or_url: return video_id_or_url.split('watch?v=')[1] e...
def _DepsOsToLines(deps_os): """Converts |deps_os| dict to list of lines for output.""" if not deps_os: return [] s = ['deps_os = {'] for dep_os, os_deps in sorted(deps_os.iteritems()): s.append(' "%s": {' % dep_os) for name, dep in sorted(os_deps.iteritems()): condition_part = ([' "cond...
def write_header(file, queries, priority, annot_gtf, peaks_bed): """Writes a file header.""" with open(file, "w") as cof: cof.write("#UROPA-Universal RObust Peak Annotator\n") for q in enumerate(queries): cof.write("#Query No {} :".format(q[0])) cof.write("\n#featur...
def long_substr(data): """ https://stackoverflow.com/questions/2892931/\ longest-common-substring-from-more-than-two-strings-python# """ substr = '' if len(data) > 1 and len(data[0]) > 0: for i in range(len(data[0])): for j in range(len(data[0])-i+1): if j...
def lxnor(x, y): """Logical XNOR""" return not (x ^ y)
def to_ipv6_network(addr): """ IPv6 addresses are eight groupings. The first three groupings (48 bits) comprise the network address. """ # Split by :: to identify omitted zeros ipv6_prefix = addr.split('::')[0] # Get the first three groups, or as many as are found + :: found_groups = [] for gr...
def peek(string, n=0): """ Peek into the next `n` characters to be read in string @param string: string you are reading. @param n: number of characters to peek. """ return string[:n]
def printable(ch): """Returns a printable representation of a character.""" val = ord(ch) if val < ord(' ') or val > ord('~'): return '.' return chr(val)
def validate_doubles(password): """ Passwords must contain at least two different, non-overlapping pairs of letters, like aa, bb, or zz """ for i, c in enumerate(password[:-4]): if c == password[i + 1]: for j, d in enumerate(password[i + 2:-1]): j_index = i + 2 + j ...