content
stringlengths
42
6.51k
def Capitalize(v): """Capitalise a string. >>> s = Schema(Capitalize) >>> s('hello world') 'Hello world' """ return str(v).capitalize()
def split_list(sequence, nb_splits): """ Split l in n_split. It can return unevenly sized chunks. Parameters: sequence: iterable Iterable object to be split in `nb_splits`. nb_splits: int Number of splits. Returns: iterable `sequence` splits in `nb_splits`. .. c...
def convert_to_none(value): """Attempts to convert the passed in < value > to < None > if it matches any of the following strings: "n/a", "N/A", "none", "None", "unknown" "Unknown" (i.e., a case-insensitive check). If no match is obtained or an exception is encountered the < value > is returned unchanged. ...
def locale_equals_language(locale, lang): """Returns wehther the locale and language are equivalent This is pretty goofy because locale != language, but this can be used for places where we have the locale the user was visiting the site with and a language and determine whether they're "similar" or...
def encrypt_letter(letter, value): """ (str, int) -> str Precondition: len(letter) == 1 and letter.isupper() Returns the letter as an encrypted letter by applying the keystream value. >>> encrypt_letter('F', 10) 'P' >>> encrypt_letter('Z', 19) 'S' """ # Change the letter to a numb...
def construct_userlist(userlist, channel_user_list): """ Creates a userID -> Real Name mapping of all users in the channel given all existing users :param userlist: JSON returned by users.list api call :param channel_user_list: list of members in a specific channel (by ID) """ global...
def BitofWord(tag): """ Test if the user is trying to write to a bit of a word ex. Tag.1 returns True (Tag = DINT) """ s = tag.split('.') if s[len(s)-1].isdigit(): return True else: return False
def sum_5_multiples(t): """Calculate the sum of the multiples of 5""" sum5=0 for i in range(1, t+1): num_to_add=5*i if (num_to_add)%3==0: #avoid adding numbers that are multiples of 3 and 5 twice continue sum5=sum5+num_to_add return sum5
def gamma_CT_fun(x,*p): """ gamma/U0=f(CT), i.e. x=Ct INPUTS: x = CT value p : list of parameters of fitting function NOTE: returns gamma_t/U0! """ return -2*(p[0] * x + p[1] * x**2 + p[2] * x**3 + p[3] * x**4)
def binToChars(data): """ convert binary to a sequence of chars """ return data.decode("utf-8", "backslashreplace")
def parse_games_played(r): """ Used to parse the amount of games played by a team. """ return int(r.get("wedAant", 0))
def _get_prefixed_values(data, prefix): """Collect lines which start with prefix; with trimming""" matches = [] for line in data.splitlines(): line = line.strip() if line.startswith(prefix): match = line[len(prefix):] match = match.strip() matches.append(m...
def naive_block_padding(b: bytes, size: int) -> bytes: """ A naive padding implementation. Given the block size, pad the input buffer with '\x00' bytes, so that the result is a multiple of the specified size. If the buffer is greater than 0, but already a multiple of `size` it's returned unmod...
def dict_union(a, b): """ performs union operation on two dictionaries of sets """ c = {k: a[k].union(b[k]) for k in set(a.keys()).intersection(set(b.keys()))} for k in (set(b.keys()) - set(c.keys())): c[k] = b[k] for k in (set(a.keys()) - set(c.keys())): c[k] = a[k] for k, ...
def _invalidWin32App(pywinerr): """ Determine if a pywintypes.error is telling us that the given process is 'not a valid win32 application', i.e. not a PE format executable. @param pywinerr: a pywintypes.error instance raised by CreateProcess @return: a boolean """ # Let's do this better ...
def get_access_path(key, parts): """ Given a list of format specifiers, returns the final access path (e.g. a.b.c[0][1]). """ path = [] for is_attribute, specifier in parts: if is_attribute: path.append(".{}".format(specifier)) else: path.append("[{!r}]".forma...
def HTMLColorToPILColor(colorstring): """ converts #RRGGBB to PIL-compatible integers""" colorstring = colorstring.strip() while colorstring[0] == '#': colorstring = colorstring[1:] # get bytes in reverse order to deal with PIL quirk colorstring = colorstring[-2:] + colorstring[2:4] + colorstring[:2...
def add_to_dict(param_dict): """ Aggregates extra variables to dictionary Parameters ---------- param_dict: python dictionary dictionary with input parameters and values Returns ---------- param_dict: python dictionary dictionary with old and new values added """ ...
def to_num(c): """ Convert to a class, encoded as number {'low', 'mid', 'high'} => {0, 1, 2} """ if c < -3: return 0 if c < 3: return 1 return 2
def inverse3(v): """ inverse3 """ return (-v[0], -v[1], -v[2])
def _get_in_out_shape(x_shape, y_shape, n_classes, batch_size): """Returns shape for input and output of the data feeder.""" x_shape = list(x_shape[1:]) if len(x_shape) > 1 else [1] input_shape = [batch_size] + x_shape if y_shape is None: return input_shape, None y_shape = list(y_shape[1:]) if len(y_shape...
def get_question_id(question_str): """ Examples -------- >>> get_question_id("q123") 123 """ return int(question_str.lstrip("q"))
def formater (string, props): """ This function does a regular substitution 'str%(dict)' with a little difference. It takes care of the escaped percentage chars, so strings can be replaced an arbitrary number of times.""" s2 = '' n = 0 while n < len(string): if n<len(string)-1 and stri...
def mulStr(s): """ String -> Number """ r = 1 for x in list(s): r *= int(x) return r
def _global_var_name(splittable_dimension, mesh_dimension): """Name for a global variable. Args: splittable_dimension: the name of a splittable dimension (string) mesh_dimension: the name of a mesh dimension (string) Returns: A string, the variable name. """ return "x_({}:{})".format(splittable_...
def __CalculateESF(myElevation): """ Retrieve the ElevationScaleFactor :param _: todo :returns: todo """ #list out elevation and elevation scale factors elevation_list = [0,80,160,240,320,400,480,520,640,720,800] ESF_list = [1,0.9999875,0.999975,0.9999625,0.99995,0.9999375,0.999925...
def laplace_scale(level): """ Level scale for the Laplace kernel. Parameters: ----------- level : int Returns: -------- float """ return 1/(2**level)
def sizeof_fmt(num): """ Returns the human readable version of a file size :param num: :return: """ for item in ['bytes', 'KB', 'MB', 'GB']: if num < 1024.0: return "%3.1f%s" % (num, item) num /= 1024.0 return "%3.1f%s" % (num, 'TB')
def select_heat_requirements(reqs): """Filters dict requirements to only those requirements pertaining to Heat""" return {k: v for k, v in reqs.items() if "heat" in v["docname"].lower()}
def bytes_to_str(byte_count): """pretty print string for bytes""" if byte_count > 1024 * 1024 * 1024: return str(int(byte_count / 1024 / 1024 / 1024)) + "GiB" if byte_count > 1024 * 1024: return str(int(byte_count / 1024 / 1024)) + "MiB" if byte_count > 1024: return str(int(byte_...
def aggregate_log_dict(agg_dict, new_dict) -> dict: """ Aggregate the statistics of a log dict :param agg_dict: aggregation dictionary :param new_dict: dict with new stats :return: new aggregation dict with aggregated """ for k in new_dict: # init new if not present if k not ...
def learning_rate_schedule(epoch): """Learning rate is scheduled to be reduced after 80 and 120 epochs. This function is automatically every epoch as part of callbacks during training. """ if epoch < 80: return 1e-3 if epoch < 120: return 1e-4 return 1e-5
def solve_hcr(q0, g): """Calculate the critical h. For 1D problem, q is theoretically constant everywhere if no mass gain/loss. So the q at the left boundary can be treated as the q everywhere. Args: ----- q0: a scalar; the conservative quantity hu at x = 0 (the left) boundary. g: ...
def _bisect_right( seq, tgt, key_func, lower_search_bound=0, upper_search_bound=None ): """Return the index of the last item in seq such that all e in seq[:index] have key_func(e) <= tgt, and all e in seq[index:] have key_func(e) > tgt. Thus, seq.insert(index, value)...
def bytesTo(bytes: float, to: str = 'm', bsize: int = 1024): """convert bytes to megabytes, etc. sample code: print('mb= ' + str(bytesTo(314575262000000, 'm'))) sample output: mb= 300002347.946 https://gist.github.com/shawnbutts/3906915 """ a = {'k': 1, 'm': ...
def select_pages(user_input, all_pages): """ Takes the range of pages user specified and image URLs of all pages available, returns a `dict` with selected pages only. """ ranges = user_input.replace(" ", "").split(",") page_numbers = [] if "all" in ranges: return all_pages ...
def wagtail_icon(name=None, classname='', title=None): """ Usage: {% wagtail_icon name="cogs" classname="icon--red" title="Settings" %} First load the tags with {% load wagtailui_tags %} """ return { 'name': name, 'classname': classname, 'title': title, }
def check_altsw(altcheck=False): """ Ask for and return alternate software release, if needed. :param altcheck: If we're using an alternate software release. :type altcheck: bool """ if altcheck: altsw = input("RADIO SOFTWARE RELEASE (PRESS ENTER TO GUESS): ") if not altsw: ...
def _format_align(sign, body, spec): """Given an unpadded, non-aligned numeric string 'body' and sign string 'sign', add padding and alignment conforming to the given format specifier dictionary 'spec' (as produced by parse_format_specifier). """ minimumwidth = spec['minimumwidth'] fill = s...
def read(rows): """Reads the list of rows and returns the sudoku dict. The sudoku dict maps an index to a known value. Unknown values are not written. Indices go from 0 to 80. """ sudoku = {} i = 0 for rn, row in enumerate(rows): if rn in (3, 7): continue j = 0 ...
def glance_type_to_ec2_type(image_type): """Converts to a three letter image type. aki, kernel => aki ari, ramdisk => ari anything else => ami """ if image_type == 'kernel': return 'aki' if image_type == 'ramdisk': return 'ari' if image_type not in ['aki', 'ari']: ...
def get_paragraphs(txt): """ Returns the paragraphs list of the given text. Args: txt: the input text string. Returns: list. """ return txt.split(".\n")
def ljust(value, arg): """ Left-aligns the value in a field of a given width. Argument: field size. """ return value.ljust(int(arg))
def grad_refactor_5(a): """ if_test """ if a > 3: return 1 return a
def to_bool(v): """Convert 'y' to True and 'n' to False or raise an error.""" if v == 'y': return True elif v == 'n': return False raise ValueError('Invalid input "{}" (only "y" or "n" are allowed)'. format(v))
def binom(n, k): """Quickly adapted from https://stackoverflow.com/questions/26560726/python-binomial-coefficient""" if k < 0 or k > n: return 0 if k == 0 or k == n: return 1 total_ways = 1 for i in range(min(k, n - k)): total_ways = total_ways * (n - i) // (i + 1) return...
def replacer(svgFile, toReplace, newData): """ Searches through SVG file until it finds a toReplace, once found, replaces it with newData """ for count in range(0,len(svgFile)): found = svgFile[count].find(toReplace) #Check if the current line in the SVG file has the required string if n...
def get_links(title: str) -> str: """ Given a query that can be assumed to be a Wikipedia Article Title, get the JSON for links back. """ baseURL = "https://en.wikipedia.org/w/api.php?action=query&titles=TEMP&prop=links&pllimit=max&format=json" query = title.replace(" ", "%20") return baseURL.re...
def escapeval_to_color(n, maxiters): """ http://www.fractalforums.com/index.php?topic=643.msg3522#msg3522 """ v = float(n) / float(maxiters) n = int(v * 4096.0) r = g = b = 0 if (n == maxiters): pass elif (n < 64): r = n * 2 elif (n < 128): r = (((n - 64...
def moran_mutation_rate_from_theta(popsize, theta): """ Given a value for theta (the population-level dimensionless innovation rate, returns the actual probability of mutation per locus per tick. This is a *per locus* innovation rate, however, so if you are using this in code which randomly selects one...
def _get_stack_values(stack_outputs, vm_name, params): """ Collect the output from Heat Stack Deployment """ result = {} for param in params: out = stack_outputs.get(vm_name + '_' + param) if out: result[param] = out return result
def simulation_timeseries_to_json( scenario_name="", scenario_id="", scenario_timeseries=None, scenario_timestamps="" ): """format the information about several timeseries within a scenario in a specific JSON""" if scenario_timeseries is None: scenario_timeseries = [] return { "scenario_...
def get_data_points(data_dict: dict, only_practiced_items: bool =False): """ Returns a dictionary of totalled values for each header :param data_dict: dict | dictionary of topics and values :return: dict | updates in dictionary data type """ updates_to_add = dict() towards_total_minu...
def fixcase(in_txt): """ Take a string_like_this and return a String Like This """ return ' '.join(p.capitalize() for p in in_txt.split("_"))
def subfield(string, delim, occurrence): """ function to extract specified occurence of subfield from string using specified field delimiter eg select subfield('abc/123/xyz','/',0) returns 'abc' eg select subfield('abc/123/xyz','/',1) returns '123' eg select subfield('abc/123/xyz','/',2) retu...
def find_expired(bucket_items, now): """ If there are no expired items in the bucket returns empty list >>> bucket_items = [('k1', 1), ('k2', 2), ('k3', 3)] >>> find_expired(bucket_items, 0) [] >>> bucket_items [('k1', 1), ('k2', 2), ('k3', 3)] Expired items are returned in the lis...
def match_field_creation(card_num, invoice_id): """ Returns a field for matching between Fiserv and Smartfolio It is defined as a concatenation of the Credit Card number and the invoice ID :return: String """ card_num = card_num.replace("*", "x") return card_num + "-" + str(invoice_id)
def stocking_event_dict(db): """return a dictionary representing a complete, valid upload event. This dictionary is used directly to represent a stocking event, or is modified to verify that invalid data is handled appropriately. """ event_dict = { "stock_id": None, "lake": "HU", ...
def last(seq): """ Returns the last element in the sequence `seq`. """ return seq[-1]
def get_goal_difference_coefficient(score_team_1, score_team_2): """Get goal difference coefficient corresponding to a match score.""" diff = abs(score_team_1 - score_team_2) if diff < 2: return 1 elif diff == 2: return 1.5 elif diff == 3: return 1.75 else: return...
def maxHeightTry3(d1, d2, d3): """ A method that calculates largest possible tower height of given boxes. Problem description: https://practice.geeksforgeeks.org/problems/box-stacking/1 time complexity: O(n^2) space complexity: O(n) Parameters ---------- d1 : int[] a lis...
def standardize_subsequence(tokenized_subsequence): """ @input : tokenized sequence @output: standardized tokenized sequence: Sequences that are uniform in length """ standardized_subsequence = [] cutoff = 16 # this value was determined from analysis of our tokenized_subsequence # I need t...
def url_file_name(url): """returns the url's file name""" return url[url.rfind('/') + 1:]
def get_parameter(input_dict, param): """ This function will get the parameter from input_dict """ if param in input_dict.keys(): return input_dict[param]
def binary_search(arr, target): """ arr must be sorted, O(nlogn) given an array and a target value, return the index returns -1 if the target is not present Best case: O(1) Worst case: O(log n) Worst case space: O(1) """ low = 0 high = len(arr) - 1 while low <= high: ...
def push(l, item): """ Inverse of pop. """ l.insert(0, item) return l
def rewrite_query_for_paging(directory: str, query: str, target_page: int) -> str: """Change query to generate different page.""" return f'/index/{directory}/search?q=' + query + f'&page={target_page}'
def versions_match(version_a, version_b, precision=2): """ Check if semantic versions match to precision (default 2). Examples -------- >>> versions_match('1.0.0', '1.2.3', precision=1) True >>> versions_match('1.2.0', '1.2.3', precision=2) True >>> versions_match('1.2.3', '1.2.3', ...
def get_ternary_dict(mode="bin"): """Returns map from floating values to bit encoding.""" if mode == "bin": return {-1.0: "11", 0.0: "00", 1.0: "01"} else: return {-1.0: "-1", 0.0: "0", 1.0: "1"}
def hello(friend_name): """ Says hello world param[0] = a String. Ignore for now. @return = a String containing a message """ return "Hello, {}!".format(friend_name)
def regularize_filename(f): """ regularize filename so that it's valid on windows """ invalids = r'< > : " / \ | ? *'.split(' ') # invalids = r'<>:"/\\\|\?\*' out = str(f) for i in invalids: out = out.replace(i, '_') return out
def parse_cls(txt_path): """ parse class file to cls2idx/idx2cls dict. """ txt_path = str(txt_path) if not txt_path: return None else: with open(txt_path, 'r') as f: c = [x.strip('\n').strip() for x in f.readlines()] return {_c: str(idx) for idx, _c in enumerate(c)}, ...
def str_cmp(s1, s2): """ Compute the Hamming distance between two strings of the same length. """ count = 0 for i in range(len(s1)): if s1[i] != s2[i]: count += 1 return count
def is_associate_or_consultant_to_pipeline(user, pipeline): """Check if a user is an assocaite or consulant of a pipeline record. """ # if user no employee assigned, then not allowed employee = getattr(user, 'as_employee', None) if not employee: return False associate_id = pipeline....
def hey(sentence): """Return bob's answer on sentence.""" sentence = sentence.strip() if sentence.isupper(): return "Whoa, chill out!" elif not sentence: return "Fine. Be that way!" elif sentence.endswith("?"): return "Sure." else: return "Whatever."
def bindings_friendly_constraint(constraint): """Convert the constraint to format that can be used with python bindings""" if constraint is None: return True return constraint
def lexical_diversity(unique_wc, total_wc): """return the proportion of unique words of the total number of words used""" ld = unique_wc / total_wc return ld
def extract_value_by_field(obj, key): """Pull all values of specified key from nested JSON.""" arr = [] def extract(obj, arr, key): """Recursively search for values of key in JSON tree.""" if isinstance(obj, dict): for k, v in obj.items(): if isinstance(v, (dict,...
def concatinate(one_list, other_list): """RETURNS: The 'one_list' extended with 'other_list' in case that 'other_list' is not None. Both lists remain unchanged during the operation. """ if other_list is not None: return one_list + other_list else: return one...
def safe_for_mongo(items): """ Returns a dict which has all keys made safe for insertion into MongoDB. This primarily means fields with a key starting with '$' are replaced with 'F$' """ d = {} for k, v in items.items(): if k.startswith('$') or k == '_id': k = "F"+k d[k] = v ...
def INVALID_IDENTIFIER(identifier): """Error message for invalid identifier.""" return "invalid identifier '{}'".format(identifier)
def convert_time(time_minutes): """ Convert time expressed in (float) minutes into (float) seconds. :param float time_minutes: Time expressed in minutes. :return: Time expressed in seconds. :rtype: float """ time_seconds = time_minutes * 60 return time_seconds
def GetChromOrder(sample_blocks): """ Get a list of chroms in sorted order Parameters ---------- sample_blocks : list of [hap_blocks] each hap_block is a dictionary with keys 'pop', 'chrom', 'start', 'end' Returns ------- chroms : list of int list of chromsomes in s...
def get_ngrams( s, n): """ Returns a list with the possible concatenation of words with a size of n """ min_n = 2*n - 1 s_lw = s.lower() tokens_list = [token for token in s_lw.split(" ") if token.strip() != ""] ngrams = zip(*[tokens_list[i:] for i in range(n)]) ngrams = [ gram for gram in ngrams if len(''.join(g...
def torr_to_pascal(torr): """Convert Torr to Pascal.""" return torr * 101325.0 / 760.0
def prepare_ladder_var(s): """Fonction qui supprime les caracteres ASCII non valides""" o = "".join(i for i in s if (ord(i)<123) and ord(i)> 47) return o
def _transform_select_string(select_string, logfiles): """This function takes a string and a list of logfiles and returns a list of strings. Positional Arguments: selected_string -- a string that should contain sources, trailed by a ',' logfiles -- a list logfile objects Returns: a list of strings, representing...
def getSection(section, iraf_format=True): """Given an input string for a section in an image, it will return the input as a list. section: An input string given a section in the image Set to None to return the whole image iraf_format: It will invert the x and y values """ #return None...
def create_db_strs(txt_tuple_iter): """ From an iterable containing DB info for records in DB or 'not in DB' when no records were found, return info formatted as string. :param txt_tuple_iter: an iterable of tuples where the 0 element of the tuple is the gene/name and element...
def corresponding_lists(x, y): """Returns True is both lists x and y have one to one mapping e.g: x = [12, 4, 12, 3] y = [44, 6, 44, 9] corresponding_lists(x, y) # True """ unique_mapping_pairs = set(zip(x, y)) unique_elements = set(y) return len(unique_ma...
def reaction_value(rxn_dct): """ reaction value """ return rxn_dct['Value']
def _quote_embedded_quotes(text): """ Replace any embedded quotes with two quotes. :param text: the text to quote :return: the quoted text """ result = text if '\'' in text: result = result.replace('\'', '\'\'') if '"' in text: result = result.replace('"', '""') ret...
def sse_pack(d): """ Format a map with Server-Sent-Event-meaningful keys into a string for transport. Happily borrowed from: http://taoofmac.com/space/blog/2014/11/16/1940 For reading on web usage: http://www.html5rocks.com/en/tutorials/eventsource/basics For reading on the format: https://...
def extend_list_in_dict(dictionary, key, *args): """ Add a value to a list inside a dictionary, automatically creates list. """ assert isinstance(dictionary, dict) if key in dictionary: assert isinstance(dictionary[key], list) else: dictionary[key] = [] dictionary[key].extend(args) ...
def reverse_bits(bits): """Reverse bits.""" bit_to_reverse = { '1': '0', '0': '1' } return ''.join( bit_to_reverse[bit] for bit in bits )
def feline_flips(start, goal, limit): """A diff function for autocorrect that determines how many letters in START need to be substituted to create GOAL, then adds the difference in their lengths and returns the result. Arguments: start: a starting word goal: a string representing a des...
def compare_keywords(new_keywords, old_keywords): """Compares two lists of keywords, and returns True if they are the same. Args: new_keywords: first list of keywords old_keywords: second list of keywords Returns: True if the two lists contain the same keywords, ignoring trailing ...
def not_the_same(u1, u2): """Returns whether the users share the same id :u1: User to compare :u2: User to compare :returns: Bool """ return u1["id"] != u2["id"]
def sieve(n: int = 100): """ Prime Sieve: Creates a sieve that can be used to generate prime numbers up to and including 'n'. If 'n' is prime, it will indicated as such by this sieve.""" n += 1 # Create a sequence of boolean values whose index equals the number being checked for primality. If the element at index...
def binary(s): """return true if a string is binary data""" return bool(s and b'\0' in s)