content
stringlengths
42
6.51k
def genres_separate(genre_ids): """ Each genre represented by a three-digit number, and there are songs have more than one genres. We want to separate them. Input: column"genre_ids" of song.csv file. Output: devided all possible categories existed for each of the song. return a diction...
def linearRange(start, stop, step): """Make a list of allowed parameter values.""" pval = start plist = [pval] while pval < stop: pval = pval + step plist.append(pval) return plist
def status2str(num): """ Return YubiHSM response status code as string. """ known = {0x80: 'YSM_STATUS_OK', 0x81: 'YSM_KEY_HANDLE_INVALID', 0x82: 'YSM_AEAD_INVALID', 0x83: 'YSM_OTP_INVALID', 0x84: 'YSM_OTP_REPLAY', 0x85: 'YSM_ID_DUPLICATE', ...
def tiers_for_dev(dev): """ Returns a tuple of tiers for a given device in ascending order by length. :returns: tuple of tiers """ t1 = dev['region'] t2 = dev['zone'] t3 = "{ip}:{port}".format(ip=dev.get('ip'), port=dev.get('port')) t4 = dev['id'] return ((t1,), (t1...
def _element_to_string(x): """element to a string within a list.""" if x is Ellipsis: return "..." if isinstance(x, str): return "'" + x + "'" return str(x)
def document_uris_from_highwire_pdf(highwire_dict, claimant): """ Return PDF document URI dicts for the given 'highwire' document metadata. Process a document.highwire dict that the client submitted as part of an annotation create or update request and return document URI dicts for all of the PDF d...
def coords(coord_string): """ Match a coordinate string (eg A7) to a gv.CHESSBOARD list index. Must check file string matches a regex in invalid input choices """ if len(coord_string) == 2: file_ = ord(coord_string[0].lower()) - 97 rank = int(coord_string[1]) return f...
def partition(test, sequence): """Split `sequence` into 2 lists: (positive,negative), according to the bool value of test(x), order preserved. `test` is either a 1-arg function; or None, which is equivalent to test=bool. `test` is called only ONCE for each element of `sequence`. """ pos = [] ...
def binary_superposition_mop(r, dic_mop, ar_1, ar_2, mop): """substitution for unary multioperations. """ rez = [0 for _ in range(r ** 2)] for i, (x, y) in enumerate(zip(ar_1, ar_2)): if x != 0 and y != 0: for a in dic_mop[x]: for b in dic_mop[y]: ...
def modable(n, v): """If n can be modulo by v""" if n % v: return True else: return False
def first_values(query_parameters): """ Select the first values from a dictionary of query parameters Query strings support multiple values for one key. This function takes a dictionary of lists and returns a dictionary of strings, where the string is the first value in each list. """ return {...
def is_same_files(files1, files2): """ test if two collection of files are equivalent """ files1_resolved = [f.resolve() for f in files1] files2_resolved = [f.resolve() for f in files2] return files1_resolved == files2_resolved
def sensitivity_adj(a,b): """ Tries to remove the issue that smaller complexes get biased towards high scores by subtracting the base case where just a single member overlaps. """ return (len(set.intersection(a,b))-1)/len(a)
def get_commit_type(commit_message): """Return new or fix or None""" commit_message = commit_message.lower() if commit_message.startswith('add'): return 'new' elif commit_message.startswith('new '): return 'new' elif '[new]' in commit_message: return 'new' elif commit_mes...
def floatToSize(val, resolution=0): """ string floatToSize(val, resolution=0) formats and decorates <val>. <resolution> controls the decimal point. """ if not val: return "0" unit="" orgVal = float(val) val = orgVal / 1024. if val < 2048: unit="KiB" else: val /= 1024. if val < 15...
def set_ad_blocking_enabled(enabled: bool) -> dict: """Enable Chrome's experimental ad filter on all sites. Parameters ---------- enabled: bool Whether to block ads. **Experimental** """ return {"method": "Page.setAdBlockingEnabled", "params": {"enabled": enabled}}
def class_(obj): """Return a class from an object Often in itk, the __class__ is not what the user is expecting. class_() should do a better job """ import inspect if inspect.isclass(obj): # obj is already a class ! return obj else: return obj.__class__
def get_arguments(args, training_memory): """ Argument parser :param args: dict of all the agent arguments with key and value as string :param training_memory: memory to be used for training agent if any :return: a dict with at least the same keys and values parsed into objects """ for arg_n...
def get_closure_lines(lines, start_line_number): """ splite closure between '{' '}' :param lines: content :param start_line_number: should recognize begein this line :return: Null """ bracket_count = 0; for p_line in range(start_line_number, len(lines)): line = lines[p_line] ...
def count(arrays, cn): """ Used in conjuction with `get_vals`. Counts the proportions of all_wt, all_mut, or mixed arrays in a given set of `data`, up to a copy number of `cn`. """ all_wt, all_mut, mixed = 0, 0, 0 for array in arrays: if len(array) != cn: continue # homo...
def format_indexes_to_sql(ctypes, ColumnsIndexs): """ in: ["Col1", "Col2"] out: INDEX Col1, INDEX Col2 """ sqls = [] for col in ColumnsIndexs: ctype = ctypes[col] if ctype == "TEXT": key_params = "(255)" else: key_params = "" sqls.appen...
def create_content_dict(file_paths): """Returns a dict of (txt) files, where each file contains all text in the file. Args: file_paths: Output of the method above Returns: raw_content_dict: dict of files as key. Each file contains one string containing all text in the file. ...
def ps_bad_mock(url, request): """ Mock for PTCRB lookup, worst case. """ thebody = "<table></table><table><td>CER-59665-001 - Rev2-x05-05</td><td>OS Version: 10.3.2.698 Radio Version: 10.3.2.699 SW Release Version: 10.3.2.700 OS Version: 10.3.2.698 Radio Version: 10.3.2.699 SW Release Version: 10.3.2.7...
def generate_ordered_sequences(waypoint_lists): """ Given an ordered list of lists of possible choices, generate all possible ordered sequences. """ sequences = [] if len(waypoint_lists) == 0: return [] if len(waypoint_lists) > 1: for node in waypoint_lists[0]: for child in generate_ordered_sequences(wayp...
def get_cache_key(tag_id): """Returns a cache key based on a tag id""" return 'lazy_tags_{0}'.format(tag_id)
def bubble_sort(lst): """Sorts a given list using bubble sort algorithm pre: lst is a list of elements that can be ordered post: returns new_lst with elements of lst sorted in increasing order """ lst_size = len(lst) for i in range(lst_size - 1): for j in range(lst_s...
def group_by(object_list, key_function): """ Return dictionary of objects grouped by keys returned by `key_function` for each element in `object_list`. `object_list` does not need to be sorted. >>> group_by([1, 2, 3, 4, 5], lambda x: x % 2) {0: [2, 4], 1: [1, 3, 5]} """ groups = dict()...
def ensemble_prediction_voting(predictions): """ :param predictions: a list containing the predictions of all the classifiers :type predictions: list :return: a value representing if a disruptive situation has been detected or not :rtype: int """ count_ones = 0 count_zeros = 0 for p...
def find_num(s): """ find all numbers """ if not s: return 1 elif len(s) == 1: return 1 else: prefix = int(s[:2]) if prefix <= 26: # 2 char return find_num(s[2:]) + find_num(s[1:]) else: # 1 char return find_num(s[1:])
def obfuscateShortcut(shortcut): """ Necessary to prevent wxPython from interpreting e.g. CTRL+LEFT in a menu item as being a shortcut. I haven't found a better way. Unused at the moment. """ return u"".join([u"\u200B" + c for c in shortcut])
def format_us_zipcode(zipcode): """NiH US postcodes have wildly inconsistent formatting, leading to geocoding errors. If the postcode if greater than 5 chars, it should be in the format XXXXX-XXXX, or XXXXX, even if the first 5 chars require zero-padding.""" ndigits = len(zipcode) # Only apply t...
def TrimBytes(byte_string): """Trim leading zero bytes.""" trimmed = byte_string.lstrip(chr(0)) if trimmed == "": # was a string of all zero byte_string return chr(0) else: return trimmed
def ninjaenc(s): """ Encodes string s for use in ninja files. """ return s.replace('$', '$$')
def string_score(strang: str) -> int: """Sum of letter values where a==1 and z == 26 :param strang: string to be scored :type strang: str :returns: -> score of the string :rtype: int .. doctest:: python >>> string_score('me') 18 >>> string_score('poooood') 95 ...
def _eval(lstr,locals) : """ Evaluate parts of the string. Normal parts ("S") are not modified. Expression parts ("E") are evaluated (using eval). """ l=[] for t,s in lstr : if t=="S" : l.append(s) if t=="E" : l.append(str(eval(s,None,locals))) return l
def pairs(itemSet, length): """Join a set with itself and returns the n-element itemsets""" return set([i.union(j) for i in itemSet for j in itemSet if len(i.union(j)) == length])
def merge(nums1, nums2): """ Merge two given sorted arrays by merge sort :param nums1: first array :type nums1: list[int] :param nums2: second array :type nums2: list[int] :return: merged array :rtype: list[int] """ result = [] i = j = 0 while i < len(nums1) and j < len(...
def len_route(current_route): """ Calculate the length of this route as when it is translated to ascii commands. current_route: tuples with the current route. [('L', 8),('R', 10),('L', 9) -->] will be translated to L,8,R,10,L,9 (comma's also count) total_length = length each direction + length eac...
def populate_providers_dict(provider_lst: list, read_func): """ Pass in lists of lists [provider,file,cost]. Reads file and populates list of channels. Returns dictionary with provider as key and list [channel list, cost] as value """ dictionary = {} for row in provider_lst: channels = read_fun...
def c_to_f(c): """given a temperature in C, convert to F""" return 9/5.0*c+32
def tiensleutels(dict): """Tien sleutels van een dictionary.""" lijst = list(dict) return(lijst[0:9])
def factorial(n : int) -> int: """ Returns the product of all the numbers in range(1,n)\n ** Uses the built in functool's module lru_cache decorator """ if n in (1,0): return 1 return n * factorial(n-1)
def prepare_id(id_): """ if id_ is string uuid, return as is, if list, format as comma separated list. """ if isinstance(id_, list): return ','.join(id_) elif isinstance(id_, str): return id_ else: raise ValueError(f'Incorrect ID type: {type(id_)}')
def RGB2int(r: int, g: int, b: int ) -> int: """Pack byte r, g and b color value components to an int representation for a specific color Args: r, g, b: color byte values Returns: int color val """ return b + (g << 8) +...
def sequential_search_word(list1, word): """ Carry out a sequential search of the given sorted list for a given word Parameters ---------- list1: input list, sorted word: the word to be searched Returns ------- True/False """ for i in range(len(list1)): if list...
def twos_complement_8bit(b: int) -> int: """Interprets b like a signed 8-bit integer, possibly changing its sign. For instance, twos_complement_8bit(204) returns -52.""" if b >= 256: raise ValueError("b must fit inside 8 bits") if b & (1 << 7): # Negative number, calculate its value using two's-complem...
def tweet_id_from_url(tweet_url: str) -> int: """Obtain tweet id from environment (from URL), e.g. .../1384130447999787017?s=20 -> 1384130447999787017.""" return int(tweet_url.split("/")[-1].split("?")[0]) if tweet_url and isinstance(tweet_url, str) else 0
def breaklines(s, maxcol=80, after='', before='', strip=True): """ Break lines in a string. Parameters ---------- s : str The string. maxcol : int The maximum number of columns per line. It is not enforced when it is not possible to break the line. Default 80. af...
def histogram(letters): """ Creates a frequency histogram of the given letters Input: letters -- word or scrambled letters Output: dictionary mapping from letters to the # of occurences of that letter """ d = dict() for letter in letters: if letter in d: d[letter] += 1 ...
def get_info(post: str): """ Get ino about year, month, day and title of the post """ parts = post.split("-") return { "year": parts[0], "month": parts[1], "day": parts[2], "title": "-".join(parts[3:]), }
def _unflatten_dict(flat_dict, prefixes): """Returns a dict of dicts if any prefixes match keys in the flat dict. The function handles the case where the prefix may not be a dict. Args: flat_dict: A dict without any nesting. prefixes: A list of strings which may have been dicts in the original s...
def power_eaton(v_ratio, n): """ Notes ----- .. math:: \\frac{\\sigma}{{\\sigma}_{n}}= \\left(\\frac{V}{V_{n}}\\right)^{n} """ return (v_ratio)**n
def has_updated(geo_code): """ Check if a muni has beein updated """ bad_list = ['KZN263', 'DC29', 'MP307', 'MP312', 'NC453'] if geo_code in bad_list: return True return False
def analysis_nindex(analysis): """ Returns a dictionary of namespace definition by name. 'nindex' stands for 'Namespace index'. """ return analysis.get("nindex", {})
def format_path(path, modules_only): """ Formats Rust paths. :param path: A Rust path delimited by `::` :param modules_only: Whether to cut off the last component of the path :return: """ if modules_only: path = path.split('::') if len(path[-1]) == 0 or path[-1][0].isupper():...
def hex_to_rgb(col): """Extracts the RGB values as integers (from 0 to 1000) from a hex color string (#rrggbb). """ mul = 1000 / 255 return tuple(round(int(col.lstrip('#')[i:i + 2], 16) * mul) for i in (0, 2, 4))
def move_polygon(polygon_coords=None, move_coords=None, limit_x=None, limit_y=None): """ update coordinate pairs in a list by the specified coordinate pair that represents distance :param polygon_coords: a list of coordinate pairs :param move_coords: a coordinate pair that holds offset values for ...
def sortbyMatch(score): """Sort the result by number of matches in a descending order Args: score: A dictionary of microorganisms and match numbers obtained by above function Return A sorted list of key-value pairs """ return sorted(score.items(), key=lambda x: x[1], rever...
def c_measure_lag(client): """ Special dummyrunner command, injected in c_login. It measures response time. Including this in the ACTION tuple will give more dummyrunner output about just how fast commands are being processed. The dummyrunner will treat this special and inject the {timestamp} ...
def paragraph(text): """Paragraph. Args: text (str): text to make into a paragraph. Returns: str: paragraph text. """ return text + '\r\n'
def curve(t): """ target curve for the Train during the sample fragment :param t: time point :return: target velocity at t point """ if 100 > t >= 0: velocity = (0.8 * (t / 20) ** 2) elif 200 > t >= 100: velocity = 40 - 0.8 * (t / 20 - 10) ** 2 elif 400 > t >= 2...
def get_dv_mission(mission): """Mission delta-v [units: meter second**-1]""" if mission == 'GTO': return 12e3 # GTO elif mission == 'LEO': return 9.5e3 # LEO else: raise ValueError()
def step_back_while(cur_index, condition): """Helper function. Decreases index from cur while condition is satisfied.""" while cur_index >= 0 and condition(cur_index): cur_index -= 1 return cur_index
def gen_feat_val_list(features, values): """ Generates feature value lists sorted in descending value. Args: features: A list of feature names. values: A list of values. Returns: A sorted list of feature-value tuples. """ sorted_feat_val_list = sorted( zip(features,...
def key_lengths(words): """Return a dictionary whose keys are numbers indicating word length. Their values will be a list of all words whose length is equal to that key. words: dictionary of words """ word_length = dict() # For each word, add it to the appropriate entry (its length) # in wor...
def shift(s, n=1): """Rightshift string n places, with wrap around""" return s[-n:] + s[:-n]
def safemin(data, default=0): """ Return mininum of array with default value for empty array Args: data (array or list): data to return the maximum default (obj): default value Returns: object: minimum value in the array or the default value """ if isinstance(data, list): ...
def parse(string): """ This function parses the encoded string for the decoding phase. This is especially userful when a character shows up more than nine times in a row. INPUT: An Encoded String OUTPUT: A List of List // Parsed Encoded String """ if not string or len(string) == 1: ...
def convert_dict_or(obj, name, converter, default=None): """Just a shorthand to return default on getting smthng from dictionary.""" try: result = converter(obj[name]) except Exception: return default if result <= 0: return default return result
def factorial(number): """ function to compute the factorial of a number :param number: integer greater than zero :return: factorial of the input # DOCTEST examples #>>> 0 1 #>>> 6 720 """ int(number) if number < 0: raise ValueError("Factorial of numbers less tha...
def one_or_more(pattern, greedy=True): """ one or more repeats of a pattern :param pattern: an `re` pattern :type pattern: str :param greedy: match as much as possible? :type greedy: bool :rtype: str """ return (r'(?:{:s})+'.format(pattern) if greedy else r'(?:{:s})+?'.form...
def _get_start_stop_blocks_for_trial( i_trial_start, i_trial_stop, input_time_length, n_preds_per_input ): """ Compute start stop block inds for one trial Parameters ---------- i_trial_start: int Index of first sample to predict(!). i_trial_stops: 1daray/list of int Index o...
def uppercase_initial(string): """ Return a capitalized string. :param string: Input string :type string: str :return: Capitalized input string :rtype: str >>> uppercase_initial("disableApiTermination") "DisableApiTermination" """ capital = string[0].upper() return capi...
def get_indexed(data, index): """Index a list""" indexed_data = {} for element in data: indexed_data[element[index]] = element return indexed_data
def format_sec_to_dhm(sec): """Format seconds to days, hours, minutes. Args: sec: float or int Number of seconds in a period of time. Returns: str Period of time represented as a string on the form ``0d\:00h\:00m``. """ rem_int, s_int = divmod(int(sec), 60) rem_int, m_int,...
def test_points(aspect_ratio, elongation, triangularity): """Compute the coordinates of inner and outer equatorial points and high point based on plasma geometrical parameters. Args: aspect_ratio (float): minor radius / major radius elongation (float): plasma elongation triangularit...
def contiguous(_input, val): """ find contiguous range that sum val """ for idx1, n1 in enumerate(_input): #if n1 == val: # print('blah') # continue count = n1 for idx2, n2 in enumerate(_input[idx1:]): if n1 == n2: continue ...
def mean(a): """ Return the average of the elements of array a. """ return sum(a) / float(len(a))
def integer_power(x, n, one=1): """Compute :math:`x^n` using only multiplications. See also the `C2 wiki <http://c2.com/cgi/wiki?IntegerPowerAlgorithm>`_. """ assert isinstance(n, int) if n < 0: raise RuntimeError("the integer power algorithm does not " "work for negative ...
def extract_value_from_file(f, key, file_type='.dat'): """ @param file_type: @param f: @param key: @return: """ proceed = f.split('_') for i, k in enumerate(proceed): if key in k: v = proceed[i + 1] if file_type in v: return v[:-len(file_ty...
def combine_all_sets(sets_a, sets_b): """ Combines two nested lists of node or element sets into the minimum ammount of set combinations. Parameters ---------- sets_a : list First nested list containing lists of element or node keys. sets_b : list Second nested list contai...
def modify(args, f_storage, name): """ args[0] ... dir to be placed at args[1] ... addr to flip """ outdir = args[0] addr = int(args[1], 16) if addr > len(f_storage): return 1 for index in range(0, 8): out = outdir + name + '_' + str(hex(addr)) + '_' + str(index)...
def duration_convert(duration: int): """ Converts duration into readable formats. """ minutes = duration // 60 seconds = duration % 60 hours = minutes // 60 minutes %= 60 return f"{hours:02d}:{minutes:02d}:{seconds:02d}"
def _knockout_index(length, knockout): """Convenience function that returns list(range(length)), with knockout removed.""" return list(range(0,knockout)) + list(range(knockout+1, length))
def find_heuristic_position(child_partition): """ This function finds the starting position of different heuristics in a combined game payoff matrix. :param child_partition: :return: """ position = {} i = 0 for method in child_partition: position[method] = (i, i+child_partition[m...
def call(fn, args=(), kwargs={}): """call fn with given args and kwargs. This is used to represent Apply.__call__ """ return fn(*args, **kwargs)
def normalize(string: str) -> str: """[removes spaces and stuff in string] Args: string (str): [any string] Returns: str: [string without spaces or -_] """ string = string.replace(' ', '') string = string.replace('-', '') string = string.replace('_', '') ...
def bestName(inRow): """ helper function for annotate_best_CDS given a row with 'Label' and 'Locus tag', choose the best annotation choose 'Label' if it's present otherwise choose 'Locus tag' return a string with the best name """ if inRow['Label'] == '': result = inRow['Locus T...
def parse_cmd(cmd): """Validates command.""" cmd_arr = cmd.split() # Blank Space if len(cmd_arr) == 0: return 'blank' # Clear if cmd_arr[0] == 'clear': return 'clear' # Help if cmd_arr[0] == 'help': return 'help' # Valid Commands if cmd_arr[0] != 'exit...
def structural_parameters(keys, columns): """ Gets the structural parameters in a specific order (if catalog is generated by the method in tbridge.binning) """ mags = columns[keys.index("MAGS")] r50s = columns[keys.index("R50S")] ns = columns[keys.index("NS")] ellips = columns[keys.index("EL...
def get_active_layer(layer_keys_pressed, layer_count): """ Class representing a keyboard procesing loop.. """ tmp = 0 if len(layer_keys_pressed) > 0: for layer_id in layer_keys_pressed: if layer_id > tmp: # use highest layer number tmp = layer_id if tmp >= la...
def remove_non_ascii(row): """ REMOVE NON ASCII CHARACTERS """ cleaned = "" for word in row["description"]: if word.isascii(): cleaned += word return cleaned
def get_fiberobj_lst(string, delimiter=';'): """Split the object names for multiple fibers. Args: string (str): Input object string. delimiter (str): Delimiter of different fibers. Returns: list: a list consist of (ifiber, objname), where **ifiber** is an integer, and **...
def path_name_to_name(path_name): """ :param path_name: :return: """ return path_name.replace("\\\\", "\\") \ .replace(r"\.", ".", ) \ .replace(r"\$", "$") \ .replace(r"\|", "|") \ .replace(r"\[", "[") \ ...
def max(a,b): """Return the maximum of two values""" if (a>b): return a else: return b
def ToCacheKey(path): """Convert a list of items to a string suitable as a cache key. Args: path: A list; elements can be strings, objects with a __name__, or anything that can be converted to a string with str(). Returns: A string serialization of the key. The items of the list are joined with ...
def quote(token): """ :param token: string token :return: properly-quoted string token """ if ' ' in token or '"' in token: return '"' + token.replace('"', '\\"') + '"' return token
def sentihood_strict_acc(y_true, y_pred): """ Calculate "strict Acc" of aspect detection task of Sentihood. """ total_cases = int(len(y_true) / 4) true_cases = 0 for i in range(total_cases): if y_true[i * 4] != y_pred[i * 4]: continue if y_true[i * 4 + 1] != y_pred[i ...
def seconds2string(number): """ Convert time in seconds to 'HH:MM:SS' format Parameters ----------- number : float value in seconds Returns ------- time_string : str time in 'HH:MM:SS' format Example ------- >>> from ISPy.io import solarnet >>> solarnet...
def html_decode(the_string): """Given a string, change HTML escaped characters (&gt;) to regular characters (>). Args: the_string (str): String to decode. Returns: str: Decoded string. """ html_chars = ( ("'", "&#39;"), ('"', "&quot;"), (">", "&gt;"), ...