content
stringlengths
42
6.51k
def jvm_args(args_line): """ converts jvm args to k/v pairs """ args = {} tokens = args_line.split(',') for token in tokens: pairs = token.split('=') if len(pairs) > 1: key = pairs[0].strip() value = "".join(pairs[1:]).strip() if key in args: ...
def subdir(num): """ Return the directory name, given a subject <num>ber, e.g. 101. """ # Create the map, # num -> dir_name num_dir_map = { 101:'101M80351917', 102:'102M80359344', 103:'103M80358136', 104:'104M80368842', 105:'105M80350861', 106:'106M80381623', 108:'1...
def make_iter(*args): """Returns each inputted argument, wrapping in a list if not already iterable. Parameters ---------- *args Arguments to make iterable. Returns ------- iterables `*args` converted to iterables. Examples -------- >>> make_iter(1) [[1]] ...
def selection_sort(lst: list) -> list: """This is a selection sort algorithm implementation Parameters ---------- lst: list The unsorted list Returns ------- list A sorted list in ascending order References ---------- https://en.wikipedia.org/wiki/Selec...
def _format_override(dotted_name): """e.g. foo.profiles.DEFAULT.bar -> foo.profile.bar foo.bar -> foo.bar foo.baz.bar -> foo.baz.bar """ parts = dotted_name.split('.') if len(parts) > 1 and parts[1] == 'profiles': new_parts = [parts[0], 'profile'] + parts[3:] return ".".join(new_parts) else: return dotte...
def ljust_all(strings, fillchar=' '): """ Determine max length of all *strings* and apply ljust to all of them. Example: ljust_all(('a','bb','')) ['a ', 'bb', ' '] """ width = max(map(len, strings)) return [s.ljust(width, fillchar) for s in strings]
def strip_newlines(base): """Strip newlines from a string""" return base.replace("\n", "")
def sort_student_score(name_list, score_list): """Method that takes a list of names and scores and returns a dict with keys as letter grades and a list of names as as values""" score_dict = {} for grade in "A B C D F".split(): score_dict[grade] = [] for name, score in zip(name_list, score_list)...
def ERR_SUMMONDISABLED(sender, receipient, message): """ Error Code 445 """ return "ERROR from <" + sender + ">: " + message
def isregex_expr(expr): """ Returns ``True`` is the given expression value is a regular expression like string with prefix ``re/`` and suffix ``/``, otherwise ``False``. Arguments: expr (mixed): expression value to test. Returns: bool """ if not isinstance(expr, str): ...
def relative_difference_by_min(x, y): """ Calculate relative difference between two numbers. """ return (x - y) / min(x, y)
def dict_to_perl(d): """Convert a dict into a string representing a Perl hash. The hash is meant to be eval'd by Perl code and then used to connect via DBI->connect(). Something like this: my %params = eval(<output of this function>); my $dbh = DBI->connect($params{"cxnstr"}, $params{"user...
def color_to_plane_bits(color, depth): """returns the bits for a given pixel in a list, lowest to highest plane""" result = [0] * depth for bit in range(depth): if color & (1 << bit) != 0: result[bit] = 1 return result
def get_search_models(models): """Generates GET params to specify models.""" params = '' for model in models: params += '&models={}'.format(model) return params
def as_bool(x): """Convert value (possibly a string) into a boolean. """ if x is True or x is False: return x if isinstance(x, int): return bool(x) retval = None if isinstance(x, str): retval = { "yes": True, "no": False, "on": True, ...
def find_key_in_list(key, key_list): """ Look for the right corresponding key in a list. key has to start with an given key from the list and the longest key will be returned. Parameters ---------- key : str Given key. key_list : list of str Valid keys to be checked aga...
def mean(distribution): """Computes the mean of a distribution in the [[point, instances]] syntax """ addition = 0.0 count = 0.0 for point, instances in distribution: addition += point * instances count += instances if count > 0: return addition / count return float(...
def hasBreakpoints(seq): """ returns True if sequnces in not strictly increasing by 1 """ for i in range(1, len(seq)): if (seq[i] != seq[i-1] + 1): return True return False
def get_localhost_host(db_host): """ convert the docker accessible host name to parent machine one host.docker.internal ---> localhost """ converted_host = db_host if db_host == 'host.docker.internal': converted_host = 'localhost' return converted_host
def ord_sum(string: str) -> int: """ Sum the ASCII values of the characters of a passed string. Args: string (str): The string whose ASCII values we are summing. Returns: int: The sum of each letter's ASCII value. """ return sum([ord(c) for c in string])
def build_optional_headers(headers): """ :param headers dict: (required) :returns: str example_dict = { 'md5': '0123456789abcdef0123456789abcdef', 'mtime': '1260000000' } """ # sorted so that we product a consistent string if not headers: return '' keys = sor...
def parse_dict(raw_dict, ignore_keys=[]): """ Parses the values in the dictionary as booleans, ints, and floats as appropriate Parameters ---------- raw_dict : dict Flat dictionary whose values are mainly strings ignore_keys : list, optional Keys in the dictionary to remove ...
def unique_fitnesses(population: list) -> int: """ Calculates the number of unique fitnesses in the population Args: population (list): The list of individual candidate solutions Returns: int: The number of unique fitnesses in the population """ fitnesses = [individual.fitness for ...
def get_minification_delta(source_text, minified_text): """Computes how much the code size has been reduced after minification""" orig_size = len(source_text) mini_size = len(minified_text) delta = orig_size - mini_size return delta
def parse_one_format(ext_and_format_name): """Parse "py:percent" into (".py", "percent"), etc""" if ext_and_format_name.find(':') >= 0: ext, format_name = ext_and_format_name.split(':', 1) else: ext = ext_and_format_name format_name = None if not ext.startswith('.'): ext...
def iroot(a, b): """Function to calculate a-th integer root from b. Example: iroot(2, 4) == 2 Parameters: a: int Root power b: int Number to calculate root from Returns: result: int Integer a-th root of b """ if b < 2: ...
def _escape(s): """PDF escapes are almost like Python ones, but brackets need slashes before them too. Use Python's repr function and chop off the quotes first""" s = repr(s)[1:-1] s = s.replace('(', r'\(') s = s.replace(')', r'\)') return s
def reqlist2string(rlis): """Convertes a list into comma separated string""" st = '' for s in rlis: st += (s + ', ') return st
def duration_string(sec): """Formats a time interval to a readable string""" sec = float(int(sec)) if sec > 60 * 60 * 24: return "%.1f days" % (sec / float(60 * 60 * 24)) if sec > 60 * 60: return "%.1f hours" % (sec / float(60 * 60)) if sec > 60: return "%.1f minutes" % (sec ...
def css_check(css_class): """ Function that checks if a CSS class is something that a command can act on. Generally speaking we do not act upon posts with these two classes. :param css_class: The css_class of the post. :return: True if the post is something than can be worked with, False if it's in...
def get_item(obj, key): """ Template tag to return a given key dynamically from a dictionary or an object """ val = None if obj and type(obj) == dict: val = obj.get(key) or obj.get(str(key)) elif obj and hasattr(obj, key): val = getattr(obj, key) elif obj and hasattr(obj, str...
def keep_matches(list1, list2): """returns a list of the elements that the two lists have in common""" list1.sort() list2.sort() matches = [] i = j = count = 0 lenLst1 = len(list1) lenLst2 = len(list2) while i < lenLst1 and j < lenLst2: if list1[i] < list2[j]: i+=...
def is_oval(obj): """ This is currently the best way of telling if an object is an openscap OVAL definition object. """ try: return obj.object == "oval_definition_model" except: return False
def encode_cooccurrence(x, y, levels=256): """Return the code corresponding to co-occurrence of intensities x and y""" return x*levels + y
def LevenshteinDistance(a, b): """ The Levenshtein distance is a metric for measuring the difference between two sequences. Calculates the Levenshtein distance between a and b. :param a: the first sequence, such as [1, 2, 3, 4] :param b: the second sequence :return: Levenshtein distance """ ...
def rgb_float_to_int(color): """ Turns a float color in 0-1 range into a 0-255 integer range :param color: tuple(float, float, float, float), color in 0-1 range :return: tuple(int, int, int, int), color in 0-255 range """ return tuple([int(round(255 * float(color_channel))) for color_channel in...
def remove_tail_id(ref, hyp): """Assumes that the ID is the final token of the string which is common in Sphinx but not in Kaldi.""" ref_id = ref[-1] hyp_id = hyp[-1] if ref_id != hyp_id: print('Reference and hypothesis IDs do not match! ' 'ref="{}" hyp="{}"\n' 'F...
def adc_to_moisture(raw_adc, arid_value, sodden_value): """Convert a micro:bit 0-1024 ADC value into a moisture percentage using crude linear model.""" a_lower = min(arid_value, sodden_value) a_range = abs(sodden_value - arid_value) inverted = arid_value > sodden_value fraction = (raw_adc -...
def argsort(numbers): """Returns the indices that would sort an array of numbers. The function is similar to NumPy's *argsort* function. Note ---- For a large list of numbers reconsider using NumPy's *argsort* function, since this function might take too long. """ return [i[0] for i in...
def exceeds_maximum_length_ratio( password: str, max_similarity: float, value: str ) -> float: """ Test that value is within a reasonable range of password. The following ratio calculations are based on testing difflib.SequenceMatcher like this: for i in range(0,6): print(10**i, difflib....
def _auc_for_one_positive(positive, negatives): """ Computes the AUC score of one single positive sample agains many negatives. The result is equal to general_roc([positive], negatives)[0], but computes much faster because one can save sorting the negatives. """ count = 0 for negative in negati...
def get_taskToken(activity_task): """ Given a response from polling for activity from SWF via boto, extract the taskToken from the json data, if present """ try: return activity_task["taskToken"] except KeyError: # No taskToken returned return None
def compute_propability(word, label, dict): """ Computes probability q(word | label). :param word: a word/state y_i :param label: a label/state y_i-1 :param dict: dictionary where pre-computed values are stored :return: dict(y_i | y_i-1) """ return dict[label][word] / sum(dict[label].val...
def gcd(u,v): """returns the greatest common divisor of u and v, i.e. GCD(u,v)""" k = 0 # Ergebnis ist immer >=0 if u < 0: u = -u if v < 0: v = -v # 0 hat beliebige Teiler; der groesste Teiler einer von 0 # verschiedenen Zahl ist die Zahl selbst. GCD(0,0) ist undefiniert # bzw. die 0: if u == 0 or v == 0: ...
def GetBigQueryTableID(tag): """Returns the ID of the BigQuery table associated with tag. This ID is appended at the end of the table name. """ # BigQuery table names can contain only alpha numeric characters and # underscores. return ''.join(c for c in tag if c.isalnum() or c == '_')
def hop_not_source(linklist, hop): """ make sure hop is not a source """ for links in linklist: if links['source'] == hop: return False return True
def importName( moduleName, name, default_func=None, verbose=False ): """ At run time, dynamically import 'name' from 'moduleName'. """ if verbose: print("Loading %s from %s." % (name, moduleName)) func = default_func try: print("WARNING: VERY SUSPICIOUS WAY OF IMPORTING") ...
def base26(w): """Convert string into base26 representation where a=0 and z=25.""" val = 0 for ch in w.lower(): next_digit = ord(ch) - ord('a') val = 26*val + next_digit return val
def evaluations_to_columns(evaluation): """Convert the results of :meth:`metrics.ScoringMixIn.evaluate` to a pandas DataFrame-ready format Parameters ---------- evaluation: dict of OrderedDicts The result of consecutive calls to :meth:`metrics.ScoringMixIn.evaluate` for all given dataset types ...
def combine_dicts(d_tracker, d_return): """combines dictionaries""" # grab new unique keys (sites) in d_return ls_new_sites = [x for x in d_tracker.keys() if x not in d_return.keys()] # if new sites are found if ls_new_sites: # iteratively add sites to d_tracker for new_site in ...
def representsInt(s, acceptRoundedFloats=False): """ This function return True if the given param (string or float) represents a int :Example: >>> representsInt(1) True >>> representsInt("1") True >>> representsInt("a") False >>> representsInt...
def combine_items(items, callable): """Combine a list of strings, and then pass them into a provided function. Useful for logging a list of strings as a single command. """ args = " ".join(items) return callable(args)
def nested_get(record: dict, target: str): """ Using dot-notation get the value of a dictionary Example: obj = { "foo": { "bar": 4 } } nested_get(obj, 'foo.bar') # returns 4 nested_get(obj, 'foo.zaz') # returns None """...
def delkey(value, key): """ :param value: dictionary :param key: string - name of element to delete """ value.pop(key) return ""
def _get_metadata_from_row(row): """ Given a row from the manifest, return the field representing metadata. Args: row (dict): column_name:row_value Returns: """ metadata = dict(row) # make sure guid is not part of the metadata if "guid" in metadata: del metadata["guid"...
def rhom(rho, eta): """ Note ---- This becomes 0 if eta = 1 and rho = 1, which leads to trouble when calculating rhom(rho, eta)**-2 """ return (1 + rho**2 - 2*rho*eta)**0.5
def getPPSA1(ChargeSA): """ The calculation of partial negative area It is the sum of the solvent-accessible surface areas of all positively charged atoms. -->PPSA1 """ res=0.0 for i in ChargeSA: if float(i[1])>0: res=res+i[2] return res
def cat(*args): """ concatenate args """ out = "" for arg in args: if not arg: pass elif len(arg) > 0: if len(out) == 0: out = arg else: out = out + " " + arg return out
def get_fext_xtalk_from_list(trlist, reclist, skip_same_index_couples=True): """Get the list of all the Far End XTalk from 2 lists of exctitations. If skip_same_index_couples is true, the tx and rx with same index position will be considered insertion losses and excluded from the list Example: excitation_...
def _mergeEnvironments(currentEnv, otherEnv): """Merges two execution environments. If both environments contain PATH variables, they are also merged using the proper separator. """ resultEnv = dict(currentEnv) for k, v in otherEnv.items(): if k == 'PATH': oldPath =...
def js_paths(context): """Return paths to JS files needed for the Zope 4 ZMI.""" return ( '/++resource++zmi/jquery-3.5.1.min.js', '/++resource++zmi/bootstrap-4.6.0/bootstrap.bundle.min.js', '/++resource++zmi/ace.ajax.org/ace.js', '/++resource++zmi/zmi_base.js', )
def count_ones(N): """ Count number of ones in a binary representation of a given decimal N >>> count_ones(8) 1 >>> count_ones(9) 2 >>> count_ones(7) 3 """ num = 0 while(N>0): if (N & 1) == 1: num += 1 N = N >> 1 return num
def receptor_unbound(pdb_code): """Augment pdb code with receptor partner and unbound binding notation.""" return pdb_code + '_r_u'
def dup_shift(f, a, K): """ Evaluate efficiently Taylor shift ``f(x + a)`` in ``K[x]``. Examples ======== >>> from sympy.polys import ring, ZZ >>> R, x = ring("x", ZZ) >>> R.dup_shift(x**2 - 2*x + 1, ZZ(2)) x**2 + 2*x + 1 """ f, n = list(f), len(f) - 1 for i in range(n, ...
def ocw_parent_folder(prefix): """ Get the S3 parent folder of an OCW course Args: prefix(str): The course prefix Returns: str: The parent folder for the course prefix """ prefix_parts = prefix.split("/") return "/".join(prefix_parts[0:2]) if prefix_parts[0] == "PROD" else ...
def computeTokenTypes(tokenNames): """ Compute a dict that is an inverted index of tokenNames (which maps int token types to names). """ if tokenNames is None: return {} return dict((name, type) for type, name in enumerate(tokenNames))
def parse_sz_compression_options(arguments): """ Function to parse compression options for the SZ compressor Input ----- arguments: list of strings Output ----- compression_method : string="lossy" compression_opts: tuple (backend:string, method:string, parame...
def get_addr_range(addrs, addr): """ Return the range of either functions/blocks/codes with a binary search, O(log N) :param addrs: the list containing a start/end address pair :param addr: the target address range one looks for :return: (start, end) if any (0,0) otherwise """ starts = [star...
def to_f90str(value): """Convert primitive Python types to equivalent Fortran strings""" if type(value) is int: return str(value) elif type(value) is float: return str(value) elif type(value) is bool: return '.{0}.'.format(str(value).lower()) elif type(value) is complex: ...
def get_unnumbered_link_label(numbered_link_label: str) -> str: """Get original link""" return numbered_link_label[:numbered_link_label.rfind(":_")]
def isEmpty(variable): """ Check if a variable is empty. :param date_str: var to check :return: True or False """ empty = False if len(str(variable)) == 0: empty = True return empty
def keepsaccade(i, j, sim, data ): """ Helper function for scanpath simplification. If no simplification can be performed on a particular saccade, this functions stores the original data. :param i: current index :param j: current index ...
def sizeof_fmt(size): """ Get human readable version of file size """ for x in ['bytes', 'KB', 'MB', 'GB', 'TB']: if size < 1024.0: return "%3.1f%s" % (size, x) size /= 1024.0
def linear_session_score(i, length): """Newest elements in sequence => largest weights. Parameters ---------- i : int Element position, i+1 must be less than length. length : int Length of a sequence. Results ------- result : float Session rank betwee...
def miller_rabin(n: int) -> bool: """ primality Test if n < 3,825,123,056,546,413,051, it is enough to test a = 2, 3, 5, 7, 11, 13, 17, 19, and 23. Complexity: O(log^3 n) """ assert(n >= 1) if n == 2: return True if n <= 1 or not n & 1: return False prime...
def parse_qotd(qotd): """ Parse the quote. Arguments: qotd - random quote. """ index = 0 str_len = len(qotd) in_bold = False in_italic = False out = "" while index < str_len: character = qotd[index] if character == '\\': index = index + 1 ...
def axlbool(value): """ convert text to python bool """ if value is None: return None if not value: return False if value.lower() == 'true': return True return False
def _deep_flatten(items): """Returns a list of objects, flattening sublists/subtuples along the way. Example: _deep_flatten([1, (2, 3, (4, 5), [6, 7]), [[[8]]]]) would return the list [1, 2, 3, 4, 5, 6, 7, 8]. Args: items: An iterable. If elements of this iterable are lists or tuples, they will be...
def load_linestyle(i): """ Provide linestyle via index. @param i: index """ linestyles = ["-", ":", "-.", "--"] return linestyles[i % len(linestyles)]
def binary_to_int_rep(rep): """ converts binary representations to integer format by creating a list of the indexes of the zeros in the original representation :param rep: list of binary values, representation in binary :return: representation in integer """ return [i for i in range(len(rep)...
def relu(z): """ Relu activation function. g(z) = max(0, z) """ return z*(z > 0)
def _search_error(col, search_string): """ Check for problems with search """ if not search_string: return "No search string provided." if not col: return "No feature selected to search." return ""
def parse_join_code(join_code): """ takes the join code and makes sure it's at least 6 digits long Args: join_code (int): the number of join codes sent out so far Returns: string: the actual join code """ if join_code < 10: return f"00000{join_code}" elif join_code ...
def padto(msg, length): """Pads 'msg' with zeroes until it's length is divisible by 'length'. If the length of msg is already a multiple of 'length', does nothing.""" L = len(msg) if L % length: msg += '\x00' * (length - L % length) assert len(msg) % length == 0 return msg
def extended_euclidean_algorithm(a, b): """return (g, x, y) such that a*x + b*y = g = gcd(a, b) where a,b>=1""" x0, x1, y0, y1 = 0, 1, 1, 0 while a != 0: q, b, a = b // a, a, b % a y0, y1 = y1, y0 - q * y1 x0, x1 = x1, x0 - q * x1 return b, x0, y0
def input_dic(keys, dic): """Fill the data in the dictionary""" obj_dic = {} for key in keys: if key not in dic.keys(): pass else: obj_dic[key] = dic[key] return obj_dic
def sametype(variable1, variable2): """ Check if 2 variables have the same type :type variable1: variable :param variable1: The first variable to check :type variable2: variable :param variable2: The second variable to check >>> sametype(True, False) True >>> sametype(True, "foo"...
def make_seq_string(seq, container_chars = '[]'): """Returns a string representing the sequence, wrapped in the container_chars (can be '{}', etc). Each element is str(element), but no quotes are used. For example: make_seq_string([ a, b, c ], '{}') -> '{ a, b, c }'. """ string = '%s ' % container...
def update_mean(new_data, old_mean, num_data): """Compute a new mean recursively using the old mean and new measurement From the arithmetic mean computed using the n-1 measurements (M_n-1), we compute the new mean (M_n) adding a new measurement (X_n) with the formula: M_n = M_n-1 + (X_n - M_n-1)/n ...
def add_no_cache_header(res): """Disable caching of any content""" # uncomment followings to enable this feature # res.headers["Cache-Control"] = "no-cache, no-store, must-revalidate" # res.headers["Pragma"] = "no-cache" # res.headers["Expires"] = "0" # res.headers['Cache-Control'] = 'public, ma...
def get_fashion_mnist_labels(labels): """Get text labels for Fashion-MNIST.""" text_labels = ['t-shirt', 'trouser', 'pullover', 'dress', 'coat', 'sandal', 'shirt', 'sneaker', 'bag', 'ankle boot'] return [text_labels[int(i)] for i in labels]
def range_squared(n): """A function range_squared(n) that takes an non-negative integer value n and returns the list [0, 1, 4, 9, 16, 25, ..., (n-1)^2]. If n is zero, the function should return the empty list.""" if n > 0: return [i ** 2 for i in range(n)] # return list(map(lambda x: x *...
def func_args_pq_kwargs(*args, p="p", q="q", **kwargs): """func. Parameters ---------- args: tuple p, q: str kwargs: dict Returns ------- args: tuple p, q: str kwargs: dict """ return None, None, None, None, args, p, q, kwargs
def make_id_friendly(string): """ Returns the string but made into something that can be used as an ID. """ from re import sub return sub(r"[^a-z0-9]", "", string.lower())
def index_startswith_substring(the_list, substring): """Return index of element in the_list that starts with substring, and -1 if substring was not found """ for i, s in enumerate(the_list): if s.startswith(substring): return i return -1
def initial_space_count(s, start=0): """Return number of initial spaces in s.""" i, end = 0, len(s) while start+i < end and s[start+i].isspace(): i += 1 return i
def sqrt(input_x): """ Given integer x, this returns the integer floor(sqrt(x)). :param input_x: :return: """ assert input_x >= 0 i = 1 while i * i <= input_x: i *= 2 intermediate_y = 0 while i > 0: if (intermediate_y + i) ** 2 <= input_x: intermediate...
def solution(N): """ Problem Statement can be found here- https://app.codility.com/demo/results/trainingJNNRF6-VG4/ Codility 100% Idea is count decedent factor in single travers. ie. if 24 is divisible by 4 then it is also divisible by 8 Traverse only up to square root of number ie. in case of ...
def base10(obj): """ Converts some hash into base 10. """ target = int(obj, 16) return target
def getJ1939ProtocolDescription(protocol : int) -> str: """ Returns a description of the protocol selected with protocol arg. Feed the result of RP1210Config.getJ1939FormatsSupported() into this function to get a description of what the format means. Honestly, I don't see anyone ever using thi...